<?php 
session_start();
if (!isset($_SESSION['admin_id'])) {
    header("Location: login_admin.php");
    exit();
}

include '../includes/config.php'; 

// --- LOGIKA FILTER & PENCARIAN ---
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$date_start = $_GET['date_start'] ?? '';
$date_end = $_GET['date_end'] ?? '';

$conditions = [];
$params = [];

if (!empty($search)) {
    $conditions[] = "(kode_tracking LIKE ? OR terlapor LIKE ? OR jenis_dugaan LIKE ?)";
    $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%";
}
if (!empty($status_filter)) {
    $conditions[] = "status = ?";
    $params[] = $status_filter;
}
if (!empty($date_start) && !empty($date_end)) {
    $conditions[] = "DATE(created_at) BETWEEN ? AND ?";
    $params[] = $date_start; $params[] = $date_end;
}

$where_sql = count($conditions) > 0 ? " WHERE " . implode(" AND ", $conditions) : "";

try {
    // 1. Statistik (Total Global)
    $stats = $pdo->query("SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'Baru' THEN 1 ELSE 0 END) as baru,
        SUM(CASE WHEN status = 'Proses' OR status = 'Diproses' THEN 1 ELSE 0 END) as proses,
        SUM(CASE WHEN status = 'Selesai' THEN 1 ELSE 0 END) as selesai,
        SUM(CASE WHEN status = 'Ditolak' THEN 1 ELSE 0 END) as ditolak
    FROM laporan")->fetch();

    // 2. Query Tabel
    $query_str = "SELECT * FROM laporan $where_sql ORDER BY id DESC LIMIT 20"; // Limit 20 agar cepat loading
    $stmt = $pdo->prepare($query_str);
    $stmt->execute($params);
    $laporan = $stmt->fetchAll();

    // 3. Data Grafik 6 Bulan
    $label_bulan = []; $data_jumlah = [];
    for ($i = 5; $i >= 0; $i--) {
        $bulan = date('Y-m', strtotime("-$i months"));
        $label_bulan[] = date('M Y', strtotime("-$i months"));
        $st = $pdo->prepare("SELECT COUNT(*) FROM laporan WHERE DATE_FORMAT(created_at, '%Y-%m') = ?");
        $st->execute([$bulan]);
        $data_jumlah[] = $st->fetchColumn();
    }
} catch (PDOException $e) { die($e->getMessage()); }

include '../includes/header.php'; 
?>

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<style>
    body { background-color: #f3f4f6; font-family: 'Inter', sans-serif; }
    
    /* Judul Besar */
    .dashboard-title {
        font-family: 'Poppins', sans-serif;
        font-weight: 800;
        font-size: 3rem; /* Sangat Besar */
        color: #111827;
        letter-spacing: -2px;
        line-height: 1;
    }
    .dashboard-title .tangkis { color: #10b981; } /* Warna Hijau BPS */
    
    /* Alert Prioritas */
    .priority-alert {
        background: rgba(220, 53, 69, 0.05); /* Soft Red Background */
        border: 2px solid #dc3545; /* Red Border */
        border-radius: 16px;
        padding: 20px;
        box-shadow: 0 4px 15px rgba(220, 53, 69, 0.1);
    }

    /* Style lainnya (Tetap) */
    .card-stat { border: none; border-radius: 16px; background: #fff; transition: 0.3s; }
    .card-stat:hover { transform: translateY(-3px); box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); }
    .icon-box { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; }
    .filter-box { background: #fff; border-radius: 16px; border: none; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    .form-control-sm, .form-select-sm { border-radius: 8px; border: 1px solid #e5e7eb; }
    .badge-soft { padding: 5px 10px; border-radius: 6px; font-weight: 600; font-size: 0.7rem; }
    
    /* Style untuk Notifikasi Desktop */
    #notif-banner { display: none; position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px; }
</style>

<div id="notif-banner" class="alert alert-danger shadow-lg border-0 animate__animated animate__fadeInRight priority-alert p-3">
    <div class="d-flex align-items-center">
        <div class="icon-box bg-danger text-white me-3"><i class="bi bi-bell-fill"></i></div>
        <div>
            <h6 class="mb-0 fw-bold">PEMBERITAHUAN!</h6>
            <small>Ada laporan baru masuk. Harap didahulukan!</small>
        </div>
    </div>
</div>

<div class="container-fluid px-5 py-5">
    <div class="row mb-5 align-items-center">
        <div class="col-md-8">
            <small class="text-muted d-block text-uppercase fw-bold letter-spacing-1 mb-1">Pusat Kendali</small>
            <h1 class="dashboard-title mb-0">ADMIN <span class="tangkis">TANGKIS</span></h1>
            <p class="text-muted mt-1 mb-0">Halo, <span class="text-dark fw-semibold"><?= $_SESSION['admin_nama'] ?? 'Administrator' ?></span>. Sistem Informasi Tangkis BPS Lampung Timur.</p>
        </div>
        <div class="col-md-4 text-md-end mt-4 mt-md-0 d-flex gap-2 justify-content-md-end">
            <a href="export_excel.php" class="btn btn-white border bg-white btn-sm shadow-sm px-3">
                <i class="bi bi-file-earmark-excel me-2 text-success"></i>Export Excel
            </a>
            <a href="logout.php" class="btn btn-danger btn-sm px-3 fw-bold rounded-pill shadow-sm"><i class="bi bi-power me-1"></i>Keluar</a>
        </div>
    </div>

    <?php if ($stats['baru'] > 0): ?>
    <div class="row mb-5">
        <div class="col-12">
            <div class="priority-alert">
                <div class="d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center">
                        <div class="icon-box bg-danger bg-opacity-10 text-danger me-3 fs-3 p-3 h-100 w-100 rounded-circle">
                            <i class="bi bi-exclamation-octagon-fill"></i>
                        </div>
                        <div>
                            <h4 class="fw-bold text-danger mb-1">Perhatian Prioritas Utama!</h4>
                            <p class="text-muted mb-0">Ada <b class="text-danger fs-5"><?= $stats['baru'] ?></b> laporan baru yang memerlukan tindakan cepat. Harap didahulukan tindak lanjutnya!</p>
                        </div>
                    </div>
                    <a href="dashboard.php?status=Baru" class="btn btn-danger btn-sm px-4 fw-bold rounded-pill text-white shadow">Tampilkan Laporan Baru</a>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="row g-3 mb-5">
        <?php 
        $cards = [
            ['TOTAL', $stats['total'], 'bi-layers', 'bg-primary', 'text-primary', ''],
            ['BARU', $stats['baru'], 'bi-bell-fill', 'bg-danger', 'text-danger', 'border-start border-danger border-4'],
            ['PROSES', $stats['proses'], 'bi-arrow-repeat', 'bg-warning', 'text-warning', ''],
            ['SELESAI', $stats['selesai'], 'bi-check-all', 'bg-success', 'text-success', ''],
            ['DITOLAK', $stats['ditolak'], 'bi-x-circle-fill', 'bg-dark', 'text-dark', 'border-start border-dark border-4']
        ];
        foreach($cards as $c): ?>
        <div class="col">
            <div class="card card-stat shadow-sm p-3 <?= $c[5] ?>">
                <div class="d-flex align-items-center">
                    <div class="icon-box <?= $c[3] ?> bg-opacity-10 <?= $c[4] ?> me-2"><i class="<?= $c[2] ?>"></i></div>
                    <div>
                        <small class="text-muted d-block" style="font-size: 0.65rem; font-weight: 700;"><?= $c[0] ?></small>
                        <h4 class="fw-bold mb-0 fs-2"><?= $c[1] ?? 0 ?></h4>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="card filter-box p-3 mb-4 border-0 shadow-sm">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="small fw-bold text-muted">Cari Kata Kunci</label>
                <input type="text" name="search" class="form-control form-control-sm" placeholder="Kode / Nama / Dugaan..." value="<?= htmlspecialchars($search) ?>">
            </div>
            <div class="col-md-2">
                <label class="small fw-bold text-muted">Status</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">Semua Status</option>
                    <option value="Baru" <?= $status_filter == 'Baru' ? 'selected' : '' ?>>Baru</option>
                    <option value="Diproses" <?= $status_filter == 'Diproses' ? 'selected' : '' ?>>Diproses</option>
                    <option value="Selesai" <?= $status_filter == 'Selesai' ? 'selected' : '' ?>>Selesai</option>
                    <option value="Ditolak" <?= $status_filter == 'Ditolak' ? 'selected' : '' ?>>Ditolak</option>
                </select>
            </div>
            <div class="col-md-4">
                <label class="small fw-bold text-muted">Rentang Tanggal</label>
                <div class="input-group input-group-sm">
                    <input type="date" name="date_start" class="form-control" value="<?= $date_start ?>">
                    <span class="input-group-text bg-white">s/d</span>
                    <input type="date" name="date_end" class="form-control" value="<?= $date_end ?>">
                </div>
            </div>
            <div class="col-md-3 d-flex gap-1">
                <button type="submit" class="btn btn-primary btn-sm w-100 fw-bold shadow-sm">Filter</button>
                <a href="dashboard.php" class="btn btn-light border btn-sm w-50 fw-bold">Reset</a>
            </div>
        </form>
    </div>

    <div class="row g-4">
        <div class="col-lg-12 mb-4">
            <div class="card filter-box p-4 border-0 shadow-sm h-100">
                <h6 class="fw-bold mb-4">Tren Laporan Masuk (6 Bulan Terakhir)</h6>
                <canvas id="mainChart" style="max-height: 200px;"></canvas>
            </div>
        </div>

        <div class="col-lg-12">
            <div class="card filter-box overflow-hidden border-0 shadow-sm">
                <div class="table-responsive">
                    <table class="table table-hover mb-0 align-middle">
                        <thead class="table-light text-secondary">
                            <tr>
                                <th class="ps-4 py-3" style="font-size: 0.7rem;">TRACKING ID</th>
                                <th style="font-size: 0.7rem;">TERLAPOR / TGL</th>
                                <th style="font-size: 0.7rem;">DUGAAN</th>
                                <th style="font-size: 0.7rem;">STATUS</th>
                                <th class="text-end pe-4" style="font-size: 0.7rem;">AKSI</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($laporan) > 0): ?>
                                <?php foreach ($laporan as $row): 
                                    $st = $row['status'];
                                    $clr = match($st) { 'Baru' => 'danger', 'Diproses','Proses' => 'warning', 'Selesai' => 'success', 'Ditolak' => 'dark', default => 'secondary' };
                                ?>
                                <tr>
                                    <td class="ps-4 fw-bold text-primary">#<?= $row['kode_tracking'] ?></td>
                                    <td>
                                        <div class="fw-bold small"><?= htmlspecialchars($row['terlapor']) ?></div>
                                        <div class="text-muted" style="font-size: 0.65rem;"><?= date('d/m/Y', strtotime($row['created_at'])) ?></div>
                                    </td>
                                    <td class="text-muted small"><?= htmlspecialchars(substr($row['jenis_dugaan'], 0, 50)) ?>...</td>
                                    <td><span class="badge-soft bg-<?= $clr ?> bg-opacity-10 text-<?= $clr ?>"><?= strtoupper($st) ?></span></td>
                                    <td class="text-end pe-4">
                                        <a href="detail_laporan.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-primary rounded-pill px-3 fw-bold" style="font-size: 0.7rem;">DETAIL</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="text-center py-5 text-muted small">Tidak ada data ditemukan.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<audio id="notifSound" src="https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3" preload="auto"></audio>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // --- GRAFIK ---
    const ctx = document.getElementById('mainChart');
    if(ctx) {
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?= json_encode($label_bulan) ?>,
                datasets: [{ data: <?= json_encode($data_jumlah) ?>, borderColor: '#10b981', backgroundColor: 'rgba(16, 185, 129, 0.1)', fill: true, tension: 0.4, borderWidth: 4 }]
            },
            options: { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } }, x: { grid: { display: false } } } }
        });
    }

    // --- NOTIFIKASI REAL-TIME ---
    let currentNewReports = <?= (int)$stats['baru'] ?>;

    function checkNewReports() {
        fetch('get_stats_ajax.php')
            .then(response => response.json())
            .then(data => {
                const newCount = parseInt(data.baru);
                if (newCount > currentNewReports) {
                    // Coba putar suara (beberapa browser memblokir autplay)
                    document.getElementById('notifSound').play().catch(e => console.log("Audio play blocked, but notif shown"));
                    document.getElementById('notif-banner').style.display = 'block';
                    // Reload setelah 3 detik
                    setTimeout(() => { window.location.reload(); }, 3000);
                }
                currentNewReports = newCount;
            });
    }

    // Cek setiap 30 detik
    setInterval(checkNewReports, 30000);
</script>

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