<?php
/**
 * admin/index.php - Dashboard Utama Administrator
 * Dikembangkan oleh: Sikawarsito, S.Kom
 */
session_start();
include '../config/database.php';

// 1. Proteksi Halaman Admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login_page.php");
    exit;
}

// 2. Ambil Konfigurasi Sistem
// --- [TAMBAHAN: LOGIKA APPROVAL & MONITORING BROADCAST] ---
if (isset($_GET['action_broadcast']) && isset($_GET['user_id'])) {
    $uid = (int)$_GET['user_id'];
    $act = $_GET['action_broadcast'];
    
    if ($act === 'approve') {
        mysqli_query($conn, "UPDATE users SET status_broadcast = 'approved' WHERE id = $uid");
        $msg_broadcast = "<div class='alert alert-success mt-3'>Akses broadcast disetujui!</div>";
    } elseif ($act === 'reject') {
        mysqli_query($conn, "UPDATE users SET status_broadcast = 'none', email_guru = NULL WHERE id = $uid");
        $msg_broadcast = "<div class='alert alert-warning mt-3'>Pengajuan ditolak.</div>";
    } elseif ($act === 'revoke') {
        // Blokir Akses (Ubah ke status 'blocked' bukan 'none')
        mysqli_query($conn, "UPDATE users SET status_broadcast = 'blocked' WHERE id = $uid");
        $msg_broadcast = "<div class='alert alert-info mt-3'>Akses pengguna berhasil diblokir.</div>";
    } elseif ($act === 'unblock') {
        // Buka Blokir (Kembalikan ke 'approved')
        mysqli_query($conn, "UPDATE users SET status_broadcast = 'approved' WHERE id = $uid");
        $msg_broadcast = "<div class='alert alert-success mt-3'>Blokir dibuka, akses dikembalikan!</div>";
    } elseif ($act === 'delete_all') {
        // Hapus Total
        mysqli_query($conn, "DELETE FROM share_tugas WHERE user_id = $uid");
        mysqli_query($conn, "UPDATE users SET status_broadcast = 'none', email_guru = NULL WHERE id = $uid");
        $msg_broadcast = "<div class='alert alert-success mt-3'>Data tugas dihapus dan akses dicabut total.</div>";
    }
    header("Location: index.php");
    exit;
}

// 1. Ambil data antrean pengajuan (KOLOM 'nama' DIGANTI 'username')
$query_pending = mysqli_query($conn, "SELECT id, username, email_guru, created_at FROM users WHERE status_broadcast = 'pending' ORDER BY id ASC");
$total_pending = mysqli_num_rows($query_pending);

// 2. Ambil data pengguna yang Approved ATAU Blocked (KOLOM 'nama' DIGANTI 'username')
$query_active = mysqli_query($conn, "
    SELECT u.id, u.username, u.email_guru, u.status_broadcast,
           (SELECT COUNT(id) FROM share_tugas WHERE user_id = u.id) as total_tugas 
    FROM users u 
    WHERE u.status_broadcast IN ('approved', 'blocked')
    ORDER BY u.username ASC
");
$total_active = mysqli_num_rows($query_active);
// ----------------------------------------------

$query_cfg = mysqli_query($conn, "SELECT * FROM settings WHERE id = 1");
$cfg = mysqli_fetch_assoc($query_cfg);

// 4. Hitung Statistik Dasar
$total_siswa = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM users WHERE role != 'admin'"));
$total_chat  = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM chat_history"));
$user_pro    = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM users WHERE status_akun = 'pro' AND role != 'admin'"));
$chat_today  = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM chat_history WHERE DATE(created_at) = CURDATE()"));
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | <?= htmlspecialchars($cfg['nama_aplikasi'] ?? 'AI SMK') ?></title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root { --sidebar-w: 260px; --primary: #0d6efd; --bg-body: #f8fafc; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-body); color: #1e293b; }
        
        /* Sidebar Styling */
        .sidebar { width: var(--sidebar-w); height: 100vh; background: white; position: fixed; border-right: 1px solid #e2e8f0; padding: 24px; z-index: 1000; }
        .main-content { margin-left: var(--sidebar-w); padding: 40px; min-height: 100vh; }
        
        .nav-link { color: #64748b; padding: 12px 16px; border-radius: 12px; margin-bottom: 8px; font-weight: 600; transition: 0.3s; display: flex; align-items: center; text-decoration: none; }
        .nav-link i { font-size: 1.2rem; margin-right: 12px; }
        .nav-link:hover { background: #f1f5f9; color: var(--primary); }
        .nav-link.active { background: var(--primary); color: white; box-shadow: 0 4px 12px rgba(13, 110, 253, 0.2); }

        /* Card Styling */
        .stat-card { background: white; padding: 24px; border-radius: 20px; border: 1px solid #e2e8f0; transition: 0.3s; height: 100%; }
        .stat-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.03); }
        .icon-box { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; margin-bottom: 16px; }
        
        .mobile-header { display: none; background: white; padding: 15px 24px; border-bottom: 1px solid #e2e8f0; position: sticky; top: 0; z-index: 999; align-items: center; justify-content: space-between; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.5); z-index: 1040; transition: 0.3s; opacity: 0; }
        .sidebar-overlay.show { display: block; opacity: 1; }

        @media (max-width: 992px) {
            .sidebar { transform: translateX(-100%); transition: transform 0.3s ease-in-out; z-index: 1050; display: block; }
            .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 20px; }
            .mobile-header { display: flex; }
        }
    </style>
</head>
<body>

<div class="mobile-header">
    <div class="d-flex align-items-center">
        <div class="bg-primary p-2 rounded-3 me-3 text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
            <i class="bi bi-shield-lock-fill fs-5"></i>
        </div>
        <h5 class="fw-bold m-0">Admin Panel</h5>
    </div>
    <button class="btn btn-light border-0" id="sidebarToggle"><i class="bi bi-list fs-3"></i></button>
</div>

<div class="sidebar-overlay" id="sidebarOverlay"></div>

<aside class="sidebar" id="sidebarMenu">
    <div class="d-flex align-items-center mb-5 px-2 justify-content-between">
        <div class="d-flex align-items-center">
            <div class="bg-primary p-2 rounded-3 me-3 text-white">
                <i class="bi bi-shield-lock-fill fs-4"></i>
            </div>
            <h5 class="fw-bold m-0">Admin Panel</h5>
        </div>
        <button class="btn btn-light d-lg-none border-0 p-1" id="sidebarClose"><i class="bi bi-x-lg fs-5"></i></button>
    </div>

    <nav class="nav flex-column">
        <a class="nav-link active" href="index.php"><i class="bi bi-grid-fill"></i> Dashboard</a>
        <a class="nav-link" href="kelola_siswa.php"><i class="bi bi-people-fill"></i> Kelola Siswa</a>
        <a class="nav-link" href="kelola_live.php"><i class="bi bi-person-bounding-box"></i> Kelola Live</a>
        <a class="nav-link" href="../llm/admin/dashboard_llm.php"><i class="bi bi-cpu-fill"></i> LLM Dashboard</a>
        <a class="nav-link" href="monitoring_api.php"><i class="bi bi-activity"></i> NOC Center</a>
        <a class="nav-link" href="konfigurasi.php"><i class="bi bi-gear-fill"></i> Pengaturan</a>
        <a class="nav-link" href="statistik.php"><i class="bi bi-bar-chart-fill"></i> Statistik</a>
        <a class="nav-link" href="setting_akun.php"><i class="bi bi-person-badge-fill"></i> Setting Akun</a>
        <a class="nav-link" href="kelola_autokoding.php"><i class="bi bi-folder-x"></i> Kelola Autokoding</a>
        <hr class="my-4 text-muted">
        <a class="nav-link text-danger" href="../auth/logout.php" onclick="return confirm('Keluar dari panel admin?')">
            <i class="bi bi-box-arrow-left"></i> Logout
        </a>
    </nav>
</aside>

<main class="main-content">
    <header class="mb-5 mt-4 mt-lg-0 d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center gap-3">
        <div>
            <h3 class="fw-bold mb-1 text-dark">Ringkasan Sistem</h3>
            <p class="text-muted mb-0">Selamat datang kembali, <b><?= htmlspecialchars($_SESSION['nama'] ?? 'Admin') ?></b></p>
        </div>
        <div class="d-flex gap-2">
            <button onclick="fetch('get_traffic_stats.php', { method: 'POST', body: new URLSearchParams({'action': 'reset_all'}) }).then(() => { alert('Network Healed! Semua API Key berhasil di-reset.'); location.reload(); });" class="btn btn-danger rounded-pill shadow-sm fw-bold px-3 py-2">
                <i class="bi bi-bandaid me-1"></i> Heal Network
            </button>
            <span class="badge bg-white text-dark border p-2 px-3 rounded-pill shadow-sm d-flex align-items-center">
                <i class="bi bi-calendar3 me-2 text-primary"></i> <?= date('d M Y') ?>
            </span>
        </div>
    </header>

    <!-- API Alert Removed for Security -->

    <div class="row g-4 mb-5">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="icon-box bg-primary-subtle text-primary"><i class="bi bi-people fs-4"></i></div>
                <div class="text-muted small fw-bold">TOTAL SISWA</div>
                <h2 class="fw-bold mt-1"><?= $total_siswa ?></h2>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="icon-box bg-success-subtle text-success"><i class="bi bi-chat-left-text fs-4"></i></div>
                <div class="text-muted small fw-bold">TOTAL PERCAKAPAN</div>
                <h2 class="fw-bold mt-1"><?= $total_chat ?></h2>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card border-primary" style="background: linear-gradient(135deg, #0d6efd 0%, #004dc7 100%); color: white;">
                <div class="icon-box bg-white bg-opacity-25 text-white"><i class="bi bi-lightning-charge fs-4"></i></div>
                <div class="text-white text-opacity-75 small fw-bold text-uppercase">Chat Hari Ini</div>
                <h2 class="fw-bold mt-1 text-white"><?= $chat_today ?></h2>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="icon-box bg-warning-subtle text-warning"><i class="bi bi-award fs-4"></i></div>
                <div class="text-muted small fw-bold">AKUN PRO</div>
                <h2 class="fw-bold mt-1"><?= $user_pro ?></h2>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-md-8">
            <div class="card border-0 rounded-4 shadow-sm p-4 h-100">
                <h5 class="fw-bold mb-4"><i class="bi bi-cpu-fill me-2 text-primary"></i>Status Aplikasi</h5>
                <div class="table-responsive">
                    <table class="table table-borderless align-middle">
                        <tbody>
                            <tr>
                                <td width="50"><i class="bi bi-check-circle-fill text-success fs-4"></i></td>
                                <td>
                                    <div class="fw-bold">Database Server</div>
                                    <small class="text-muted">Koneksi genn5153_ai stabil</small>
                                </td>
                                <td class="text-end"><span class="badge bg-success-subtle text-success">Connected</span></td>
                            </tr>
                            <tr>
                                <td><i class="bi bi-shield-lock-fill <?= $cfg['maintenance_mode'] ? 'text-danger' : 'text-primary' ?> fs-4"></i></td>
                                <td>
                                    <div class="fw-bold">Mode Pemeliharaan</div>
                                    <small class="text-muted">Akses untuk pengguna umum</small>
                                </td>
                                <td class="text-end">
                                    <span class="badge <?= $cfg['maintenance_mode'] ? 'bg-danger' : 'bg-light text-dark' ?>">
                                        <?= $cfg['maintenance_mode'] ? 'Aktif' : 'Non-Aktif' ?>
                                    </span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card border-0 rounded-4 shadow-sm p-4 bg-dark text-white h-100">
                <h5 class="fw-bold mb-3">System Information</h5>
                <div class="mb-4">
                    <div class="small text-secondary text-uppercase mb-1">Nama Aplikasi</div>
                    <div class="fw-bold"><?= htmlspecialchars($cfg['nama_aplikasi'] ?? 'AI SMK Assistant') ?></div>
                </div>
                <div class="mb-4">
                    <div class="small text-secondary text-uppercase mb-1">Developer</div>
                    <div class="fw-bold text-info">Sikawarsito, S.Kom</div>
                </div>
                <a href="konfigurasi.php" class="btn btn-primary btn-sm w-100 rounded-pill py-2 mt-2 fw-bold">
                    <i class="bi bi-gear-fill me-2"></i>Edit Konfigurasi
                </a>
                <a href="konfigurasi.php" class="btn btn-outline-danger btn-sm w-100 rounded-pill py-2 mt-2 fw-bold">
                    <i class="bi bi-youtube me-2"></i>Setup YouTube API Key
                </a>
            </div>
        </div>
    </div>

    <div class="row mt-4 mb-5">
        <div class="col-12">
            <div class="card border-0 rounded-4 shadow-sm p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold mb-0">
                        <i class="bi bi-broadcast-pin text-success me-2"></i> Antrean Akses Broadcast
                    </h5>
                    <?php if($total_pending > 0): ?>
                        <span class="badge bg-danger rounded-pill"><?= $total_pending ?> Menunggu</span>
                    <?php endif; ?>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Username</th>
                                <th>Email Terdaftar (Guru/Belajar.id)</th>
                                <th>Tanggal Daftar Akun</th>
                                <th class="text-end">Tindakan Admin</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($total_pending > 0): ?>
                                <?php while($row_pengajuan = mysqli_fetch_assoc($query_pending)): ?>
                                <tr>
                                    <td class="fw-bold"><?= htmlspecialchars($row_pengajuan['username']) ?></td>
                                    <td><span class="badge bg-primary-subtle text-primary border border-primary-subtle px-3 py-2"><?= htmlspecialchars($row_pengajuan['email_guru']) ?></span></td>
                                    <td class="text-muted small"><?= date('d M Y, H:i', strtotime($row_pengajuan['created_at'])) ?></td>
                                    <td class="text-end">
                                        <a href="?action_broadcast=approve&user_id=<?= $row_pengajuan['id'] ?>" class="btn btn-sm btn-success rounded-pill px-3 fw-bold shadow-sm" onclick="return confirm('Setujui akses untuk guru ini?');">
                                            <i class="bi bi-check2"></i> Setujui
                                        </a>
                                        <a href="?action_broadcast=reject&user_id=<?= $row_pengajuan['id'] ?>" class="btn btn-sm btn-outline-danger rounded-pill px-3 ms-1 fw-bold" onclick="return confirm('Tolak pengajuan ini?');">
                                            <i class="bi bi-x-lg"></i> Tolak
                                        </a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4 fst-italic">
                                        Tidak ada antrean pengajuan akses Broadcast saat ini.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-5">
        <div class="col-12">
            <div class="card border-0 rounded-4 shadow-sm p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold mb-0">
                        <i class="bi bi-person-video3 text-primary me-2"></i> Monitor Pengguna Broadcast Aktif
                    </h5>
                    <span class="badge bg-primary rounded-pill"><?= $total_active ?> Aktif</span>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Username</th>
                                <th>Email (Guru/Belajar.id)</th>
                                <th class="text-center">Total Tugas Dibuat</th>
                                <th class="text-end">Tindakan Admin</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($total_active > 0): ?>
                                <?php while($row_aktif = mysqli_fetch_assoc($query_active)): ?>
                                <tr>
                                    <td>
                                        <div class="fw-bold"><?= htmlspecialchars($row_aktif['username']) ?></div>
                                        <?php if($row_aktif['status_broadcast'] == 'approved'): ?>
                                            <span class="badge bg-success" style="font-size: 10px;">Aktif</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger" style="font-size: 10px;">Diblokir</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><span class="badge bg-light text-dark border px-3 py-2"><?= htmlspecialchars($row_aktif['email_guru']) ?></span></td>
                                    <td class="text-center">
                                        <span class="badge bg-info text-dark rounded-circle p-2" style="width: 30px; height: 30px; display: inline-flex; align-items: center; justify-content: center;">
                                            <?= $row_aktif['total_tugas'] ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <?php if($row_aktif['status_broadcast'] == 'approved'): ?>
                                            <a href="?action_broadcast=revoke&user_id=<?= $row_aktif['id'] ?>" class="btn btn-sm btn-warning rounded-pill px-3 fw-bold shadow-sm" onclick="return confirm('Yakin ingin memblokir akses pengguna ini?');">
                                                <i class="bi bi-slash-circle"></i> Blokir
                                            </a>
                                        <?php else: ?>
                                            <a href="?action_broadcast=unblock&user_id=<?= $row_aktif['id'] ?>" class="btn btn-sm btn-success rounded-pill px-3 fw-bold shadow-sm" onclick="return confirm('Buka blokir dan berikan akses kembali?');">
                                                <i class="bi bi-unlock"></i> Buka Blokir
                                            </a>
                                        <?php endif; ?>

                                        <a href="?action_broadcast=delete_all&user_id=<?= $row_aktif['id'] ?>" class="btn btn-sm btn-danger rounded-pill px-3 ms-1 fw-bold shadow-sm" onclick="return confirm('PERINGATAN! Ini akan MENGHAPUS SEMUA DATA TUGAS pengguna ini. Lanjutkan?');">
                                            <i class="bi bi-trash3"></i> Hapus Total
                                        </a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4 fst-italic">
                                        Belum ada pengguna yang dikelola.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const sidebar = document.getElementById("sidebarMenu");
        const toggleBtn = document.getElementById("sidebarToggle");
        const closeBtn = document.getElementById("sidebarClose");
        const overlay = document.getElementById("sidebarOverlay");

        function toggleSidebar() {
            if(sidebar) sidebar.classList.toggle("show");
            if(overlay) overlay.classList.toggle("show");
        }

        if (toggleBtn) toggleBtn.addEventListener("click", toggleSidebar);
        if (closeBtn) closeBtn.addEventListener("click", toggleSidebar);
        if (overlay) overlay.addEventListener("click", toggleSidebar);
    });
</script>
</body>
</html>