<?php
// File: superadmin/superadmin_dashboard.php

// 1. Matikan Cache
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

include 'auth_check.php';
require_role(['superadmin']); 
require_once('../db.php'); 

$username = $_SESSION['username'] ?? 'Superadmin';

// --- 1. LOGIKA NOTIFIKASI ---
$sql_notif = "SELECT COUNT(*) as total_active FROM tasks WHERE status IN ('pending', 'in_progress')";
$res_notif = mysqli_query($conn, $sql_notif);
$notif_count = mysqli_fetch_assoc($res_notif)['total_active'];

// --- 2. AMBIL LIST PROJECT (Untuk Pilihan Export) ---
$all_projects_export = [];
$q_pro = mysqli_query($conn, "SELECT project_id, project_name FROM projects ORDER BY project_name ASC");
while($row = mysqli_fetch_assoc($q_pro)) { $all_projects_export[] = $row; }

// --- 3. LOGIKA FILTER & PAGINATION ---
$filter_type = isset($_GET['filter']) ? $_GET['filter'] : ''; 
$filter_project = isset($_GET['project_id']) ? $_GET['project_id'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';

$limit = 5; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$where_clauses = ["1=1"];
$params = [];
$types = "";

if ($filter_type == 'active') {
    $where_clauses[] = "t.status IN ('pending', 'in_progress')";
} else {
    if (!empty($filter_project)) { $where_clauses[] = "t.project_id = ?"; $params[] = $filter_project; $types .= "i"; }
    if (!empty($filter_status)) { $where_clauses[] = "t.status = ?"; $params[] = $filter_status; $types .= "s"; }
}

$where_sql = implode(" AND ", $where_clauses);

$sql_count = "SELECT COUNT(*) as total FROM tasks t WHERE $where_sql";
$stmt_count = $conn->prepare($sql_count);
if (!empty($params)) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $limit);
$stmt_count->close();

$sql = "
    SELECT 
        t.*, 
        p.project_name, 
        m.username AS member_name,
        c.username AS creator_name
    FROM tasks t
    JOIN projects p ON t.project_id = p.project_id
    JOIN users m ON t.assigned_to = m.id
    JOIN users c ON t.creator_id = c.id
    WHERE $where_sql
    ORDER BY 
        CASE WHEN t.status = 'completed' THEN 2 ELSE 1 END ASC,
        t.id DESC
    LIMIT ? OFFSET ?
";

$params[] = $limit;
$params[] = $offset;
$types .= "ii";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

// Ambil Project untuk Filter Dropdown
$projects = [];
$res_proj = mysqli_query($conn, "SELECT project_id, project_name FROM projects ORDER BY project_name");
while ($row = mysqli_fetch_assoc($res_proj)) { $projects[] = $row; }
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <title>Dashboard Superadmin</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #111; --accent: #39ff14; --bg: #f4f6f9; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); color: #333; padding-bottom: 50px; }

        /* HEADER FREEZE */
        .header {
            position: sticky; top: 0; z-index: 1000;
            background: linear-gradient(135deg, #1a1a1a, #2c3e50);
            color: white;
            padding: 20px 30px 25px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.2);
            border-bottom: 4px solid var(--accent);
            margin-bottom: 30px;
            display: flex; 
            justify-content: space-between;
            align-items: center;
        }

        .header-left .text-brand { font-size: 24px; font-weight: 800; color: white; text-transform: uppercase; letter-spacing: 0.5px; }
        .header-left .text-brand span { color: var(--accent); }
        .header-center { text-align: center; position: absolute; left: 50%; transform: translateX(-50%); }
        .header-center h1 { font-size: 28px; font-weight: 700; margin: 0; }
        .header-center p { font-size: 14px; opacity: 0.9; margin: 0; }
        .header-right { display: flex; align-items: center; gap: 20px; z-index: 1001; }

        /* LONCENG, EXPORT & LOGOUT */
        .notif-wrapper { position: relative; cursor: pointer; display: flex; align-items: center; text-decoration: none; }
        .icon-bell { width: 28px; height: 28px; fill: white; transition: 0.2s; }
        .notif-wrapper.active .icon-bell { fill: var(--accent); filter: drop-shadow(0 0 5px var(--accent)); }
        .notif-wrapper:hover .icon-bell { transform: scale(1.1); }
        .notif-badge { position: absolute; top: -5px; right: -5px; background-color: #ff3333; color: white; font-size: 10px; font-weight: 700; padding: 2px 6px; border-radius: 50px; border: 2px solid #2c3e50; }
        
        .btn-logout-top { background-color: #ff3333; color: white; padding: 10px 25px; border-radius: 50px; text-decoration: none; font-weight: 700; font-size: 13px; border: 2px solid white; box-shadow: 0 4px 10px rgba(0,0,0,0.3); transition: 0.3s; }
        .btn-logout-top:hover { background-color: white; color: #ff3333; }

        /* TOMBOL EXPORT HIJAU */
        .btn-export-top { 
            background-color: #2ecc71; color: white; padding: 10px 20px; border-radius: 50px; 
            text-decoration: none; font-weight: 700; font-size: 13px; border: 2px solid #27ae60; 
            cursor: pointer; display: flex; align-items: center; gap: 5px; box-shadow: 0 4px 10px rgba(46, 204, 113, 0.3);
        }
        .btn-export-top:hover { background-color: #27ae60; transform: translateY(-2px); }

        /* MENU GRID */
        .container { max-width: 1200px; margin: 0 auto; padding: 0 20px; }
        .menu-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 40px; }
        .menu-card { background: white; padding: 25px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); border-left: 5px solid #333; transition: 0.2s; }
        .menu-card:hover { transform: translateY(-5px); }
        .menu-card h3 { font-size: 20px; margin-bottom: 15px; }
        .btn { text-decoration: none; padding: 10px 15px; border-radius: 8px; font-size: 14px; font-weight: 600; background-color: #f0f0f0; color: #333; display: inline-block; margin-right: 5px; margin-bottom: 5px; }
        .btn:hover { background-color: #333; color: var(--accent); }

        /* MONITORING & FILTER */
        .monitoring-section { background: white; padding: 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
        .section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 2px solid #eee; padding-bottom: 15px; }
        .section-title { font-size: 24px; font-weight: 700; margin: 0; }
        .filter-form { background: #f8f9fa; padding: 15px; border-radius: 10px; display: flex; gap: 15px; align-items: center; flex-wrap: wrap; margin-bottom: 20px; }
        .filter-form select { padding: 8px; border-radius: 5px; border: 1px solid #ddd; }
        .btn-filter { background: #333; color: white; border: none; padding: 8px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; }
        .reset-filter { font-size: 13px; color: #d32f2f; font-weight: 600; text-decoration: none; }

        /* TABLE */
        .table-responsive { overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; }
        th { background: #333; color: white; padding: 15px; text-align: left; }
        td { padding: 15px; border-bottom: 1px solid #eee; }
        .badge { padding: 6px 12px; border-radius: 50px; font-size: 12px; font-weight: 700; display: inline-block; }
        .bg-pending { background-color: #fffbeb; color: #b45309; } .bg-in_progress { background-color: #eff6ff; color: #1d4ed8; } .bg-completed { background-color: #ecfdf5; color: #047857; }
        .btn-detail { text-decoration: none; color: white; background: #007bff; padding: 5px 10px; border-radius: 5px; font-size: 12px; font-weight: 600; margin-right: 5px; }
        .btn-delete { text-decoration: none; color: white; background: #d32f2f; padding: 5px 10px; border-radius: 5px; font-size: 12px; font-weight: 600; }
        .pagination { margin-top: 30px; text-align: center; }
        .page-link { display: inline-block; padding: 8px 14px; margin: 0 4px; border: 1px solid #ddd; color: #333; text-decoration: none; border-radius: 6px; }
        .page-link.active { background-color: #333; color: white; }

        /* MODAL POPUP */
        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); align-items: center; justify-content: center; }
        .modal-content { background-color: #fff; padding: 30px; border-radius: 15px; width: 90%; max-width: 400px; position: relative; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.3); animation: slideDown 0.3s ease; }
        @keyframes slideDown { from {transform: translateY(-50px); opacity: 0;} to {transform: translateY(0); opacity: 1;} }
        .close-btn { position: absolute; top: 15px; right: 20px; font-size: 24px; cursor: pointer; color: #999; }
        .form-select { width: 100%; padding: 12px; margin: 15px 0; border: 2px solid #eee; border-radius: 8px; font-size: 14px; }
        .btn-download { background: #2ecc71; color: white; border: none; padding: 12px 25px; border-radius: 8px; font-weight: bold; cursor: pointer; width: 100%; font-size: 16px; } .btn-download:hover { background: #27ae60; }
    </style>
</head>
<body>

    <div id="exportModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal()">&times;</span>
            <h2 style="margin-top:0; color:#333;">📥 Export ke Excel</h2>
            <p style="color:#666; font-size:14px;">Pilih project yang ingin di-download datanya.</p>
            
            <form action="export_excel.php" method="POST">
                <select name="project_id" class="form-select" required>
                    <option value="">-- Pilih Project --</option>
                    <?php foreach ($all_projects_export as $p): ?>
                        <option value="<?php echo $p['project_id']; ?>"><?php echo htmlspecialchars($p['project_name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="btn-download">Download .XLS</button>
            </form>
        </div>
    </div>

    <div class="header">
        <div class="header-left">
            <div class="text-brand">TASK <span>MANAGEMENT</span></div>
        </div>
        
        <div class="header-center">
            <h1>👋 Dashboard Superadmin</h1>
            <p>Selamat datang, <strong><?php echo htmlspecialchars($username); ?></strong>.</p>
        </div>
        
        <div class="header-right">
            <button onclick="openModal()" class="btn-export-top">📥 Export</button>

            <a href="superadmin_dashboard.php?filter=active" class="notif-wrapper <?php echo ($filter_type == 'active') ? 'active' : ''; ?>" title="Lihat Tugas Berjalan">
                <svg class="icon-bell" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12.02 24c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm10-6v-5.5c0-3.07-2.13-5.64-5-6.32V6c0-2.76-2.24-5-5-5s-5 2.24-5 5v.18c-2.87.68-5 3.25-5 6.32V18l-2 2v1h24v-1l-2-2z"/></svg>
                <?php if ($notif_count > 0): ?><span class="notif-badge"><?php echo $notif_count; ?></span><?php endif; ?>
            </a>
            <a href="../logout.php" class="btn-logout-top">LOGOUT</a>
        </div>
    </div>

    <div class="container">
        
        <div class="menu-grid">
            <div class="menu-card" style="border-left-color: #2196F3;">
                <h3>👥 User</h3>
                <a href="superadmin_create_user.php" class="btn">➕ Buat</a>
                <a href="superadmin_list_user.php" class="btn">📋 List</a>
            </div>
            
            <div class="menu-card" style="border-left-color: #FF9800;">
                <h3>🏗️ Project</h3>
                <a href="superadmin_create_project.php" class="btn">➕ Buat</a>
                <a href="superadmin_list_project.php" class="btn">📋 List</a>
            </div>

            <div class="menu-card" style="border-left-color: #E91E63;">
                <h3>📝 Task</h3>
                <a href="superadmin_create_task.php" class="btn">➕ Buat</a>
            </div>
        </div>

        <div class="monitoring-section">
            <div class="section-header">
                <div class="section-title">
                    <?php if ($filter_type == 'active'): ?>⏳ Tugas Berjalan<?php else: ?>📊 Monitoring Real-Time<?php endif; ?>
                </div>
                <?php if ($filter_type == 'active'): ?><a href="superadmin_dashboard.php" class="reset-filter">❌ Reset Filter</a><?php endif; ?>
            </div>

            <?php if ($filter_type != 'active'): ?>
            <form method="GET" class="filter-form">
                <select name="project_id"><option value="">-- Semua Project --</option><?php foreach ($projects as $p): ?><option value="<?php echo $p['project_id']; ?>"><?php echo htmlspecialchars($p['project_name']); ?></option><?php endforeach; ?></select>
                <select name="status"><option value="">-- Semua Status --</option><option value="pending">Pending</option><option value="in_progress">In Progress</option><option value="completed">Completed</option></select>
                <button type="submit" class="btn-filter">Filter</button>
            </form>
            <?php endif; ?>

            <div class="table-responsive">
                <table width="100%">
                    <thead><tr><th>Project</th><th>Judul</th><th>Penerima</th><th>Deadline</th><th>Status</th><th>Aksi</th></tr></thead>
                    <tbody>
                        <?php if ($result->num_rows > 0): while ($row = $result->fetch_assoc()): $clean = strtolower(trim($row['status'] ?? '')); if(empty($clean)) $clean='pending'; ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['project_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['title']); ?></td>
                            <td><?php echo htmlspecialchars($row['member_name']); ?></td>
                            <td style="color:#d32f2f;"><?php echo $row['due_date']; ?></td>
                            <td><span class="badge bg-<?php echo $clean; ?>"><?php echo strtoupper(str_replace('_',' ',$clean)); ?></span></td>
                            <td>
                                <a href="superadmin_view_task.php?task_id=<?php echo $row['id']; ?>" class="btn-detail">Detail</a>
                                <a href="superadmin_delete_task.php?id=<?php echo $row['id']; ?>" onclick="return confirm('Hapus?')" class="btn-delete">Hapus</a>
                            </td>
                        </tr>
                        <?php endwhile; else: ?><tr><td colspan="6" style="text-align:center; padding:30px; color:#999;">Tidak ada data.</td></tr><?php endif; ?>
                    </tbody>
                </table>
                
                <div class="pagination">
                    <?php 
                        $link_filter = "";
                        if ($filter_type == 'active') $link_filter = "&filter=active";
                        elseif ($filter_project || $filter_status) $link_filter = "&project_id=$filter_project&status=$filter_status";
                    ?>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <a href="?page=<?php echo $i . $link_filter; ?>" class="page-link <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                    <?php endfor; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        function openModal() { document.getElementById('exportModal').style.display = 'flex'; }
        function closeModal() { document.getElementById('exportModal').style.display = 'none'; }
        
        // Tutup modal kalau klik di luar kotak putih
        window.onclick = function(event) {
            if (event.target == document.getElementById('exportModal')) {
                closeModal();
            }
        }
    </script>

</body>
</html>