<?php
// sekretaris/kontak/index.php
$pageTitle = 'Kelola Pesan Kontak';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya sekretaris
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'sekretaris') {
    // Redirect ke halaman login jika belum login atau bukan sekretaris
    setFlash('login_required', 'Anda harus login sebagai sekretaris untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Handle aksi delete jika ada
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = $_GET['id'];
    
    // Hapus pesan kontak dari database
    $db->query("DELETE FROM kontak WHERE id = :id");
    $db->bind(':id', $id);
    
    if ($db->execute()) {
        // Log aktivitas
        logActivity('Menghapus pesan kontak', 'kontak', $id, 'Sekretaris menghapus pesan kontak dengan id: ' . $id);
        
        setFlash('kontak', 'Pesan kontak berhasil dihapus', 'success');
    } else {
        setFlash('kontak', 'Pesan kontak gagal dihapus', 'danger');
    }
    
    // Redirect ke halaman kontak
    header('Location: ' . SITE_URL . '/sekretaris/kontak/index.php');
    exit;
}

// Handle aksi mark as read
if (isset($_GET['action']) && $_GET['action'] == 'mark_read' && isset($_GET['id'])) {
    $id = $_GET['id'];
    
    // Update status pesan
    $db->query("UPDATE kontak SET is_read = 1 WHERE id = :id");
    $db->bind(':id', $id);
    
    if ($db->execute()) {
        // Log aktivitas
        logActivity('Menandai pesan kontak sebagai dibaca', 'kontak', $id, 'Sekretaris menandai pesan kontak sebagai dibaca dengan id: ' . $id);
        
        setFlash('kontak', 'Pesan kontak berhasil ditandai sebagai dibaca', 'success');
    } else {
        setFlash('kontak', 'Gagal menandai pesan kontak sebagai dibaca', 'danger');
    }
    
    // Redirect ke halaman kontak
    header('Location: ' . SITE_URL . '/sekretaris/kontak/index.php');
    exit;
}

// Handle aksi mark all as read
if (isset($_GET['action']) && $_GET['action'] == 'mark_all_read') {
    // Update semua pesan yang belum dibaca
    $db->query("UPDATE kontak SET is_read = 1 WHERE is_read = 0");
    
    if ($db->execute()) {
        // Log aktivitas
        logActivity('Menandai semua pesan kontak sebagai dibaca', 'kontak', null, 'Sekretaris menandai semua pesan kontak sebagai dibaca');
        
        setFlash('kontak', 'Semua pesan kontak berhasil ditandai sebagai dibaca', 'success');
    } else {
        setFlash('kontak', 'Gagal menandai semua pesan kontak sebagai dibaca', 'danger');
    }
    
    // Redirect ke halaman kontak
    header('Location: ' . SITE_URL . '/sekretaris/kontak/index.php');
    exit;
}

// Pagination
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 10;
$offset = ($current_page - 1) * $limit;

// Filter & Search
$search = isset($_GET['search']) ? $_GET['search'] : '';
$filter = isset($_GET['filter']) ? $_GET['filter'] : '';

// Query untuk menghitung total pesan kontak
$query_count = "SELECT COUNT(*) as total FROM kontak WHERE 1=1";
$query_params = [];

if (!empty($search)) {
    $query_count .= " AND (nama LIKE :search OR email LIKE :search OR subjek LIKE :search OR pesan LIKE :search)";
    $query_params[':search'] = "%$search%";
}

if ($filter === 'unread') {
    $query_count .= " AND is_read = 0";
} elseif ($filter === 'read') {
    $query_count .= " AND is_read = 1";
}

$db->query($query_count);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$total_rows = $db->single()->total;
$total_pages = ceil($total_rows / $limit);

// Query untuk mengambil data pesan kontak
$query = "SELECT * FROM kontak WHERE 1=1";

if (!empty($search)) {
    $query .= " AND (nama LIKE :search OR email LIKE :search OR subjek LIKE :search OR pesan LIKE :search)";
}

if ($filter === 'unread') {
    $query .= " AND is_read = 0";
} elseif ($filter === 'read') {
    $query .= " AND is_read = 1";
}

$query .= " ORDER BY created_at DESC LIMIT :offset, :limit";

$db->query($query);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$db->bind(':offset', $offset, PDO::PARAM_INT);
$db->bind(':limit', $limit, PDO::PARAM_INT);
$kontak_list = $db->resultSet();

// Hitung jumlah pesan yang belum dibaca
$db->query("SELECT COUNT(*) as count FROM kontak WHERE is_read = 0");
$unread_count = $db->single()->count;

// Include header
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/sekretaris/dashboard.php">
                            <i class="fas fa-tachometer-alt me-2"></i>
                            Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/sekretaris/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/sekretaris/berita/index.php">
                            <i class="fas fa-newspaper me-2"></i>
                            Berita Kegiatan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/sekretaris/kontak/index.php">
                            <i class="fas fa-envelope me-2"></i>
                            Pesan Kontak
                            <?php if ($unread_count > 0): ?>
                                <span class="badge bg-danger rounded-pill ms-1"><?= $unread_count ?></span>
                            <?php endif; ?>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/sekretaris/profil/index.php">
                            <i class="fas fa-user-circle me-2"></i>
                            Profil Saya
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/auth/logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i>
                            Logout
                        </a>
                    </li>
                </ul>
                
                <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
                    <span>Pintasan</span>
                </h6>
                <ul class="nav flex-column mb-2">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>" target="_blank">
                            <i class="fas fa-external-link-alt me-2"></i>
                            Lihat Website
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Kelola Pesan Kontak</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <?php if ($unread_count > 0): ?>
                        <a href="<?= SITE_URL ?>/sekretaris/kontak/index.php?action=mark_all_read" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-envelope-open me-1"></i> Tandai Semua Dibaca
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Filter & Search -->
            <div class="card mb-4">
                <div class="card-body">
                    <form action="" method="get" class="row g-3">
                        <div class="col-md-6">
                            <label for="search" class="form-label">Cari</label>
                            <input type="text" class="form-control" id="search" name="search" placeholder="Cari nama, email, subjek, atau pesan..." value="<?= $search ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="filter" class="form-label">Filter</label>
                            <select class="form-select" id="filter" name="filter">
                                <option value="" <?= $filter === '' ? 'selected' : '' ?>>Semua Pesan</option>
                                <option value="unread" <?= $filter === 'unread' ? 'selected' : '' ?>>Belum Dibaca</option>
                                <option value="read" <?= $filter === 'read' ? 'selected' : '' ?>>Sudah Dibaca</option>
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">Filter</button>
                            <a href="<?= SITE_URL ?>/sekretaris/kontak/index.php" class="btn btn-secondary">Reset</a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Tabel Pesan Kontak -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th scope="col" width="5%">#</th>
                                    <th scope="col" width="15%">Nama</th>
                                    <th scope="col" width="15%">Email</th>
                                    <th scope="col" width="15%">Subjek</th>
                                    <th scope="col">Pesan</th>
                                    <th scope="col" width="15%">Tanggal</th>
                                    <th scope="col" width="10%">Status</th>
                                    <th scope="col" width="10%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($kontak_list)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center py-4">Tidak ada pesan kontak</td>
                                    </tr>
                                <?php else: ?>
                                    <?php $no = $offset + 1; ?>
                                    <?php foreach ($kontak_list as $kontak): ?>
                                        <tr class="<?= $kontak->is_read ? '' : 'table-active' ?>">
                                            <th scope="row"><?= $no++ ?></th>
                                            <td><?= $kontak->nama ?></td>
                                            <td><?= $kontak->email ?></td>
                                            <td><?= $kontak->subjek ?></td>
                                            <td><?= potongTeks($kontak->pesan, 50) ?></td>
                                            <td><?= date('d/m/Y H:i', strtotime($kontak->created_at)) ?></td>
                                            <td>
                                                <?php if ($kontak->is_read): ?>
                                                    <span class="badge bg-success">Dibaca</span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger">Belum Dibaca</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/sekretaris/kontak/detail.php?id=<?= $kontak->id ?>" class="btn btn-sm btn-primary mb-1 w-100">
                                                    <i class="fas fa-eye"></i> Detail
                                                </a>
                                                <a href="<?= SITE_URL ?>/sekretaris/kontak/index.php?action=delete&id=<?= $kontak->id ?>" class="btn btn-sm btn-danger w-100" onclick="return confirm('Yakin ingin menghapus pesan ini?')">
                                                    <i class="fas fa-trash"></i> Hapus
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?= ($current_page <= 1) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/sekretaris/kontak/index.php?page=<?= $current_page - 1 ?><?= !empty($search) ? '&search=' . $search : '' ?><?= !empty($filter) ? '&filter=' . $filter : '' ?>">Previous</a>
                                </li>
                                
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?= ($current_page == $i) ? 'active' : '' ?>">
                                        <a class="page-link" href="<?= SITE_URL ?>/sekretaris/kontak/index.php?page=<?= $i ?><?= !empty($search) ? '&search=' . $search : '' ?><?= !empty($filter) ? '&filter=' . $filter : '' ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/sekretaris/kontak/index.php?page=<?= $current_page + 1 ?><?= !empty($search) ? '&search=' . $search : '' ?><?= !empty($filter) ? '&filter=' . $filter : '' ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<?php require_once '../../includes/footer.php'; ?>