<?php
/**
 * admin/statistik.php - Enhanced Monitoring Center
 * Fitur: Filter Limit, Search, & Detail Modal Fix (Disesuaikan tanpa kolom 'nama')
 * Developer: Sikawarsito, S.Kom
 */
session_start();
include '../config/database.php';

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

// --- LOGIKA HAPUS RIWAYAT ---
$msg_hapus = "";
if (isset($_POST['hapus_riwayat'])) {
    $target_status = mysqli_real_escape_string($conn, $_POST['target_status']);
    $query_del = "DELETE h FROM chat_history h INNER JOIN users u ON h.user_id = u.id WHERE u.status_akun = '$target_status'";
    if (mysqli_query($conn, $query_del)) {
        $jml = mysqli_affected_rows($conn);
        $msg_hapus = "<div class='alert alert-success border-0 shadow-sm'>Berhasil menghapus $jml riwayat akun $target_status!</div>";
    }
}

// --- LOGIKA FILTER & SEARCH ---
$limit = isset($_GET['limit']) ? $_GET['limit'] : '100';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

$sql_limit = ($limit == 'all') ? "" : "LIMIT $limit";
// UBAH: Pencarian menggunakan username, email_guru, atau user_message
$sql_search = (!empty($search)) ? "WHERE u.username LIKE '%$search%' OR u.email_guru LIKE '%$search%' OR h.user_message LIKE '%$search%'" : "";

// Ambil riwayat chat dengan join (UBAH: select username dan email_guru)
$query_stats = mysqli_query($conn, "
    SELECT h.*, u.username, u.email_guru, u.role, u.status_akun 
    FROM chat_history h 
    LEFT JOIN users u ON h.user_id = u.id 
    $sql_search
    ORDER BY h.id DESC 
    $sql_limit
");
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Statistik AI | Admin Control</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">
    <style>
        body { background: #f8fafc; font-family: 'Inter', sans-serif; color: #1e293b; }
        .card-table { border: none; border-radius: 24px; box-shadow: 0 10px 30px rgba(0,0,0,0.04); }
        .table thead { background: #f1f5f9; color: #64748b; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; }
        .badge-free { background: #fee2e2; color: #991b1b; }
        .badge-pro { background: #dcfce7; color: #166534; }
        .msg-preview { max-width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; color: #2563eb; font-weight: 500; }
        .filter-section { background: white; padding: 20px; border-radius: 20px; margin-bottom: 25px; border: 1px solid #e2e8f0; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-1">Monitoring Interaksi AI</h3>
            <p class="text-muted mb-0">Total terlihat: <b><?= mysqli_num_rows($query_stats) ?></b> percakapan</p>
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-danger rounded-pill px-4 fw-bold" data-bs-toggle="modal" data-bs-target="#modalHapus">
                <i class="bi bi-trash3 me-2"></i> Bersihkan
            </button>
            <a href="index.php" class="btn btn-outline-dark rounded-pill px-4 fw-bold">Kembali</a>
        </div>
    </div>

    <?= $msg_hapus ?>

    <div class="filter-section shadow-sm">
        <form method="GET" class="row g-3 align-items-end">
            <div class="col-md-4">
                <label class="form-label small fw-bold text-muted">Cari Pengguna / Pesan</label>
                <div class="input-group">
                    <span class="input-group-text bg-white border-end-0"><i class="bi bi-search"></i></span>
                    <input type="text" name="search" class="form-control border-start-0" placeholder="Ketik username atau chat..." value="<?= htmlspecialchars($search) ?>">
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-muted">Tampilkan Jumlah</label>
                <select name="limit" class="form-select">
                    <option value="50" <?= $limit == '50' ? 'selected' : '' ?>>50 Data Terbaru</option>
                    <option value="100" <?= $limit == '100' ? 'selected' : '' ?>>100 Data Terbaru</option>
                    <option value="500" <?= $limit == '500' ? 'selected' : '' ?>>500 Data Terbaru</option>
                    <option value="all" <?= $limit == 'all' ? 'selected' : '' ?>>Tampilkan Semua</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100 rounded-3 fw-bold">Terapkan</button>
            </div>
        </form>
    </div>

    <div class="card card-table bg-white p-4">
        <div class="table-responsive">
            <table class="table table-hover align-middle" id="tableStats">
                <thead>
                    <tr>
                        <th>Waktu</th>
                        <th>Pengguna</th>
                        <th>Layanan</th>
                        <th>Pertanyaan Siswa</th>
                        <th class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(mysqli_num_rows($query_stats) > 0): ?>
                        <?php while($row = mysqli_fetch_assoc($query_stats)): ?>
                        <tr>
                            <td class="small text-muted"><?= date('d M, H:i', strtotime($row['created_at'])) ?></td>
                            <td>
                                <div class="fw-bold text-dark">@<?= htmlspecialchars($row['username'] ?? 'User Dihapus') ?></div>
                                <?php if(!empty($row['email_guru'])): ?>
                                    <div class="text-muted small" style="font-size: 0.75rem;"><i class="bi bi-envelope"></i> <?= htmlspecialchars($row['email_guru']) ?></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge rounded-pill <?= $row['status_akun'] == 'pro' ? 'badge-pro' : 'badge-free' ?>">
                                    <?= strtoupper($row['status_akun'] ?? 'FREE') ?>
                                </span>
                            </td>
                            <td>
                                <div class="msg-preview" onclick="viewDetail('<?= base64_encode($row['user_message']) ?>', '<?= base64_encode($row['ai_response']) ?>')">
                                    <?= htmlspecialchars($row['user_message']) ?>
                                </div>
                            </td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-light border rounded-pill px-3 fw-bold" onclick="viewDetail('<?= base64_encode($row['user_message']) ?>', '<?= base64_encode($row['ai_response']) ?>')">
                                    <i class="bi bi-eye-fill me-1"></i> Detail
                                </button>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="text-center py-5 text-muted">Tidak ada data ditemukan.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalHapus" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 rounded-4 shadow">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold text-danger">Bersihkan Data</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <label class="form-label small fw-bold">Hapus Riwayat Berdasarkan Status:</label>
                    <select name="target_status" class="form-select mb-3" required>
                        <option value="free">Semua Akun FREE</option>
                        <option value="pro">Semua Akun PRO</option>
                    </select>
                    <div class="alert alert-warning border-0 small mb-0">
                        <i class="bi bi-exclamation-triangle-fill"></i> Data yang dihapus tidak dapat dikembalikan.
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" name="hapus_riwayat" class="btn btn-danger w-100 rounded-3 fw-bold">Konfirmasi Hapus</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalDetail" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 rounded-4 shadow-lg">
            <div class="modal-body p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold m-0 text-primary"><i class="bi bi-chat-left-dots-fill me-2"></i>Detail Analisa Chat</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="mb-4">
                    <label class="badge bg-primary px-3 mb-2 rounded-pill">Pertanyaan Siswa</label>
                    <div class="p-3 bg-light rounded-4 border small" id="text-user"></div>
                </div>
                
                <div>
                    <label class="badge bg-success px-3 mb-2 rounded-pill">Jawaban AI</label>
                    <div class="p-3 bg-light rounded-4 border small" id="text-ai" style="max-height: 400px; overflow-y: auto; white-space: pre-wrap;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Gunakan base64 untuk menghindari error karakter khusus saat passing data ke modal
    function viewDetail(userMsg, aiMsg) {
        $('#text-user').text(atob(userMsg));
        $('#text-ai').text(atob(aiMsg));
        $('#modalDetail').modal('show');
    }
</script>
</body>
</html>