<?php
/**
 * admin/riwayat_rpp.php - Panel Admin Workspace AI
 * Fitur: Manajemen Riwayat Dokumen RPP/Modul Ajar
 */
session_start();

// Cek akses admin (Sesuaikan dengan sistem keamanan Anda)
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Akses ditolak. Halaman ini khusus Admin.");
}

include '../config/database.php';

// Hapus Riwayat Spesifik (Jika ada request penghapusan)
if (isset($_GET['hapus_id'])) {
    $id_hapus = (int)$_GET['hapus_id'];
    $stmt_del = mysqli_prepare($conn, "DELETE FROM chat_history WHERE id = ?");
    mysqli_stmt_bind_param($stmt_del, "i", $id_hapus);
    mysqli_stmt_execute($stmt_del);
    header("Location: riwayat_rpp.php?pesan=dihapus");
    exit;
}

// Ambil data riwayat obrolan khusus yang panjang (indikasi hasil RPP) atau dari user tertentu
// Menggabungkan tabel chat_history dengan users untuk menampilkan nama pembuatnya
// KODE YANG DIPERBAIKI: Menghapus u.instansi dari query
$query = "
    SELECT ch.id, ch.session_id, ch.user_message AS topik, ch.ai_response, u.nama
    FROM chat_history ch
    JOIN users u ON ch.user_id = u.id
    WHERE LENGTH(ch.ai_response) > 500
    ORDER BY ch.id DESC
";
$result = mysqli_query($conn, $query);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manajemen Dokumen RPP - Admin Panel</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 { font-family: 'Inter', sans-serif; background-color: #f8fafc; color: #1e293b; }
        .admin-header { background: #ffffff; padding: 20px 30px; border-bottom: 1px solid #e2e8f0; margin-bottom: 30px; }
        .card-custom { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05); }
        .table-custom th { background-color: #f1f5f9; color: #475569; font-weight: 600; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #cbd5e1; padding: 15px; }
        .table-custom td { padding: 15px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        .btn-action { padding: 6px 12px; font-size: 13px; border-radius: 6px; font-weight: 500; }
        .badge-ai { background: #e0e7ff; color: #4f46e5; padding: 5px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; }
    </style>
</head>
<body>

<div class="admin-header d-flex justify-content-between align-items-center">
    <div>
        <h4 class="fw-bold mb-1 text-dark"><i class="bi bi-folder-fill text-primary me-2"></i> Arsip Dokumen RPP & Modul</h4>
        <p class="text-muted small mb-0">Kelola semua dokumen yang telah dihasilkan oleh sistem AI.</p>
    </div>
    <a href="dashboard.php" class="btn btn-outline-secondary btn-sm rounded-pill px-4 fw-bold">
        <i class="bi bi-arrow-left me-2"></i> Kembali ke Dashboard
    </a>
</div>

<div class="container-fluid px-4 mb-5">
    <?php if (isset($_GET['pesan']) && $_GET['pesan'] == 'dihapus'): ?>
        <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm" role="alert">
            <i class="bi bi-check-circle-fill me-2"></i> Dokumen berhasil dihapus dari database.
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="card card-custom overflow-hidden">
        <div class="table-responsive">
            <table class="table table-hover table-custom mb-0">
                <thead>
                    <tr>
                        <th width="5%">No</th>
                        <th width="20%">Nama Guru / Pengguna</th>
                        <th width="35%">Topik / Perintah Permintaan</th>
                        <th width="15%">Status</th>
                        <th width="25%" class="text-end">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $no = 1;
                    if (mysqli_num_rows($result) > 0):
                        while($row = mysqli_fetch_assoc($result)): 
                    ?>
                    <tr>
                        <td class="text-secondary fw-bold"><?= $no++ ?></td>
                        <td>
                            <div class="fw-bold text-dark"><?= htmlspecialchars($row['nama']) ?></div>
                            <small class="text-muted"><i class="bi bi-person-badge"></i> Pengguna</small>
                        </td>
                        <td>
                            <div class="text-truncate" style="max-width: 350px;" title="<?= htmlspecialchars($row['topik']) ?>">
                                <?= htmlspecialchars($row['topik']) ?>
                            </div>
                        </td>
                        <td><span class="badge-ai"><i class="bi bi-check-lg"></i> Berhasil di-Generate</span></td>
                        <td class="text-end">
                            <button class="btn btn-light border btn-action me-1 text-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#viewModal<?= $row['id'] ?>">
                                <i class="bi bi-eye"></i> Lihat
                            </button>
                            <a href="riwayat_rpp.php?hapus_id=<?= $row['id'] ?>" class="btn btn-danger btn-action shadow-sm" onclick="return confirm('Yakin ingin menghapus arsip dokumen ini secara permanen?');">
                                <i class="bi bi-trash"></i>
                            </a>
                        </td>
                    </tr>

                    <div class="modal fade" id="viewModal<?= $row['id'] ?>" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-xl modal-dialog-scrollable">
                            <div class="modal-content border-0 shadow-lg rounded-4">
                                <div class="modal-header bg-light pb-3">
                                    <h5 class="modal-title fw-bold">
                                        <i class="bi bi-file-earmark-text text-primary me-2"></i> Preview Dokumen: <?= htmlspecialchars($row['nama']) ?>
                                    </h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body p-4 bg-white render-markdown" style="font-size: 15px; color: #000;">
                                    <?= htmlspecialchars($row['ai_response']) ?>
                                </div>
                                <div class="modal-footer bg-light">
                                    <button type="button" class="btn btn-secondary rounded-pill px-4" data-bs-dismiss="modal">Tutup</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php 
                        endwhile; 
                    else: 
                    ?>
                    <tr>
                        <td colspan="5" class="text-center py-5 text-muted">
                            <i class="bi bi-inbox fs-1 d-block mb-3 text-light"></i>
                            Belum ada dokumen RPP/Modul yang dibuat.
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </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 src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
    // Merubah format Markdown AI menjadi HTML di dalam Modal Preview
    $(document).ready(function() {
        $('.render-markdown').each(function() {
            let rawText = $(this).text();
            let htmlText = marked.parse(rawText);
            $(this).html(htmlText);
            
            // Format tabel di panel admin agar terlihat rapi seperti di front-end
            $(this).find('table').addClass('table table-bordered table-sm mt-3');
            $(this).find('thead').addClass('table-light');
        });
    });
</script>
</body>
</html>