<?php
// =========================================================================
// admin/monitor_cache.php - XIEQA CACHE ENGINE MONITOR (ADMIN ONLY)
// Fitur: Statistik, Peringkat Teks, Manual Flush, Auto-Clear & PAGINATION
// Developer: Sikawarsito, S.Kom
// =========================================================================

session_start();
include '../../config/database.php';

// PROTEKSI MUTLAK: Hanya Admin yang boleh masuk
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login_page.php");
    exit;
}

// 1. Logika Hapus Cache Manual (Hapus Sekarang)
if (isset($_POST['clear_cache_now'])) {
    mysqli_query($conn, "TRUNCATE TABLE cache_llm");
    $_SESSION['msg_cache'] = "Tindakan berhasil! Seluruh data cache telah dikosongkan.";
    header("Location: monitor_cache.php");
    exit;
}

// 2. Logika Simpan Pengaturan Terjadwal
if (isset($_POST['save_schedule'])) {
    $hours = (int)$_POST['auto_clear_hours'];
    mysqli_query($conn, "UPDATE settings SET cache_auto_clear = $hours WHERE id = 1");
    $_SESSION['msg_cache'] = "Pengaturan jadwal pembersihan otomatis berhasil diperbarui!";
    header("Location: monitor_cache.php");
    exit;
}

// Notifikasi
$pesan = "";
if (isset($_SESSION['msg_cache'])) {
    $pesan = $_SESSION['msg_cache'];
    unset($_SESSION['msg_cache']);
}

// Ambil Pengaturan Jadwal Saat Ini
$q_cfg = mysqli_query($conn, "SELECT cache_auto_clear FROM settings WHERE id = 1");
$cfg = mysqli_fetch_assoc($q_cfg);
$current_schedule = $cfg['cache_auto_clear'] ?? 0;

// Ambil Statistik Keseluruhan
$q_stats = mysqli_query($conn, "SELECT COUNT(id) as total_saved, SUM(hit_count) as total_hits FROM cache_llm");
$stats = mysqli_fetch_assoc($q_stats);
$total_saved = $stats['total_saved'] ?? 0;
$total_hits = $stats['total_hits'] ?? 0;

// Kalkulasi estimasi penghematan
$estimasi_hemat = $total_hits * 15; 

// =========================================================================
// --- SISTEM PAGINATION (HALAMAN SELANJUTNYA) ---
// =========================================================================
$limit = 10; // Jumlah baris data yang ingin ditampilkan per halaman
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Hitung total halaman
$total_pages = ceil($total_saved / $limit);

// Ambil Data Peringkat Sesuai Halaman (LIMIT & OFFSET)
$q_ranking = mysqli_query($conn, "SELECT * FROM cache_llm ORDER BY hit_count DESC, last_used DESC LIMIT $limit OFFSET $offset");
// =========================================================================
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Xieqa Cache Monitor</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <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-color: #f0f4f9; font-family: 'Inter', sans-serif; }
        .card-premium { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.04); }
        .stat-box { background: #f8fafc; border-radius: 15px; padding: 20px; border: 1px solid #e2e8f0; border-left: 5px solid #1a73e8;}
        .table-keys th { background: #f8fafc; font-weight: 600; color: #64748b; font-size: 13px; text-transform: uppercase; }
        .badge-hit { background: #fee2e2; color: #ef4444; font-weight: bold; border-radius: 50px; padding: 5px 12px; }
        
        .text-truncate-2 { 
            display: -webkit-box; 
            -webkit-line-clamp: 2; 
            -webkit-box-orient: vertical; 
            overflow: hidden; 
            transition: all 0.3s ease;
        }
        
        .btn-readmore { 
            font-size: 12px; 
            font-weight: 700; 
            text-decoration: none; 
            cursor: pointer; 
            color: #1a73e8; 
            display: inline-block; 
            margin-top: 6px; 
            background: #e8f0fe;
            padding: 4px 10px;
            border-radius: 6px;
        }
        .btn-readmore:hover { background: #d2e3fc; color: #1557b0; }
        
        /* Modifikasi Pagination */
        .page-link { color: #1a73e8; border-radius: 8px; margin: 0 3px; border: 1px solid #e2e8f0; }
        .page-link:hover { background: #e8f0fe; color: #1557b0; }
        .page-item.disabled .page-link { background: #f8fafc; color: #94a3b8; border-color: #e2e8f0; }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-3">
            <h2 class="fw-bold m-0 text-dark">
                <i class="bi bi-database-fill-check text-success me-2"></i> Xieqa Cache Monitor
            </h2>
            <a href="dashboard_llm.php" class="btn btn-white border rounded-pill fw-bold text-secondary shadow-sm px-4 bg-white">
                <i class="bi bi-arrow-left me-1"></i> Kembali ke Pusat Kendali
            </a>
        </div>

        <?php if($pesan): ?>
            <div class="alert alert-success bg-white border border-success border-2 border-start-0 border-end-0 border-bottom-0 text-success fw-bold shadow-sm d-flex align-items-center rounded-4 p-3 mb-4">
                <i class="bi bi-check-circle-fill fs-4 me-3"></i> <div><?= $pesan ?></div>
            </div>
        <?php endif; ?>

        <div class="card-premium p-4 mb-4" style="background: linear-gradient(to right, #ffffff, #f8fafc);">
            <div class="row align-items-center">
                <div class="col-md-7 border-end">
                    <h5 class="fw-bold mb-3"><i class="bi bi-clock-history text-primary me-2"></i>Jadwal Pembersihan Otomatis (TTL)</h5>
                    <p class="text-secondary small mb-3">Sistem akan otomatis menghapus pertanyaan yang usianya lebih tua dari batas waktu yang ditentukan agar jawaban AI tidak "basi".</p>
                    <form method="POST" class="d-flex gap-2">
                        <select name="auto_clear_hours" class="form-select bg-white" style="max-width: 250px;">
                            <option value="0" <?= ($current_schedule == 0) ? 'selected' : '' ?>>Nonaktifkan (Jangan Hapus)</option>
                            <option value="12" <?= ($current_schedule == 12) ? 'selected' : '' ?>>Per 12 Jam</option>
                            <option value="24" <?= ($current_schedule == 24) ? 'selected' : '' ?>>Per 24 Jam (1 Hari)</option>
                            <option value="72" <?= ($current_schedule == 72) ? 'selected' : '' ?>>Per 72 Jam (3 Hari)</option>
                            <option value="168" <?= ($current_schedule == 168) ? 'selected' : '' ?>>Per 168 Jam (7 Hari)</option>
                        </select>
                        <button type="submit" name="save_schedule" class="btn btn-primary fw-bold px-4">Simpan</button>
                    </form>
                </div>
                <div class="col-md-5 ps-md-4 mt-4 mt-md-0 text-md-center">
                    <h5 class="fw-bold mb-3 text-danger"><i class="bi bi-trash3-fill me-2"></i>Hapus Paksa (Flush)</h5>
                    <p class="text-secondary small mb-3">Hapus seluruh data cache saat ini secara instan.</p>
                    <form method="POST">
                        <button type="submit" name="clear_cache_now" class="btn btn-danger fw-bold w-100 rounded-pill" onclick="return confirm('PERINGATAN!\n\nSeluruh ingatan cache akan dihapus permanen. Mesin harus membaca dari awal menggunakan API eksternal.\n\nLanjutkan?');">
                            <i class="bi bi-exclamation-triangle-fill me-1"></i> Kosongkan Cache Sekarang
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-md-4">
                <div class="stat-box">
                    <div class="text-secondary small fw-bold mb-1">DATA TERSIMPAN (KNOWLEDGE BASE)</div>
                    <h3 class="fw-bold m-0 text-dark"><?= number_format($total_saved) ?> <small class="fs-6 text-muted">Prompt</small></h3>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-box" style="border-left-color: #10b981;">
                    <div class="text-secondary small fw-bold mb-1">TOTAL CACHE HIT (API BYPASS)</div>
                    <h3 class="fw-bold m-0 text-dark"><?= number_format($total_hits) ?> <small class="fs-6 text-muted">Kali</small></h3>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-box" style="border-left-color: #f59e0b;">
                    <div class="text-secondary small fw-bold mb-1">ESTIMASI PENGHEMATAN API</div>
                    <h3 class="fw-bold m-0 text-dark">Rp <?= number_format($estimasi_hemat, 0, ',', '.') ?></h3>
                </div>
            </div>
        </div>

        <div class="card-premium p-4 mb-5">
            <h5 class="fw-bold mb-3"><i class="bi bi-bar-chart-fill text-primary me-2"></i>Peringkat Teks Terbaik (Top Ranked Queries)</h5>
            <div class="table-responsive mb-2">
                <table class="table table-hover align-middle table-keys" style="table-layout: fixed;">
                    <thead>
                        <tr>
                            <th width="5%">Rank</th>
                            <th width="35%">Pertanyaan User (Prompt)</th>
                            <th width="40%">Jawaban Internal (Xieqa Cache)</th>
                            <th width="10%" class="text-center">Total Hit</th>
                            <th width="10%">Terakhir Dipakai</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $no = $offset + 1; // Penomoran urut terus meski pindah halaman
                        if(mysqli_num_rows($q_ranking) > 0):
                            while($row = mysqli_fetch_assoc($q_ranking)): 
                        ?>
                        <tr>
                            <td class="fw-bold text-muted">#<?= $no++ ?></td>
                            <td class="align-top">
                                <div class="fw-bold text-dark text-truncate-2" id="prompt-<?= $row['id'] ?>" style="font-size: 14px; line-height: 1.5;">
                                    <?= nl2br(htmlspecialchars($row['prompt_text'])) ?>
                                </div>
                                <?php if(strlen($row['prompt_text']) > 80): ?>
                                    <a class="btn-readmore" onclick="toggleText('prompt-<?= $row['id'] ?>', this)">
                                        <i class="bi bi-chevron-down"></i> Detail
                                    </a>
                                <?php endif; ?>
                            </td>
                            <td class="align-top">
                                <div class="text-secondary text-truncate-2" id="reply-<?= $row['id'] ?>" style="font-size: 13px; line-height: 1.5;">
                                    <?= nl2br(htmlspecialchars($row['response_text'])) ?>
                                </div>
                                <?php if(strlen($row['response_text']) > 120): ?>
                                    <a class="btn-readmore" onclick="toggleText('reply-<?= $row['id'] ?>', this)">
                                        <i class="bi bi-chevron-down"></i> Detail
                                    </a>
                                <?php endif; ?>
                            </td>
                            <td class="text-center align-top"><span class="badge-hit"><i class="bi bi-fire"></i> <?= $row['hit_count'] ?>x</span></td>
                            <td class="text-muted small align-top"><?= date('d/m/Y H:i', strtotime($row['last_used'])) ?></td>
                        </tr>
                        <?php endwhile; else: ?>
                        <tr><td colspan="5" class="text-center py-4 text-muted">Belum ada data cache yang tersimpan.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-4 pt-3 border-top">
                <ul class="pagination justify-content-center mb-0">
                    <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                        <a class="page-link shadow-sm fw-bold" href="?page=<?= $page - 1 ?>">
                            <i class="bi bi-chevron-double-left"></i> Sebelumnya
                        </a>
                    </li>
                    
                    <li class="page-item disabled">
                        <span class="page-link text-dark fw-bold bg-light">Halaman <?= $page ?> dari <?= $total_pages ?></span>
                    </li>

                    <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                        <a class="page-link shadow-sm fw-bold" href="?page=<?= $page + 1 ?>">
                            Selanjutnya <i class="bi bi-chevron-double-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>

        </div>
    </div>

    <script>
        function toggleText(elementId, btn) {
            const el = document.getElementById(elementId);
            if (el.classList.contains('text-truncate-2')) {
                el.classList.remove('text-truncate-2');
                btn.innerHTML = '<i class="bi bi-chevron-up"></i> Tutup';
            } else {
                el.classList.add('text-truncate-2');
                btn.innerHTML = '<i class="bi bi-chevron-down"></i> Detail';
            }
        }
    </script>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>