<?php
/**
 * Project: Game Teka Teki Modern - Xieqa LLM Ecosystem
 * Developer: Sikawarsito, S.Kom
 * File: index.html (PHP Integrated)
 */

// Include DataStore Helper as per Mandatory Rules
include __DIR__ . '/helper/DataStore.php';

// Initialize Collection
$collection = 'teka_teki';
initData($collection, [
    [
        'id' => time(),
        'pertanyaan' => 'Apa yang selalu datang tapi tidak pernah sampai?',
        'jawaban' => 'Besok',
        'kategori' => 'Logika',
        'kesulitan' => 'Mudah',
        'tanggal' => date('Y-m-d H:i:s')
    ]
]);

// Handle Actions
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'save':
                $newData = [
                    'pertanyaan' => htmlspecialchars($_POST['pertanyaan']),
                    'jawaban' => htmlspecialchars($_POST['jawaban']),
                    'kategori' => $_POST['kategori'],
                    'kesulitan' => $_POST['kesulitan'],
                    'tanggal' => date('Y-m-d H:i:s')
                ];
                if (!empty($_POST['id'])) {
                    updateRecord($collection, $_POST['id'], $newData);
                } else {
                    addRecord($collection, $newData);
                }
                header("Location: " . $_SERVER['PHP_SELF']);
                exit;
            case 'delete':
                deleteRecord($collection, $_POST['id']);
                header("Location: " . $_SERVER['PHP_SELF']);
                exit;
        }
    }
}

// Load Data
$allData = loadData($collection);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game Teka Teki | Xieqa LLM</title>
    
    <!-- Fonts & Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Libraries -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        :root {
            --primary: #6366f1;
            --primary-hover: #4f46e5;
            --bg-light: #f8fafc;
            --bg-dark: #0f172a;
            --card-light: #ffffff;
            --card-dark: #1e293b;
            --text-light: #1e293b;
            --text-dark: #f1f5f9;
            --border-radius: 1rem;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        body {
            font-family: 'Outfit', sans-serif;
            background-color: var(--bg-light);
            color: var(--text-light);
            margin: 0;
            transition: var(--transition);
        }

        body.dark-mode {
            background-color: var(--bg-dark);
            color: var(--text-dark);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        /* Header Styles */
        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        .logo-area h1 {
            font-size: 1.8rem;
            font-weight: 700;
            background: linear-gradient(to right, var(--primary), #a855f7);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin: 0;
        }

        /* Card Styles */
        .glass-card {
            background: var(--card-light);
            border-radius: var(--border-radius);
            padding: 1.5rem;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(0, 0, 0, 0.05);
            margin-bottom: 2rem;
            transition: var(--transition);
        }

        .dark-mode .glass-card {
            background: var(--card-dark);
            border-color: rgba(255, 255, 255, 0.05);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3);
        }

        /* Form Styles */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }

        .input-group {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        label {
            font-weight: 500;
            font-size: 0.9rem;
        }

        input, select, textarea {
            padding: 0.75rem;
            border-radius: 0.5rem;
            border: 1px solid #e2e8f0;
            background: transparent;
            color: inherit;
            font-family: inherit;
            transition: var(--transition);
        }

        .dark-mode input, .dark-mode select, .dark-mode textarea {
            border-color: #334155;
        }

        input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2);
        }

        /* Button Styles */
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            border: none;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: var(--transition);
        }

        .btn-primary { background: var(--primary); color: white; }
        .btn-primary:hover { background: var(--primary-hover); transform: translateY(-2px); }
        
        .btn-outline { border: 1px solid var(--primary); color: var(--primary); background: transparent; }
        .btn-outline:hover { background: var(--primary); color: white; }

        .btn-danger { background: #ef4444; color: white; }
        .btn-danger:hover { background: #dc2626; }

        /* Table Styles */
        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        th {
            text-align: left;
            padding: 1rem;
            border-bottom: 2px solid #e2e8f0;
            font-weight: 600;
        }

        .dark-mode th { border-bottom-color: #334155; }

        td {
            padding: 1rem;
            border-bottom: 1px solid #e2e8f0;
        }

        .dark-mode td { border-bottom-color: #334155; }

        /* Badge Styles */
        .badge {
            padding: 0.25rem 0.75rem;
            border-radius: 1rem;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .badge-easy { background: #dcfce7; color: #166534; }
        .badge-medium { background: #fef9c3; color: #854d0e; }
        .badge-hard { background: #fee2e2; color: #991b1b; }

        /* Mobile Card View */
        .mobile-cards {
            display: none;
            grid-template-columns: 1fr;
            gap: 1rem;
        }

        @media (max-width: 768px) {
            .desktop-table { display: none; }
            .mobile-cards { display: grid; }
            header { flex-direction: column; gap: 1rem; text-align: center; }
        }

        /* Animations */
        .fade-in { animation: fadeIn 0.5s ease-in; }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Search & Filter Bar */
        .controls {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }

        .search-box {
            flex: 1;
            min-width: 250px;
            position: relative;
        }

        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
        }

        .search-box input {
            width: 100%;
            padding-left: 2.5rem;
            box-sizing: border-box;
        }

        /* Answer Reveal Logic */
        .answer-text {
            filter: blur(5px);
            transition: var(--transition);
            cursor: pointer;
            user-select: none;
        }

        .answer-text.revealed {
            filter: blur(0);
            color: var(--primary);
            font-weight: 600;
        }
    </style>
</head>
<body class="">

    <div class="container">
        <!-- Header -->
        <header class="animate__animated animate__fadeInDown">
            <div class="logo-area">
                <h1><i class="fas fa-brain"></i> Game Teka Teki</h1>
                <p style="font-size: 0.8rem; color: #94a3b8; margin-top: 5px;">Xieqa LLM Ecosystem v1.0</p>
            </div>
            <div class="actions">
                <button onclick="toggleDarkMode()" class="btn btn-outline" id="theme-toggle">
                    <i class="fas fa-moon"></i>
                </button>
                <button onclick="exportData()" class="btn btn-outline">
                    <i class="fas fa-file-export"></i> Export
                </button>
            </div>
        </header>

        <!-- Form Section -->
        <section class="glass-card animate__animated animate__fadeInUp">
            <h3 style="margin-top: 0;"><i class="fas fa-plus-circle"></i> Tambah / Edit Teka Teki</h3>
            <form id="mainForm" method="POST">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" id="form-id">
                
                <div class="form-grid">
                    <div class="input-group" style="grid-column: span 2;">
                        <label>Pertanyaan</label>
                        <textarea name="pertanyaan" id="form-pertanyaan" rows="2" placeholder="Masukkan teka-teki..." required></textarea>
                    </div>
                    <div class="input-group">
                        <label>Jawaban</label>
                        <input type="text" name="jawaban" id="form-jawaban" placeholder="Jawaban..." required>
                    </div>
                    <div class="input-group">
                        <label>Kategori</label>
                        <select name="kategori" id="form-kategori">
                            <option value="Logika">Logika</option>
                            <option value="Tebak-tebakan">Tebak-tebakan</option>
                            <option value="Matematika">Matematika</option>
                            <option value="Umum">Umum</option>
                        </select>
                    </div>
                    <div class="input-group">
                        <label>Kesulitan</label>
                        <select name="kesulitan" id="form-kesulitan">
                            <option value="Mudah">Mudah</option>
                            <option value="Sedang">Sedang</option>
                            <option value="Sulit">Sulit</option>
                        </select>
                    </div>
                    <div class="input-group" style="justify-content: flex-end; flex-direction: row; align-items: flex-end;">
                        <button type="button" onclick="resetForm()" class="btn btn-outline">Reset</button>
                        <button type="submit" class="btn btn-primary">Simpan Data</button>
                    </div>
                </div>
            </form>
        </section>

        <!-- Controls -->
        <div class="controls animate__animated animate__fadeIn">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" placeholder="Cari teka-teki atau jawaban..." onkeyup="filterData()">
            </div>
            <select id="filterKategori" onchange="filterData()" class="btn-outline" style="padding: 0.5rem; border-radius: 0.5rem;">
                <option value="">Semua Kategori</option>
                <option value="Logika">Logika</option>
                <option value="Tebak-tebakan">Tebak-tebakan</option>
                <option value="Matematika">Matematika</option>
            </select>
        </div>

        <!-- Data Display -->
        <div class="glass-card animate__animated animate__fadeIn">
            <!-- Desktop Table -->
            <div class="table-container desktop-table">
                <table>
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Pertanyaan</th>
                            <th>Jawaban (Klik)</th>
                            <th>Kategori</th>
                            <th>Kesulitan</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="dataTable">
                        <?php if (empty($allData)): ?>
                            <tr>
                                <td colspan="6" style="text-align: center; padding: 2rem; color: #94a3b8;">
                                    <i class="fas fa-folder-open" style="font-size: 2rem; display: block; margin-bottom: 1rem;"></i>
                                    Belum ada data teka-teki.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($allData as $index => $item): ?>
                                <tr class="data-row" data-category="<?= $item['kategori'] ?>">
                                    <td><?= $index + 1 ?></td>
                                    <td style="max-width: 300px;"><?= $item['pertanyaan'] ?></td>
                                    <td>
                                        <span class="answer-text" onclick="this.classList.toggle('revealed')">
                                            <?= $item['jawaban'] ?>
                                        </span>
                                    </td>
                                    <td><?= $item['kategori'] ?></td>
                                    <td>
                                        <span class="badge badge-<?= strtolower($item['kesulitan']) ?>">
                                            <?= $item['kesulitan'] ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div style="display: flex; gap: 0.5rem;">
                                            <button onclick='editData(<?= json_encode($item) ?>)' class="btn btn-outline" style="padding: 0.4rem 0.8rem;">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <form method="POST" onsubmit="return confirmDelete(event, this)">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                                <button type="submit" class="btn btn-danger" style="padding: 0.4rem 0.8rem;">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Mobile Cards -->
            <div class="mobile-cards" id="mobileCards">
                <?php foreach ($allData as $item): ?>
                    <div class="glass-card" style="margin-bottom: 1rem; border: 1px solid #e2e8f0;">
                        <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                            <span class="badge badge-<?= strtolower($item['kesulitan']) ?>"><?= $item['kategori'] ?></span>
                            <small style="color: #94a3b8;"><?= date('d/m/y', strtotime($item['tanggal'])) ?></small>
                        </div>
                        <p style="font-weight: 600; margin: 1rem 0;"><?= $item['pertanyaan'] ?></p>
                        <div style="background: #f1f5f9; padding: 0.75rem; border-radius: 0.5rem; margin-bottom: 1rem;" class="dark-mode-bg">
                            <small style="display: block; color: #64748b;">Jawaban:</small>
                            <span class="answer-text" onclick="this.classList.toggle('revealed')"><?= $item['jawaban'] ?></span>
                        </div>
                        <div style="display: flex; gap: 0.5rem;">
                            <button onclick='editData(<?= json_encode($item) ?>)' class="btn btn-outline" style="flex: 1;">Edit</button>
                            <form method="POST" onsubmit="return confirmDelete(event, this)" style="flex: 1;">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                <button type="submit" class="btn btn-danger" style="width: 100%;">Hapus</button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <script>
        // Dark Mode Toggle
        function toggleDarkMode() {
            document.body.classList.toggle('dark-mode');
            const isDark = document.body.classList.contains('dark-mode');
            localStorage.setItem('darkMode', isDark);
            document.getElementById('theme-toggle').innerHTML = isDark ? '<i class="fas fa-sun"></i>' : '<i class="fas fa-moon"></i>';
        }

        // Load Theme Preference
        if (localStorage.getItem('darkMode') === 'true') {
            document.body.classList.add('dark-mode');
            document.getElementById('theme-toggle').innerHTML = '<i class="fas fa-sun"></i>';
        }

        // Search & Filter Logic
        function filterData() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const categoryFilter = document.getElementById('filterKategori').value;
            const rows = document.querySelectorAll('.data-row');

            rows.forEach(row => {
                const text = row.innerText.toLowerCase();
                const category = row.getAttribute('data-category');
                const matchesSearch = text.includes(searchTerm);
                const matchesCategory = categoryFilter === "" || category === categoryFilter;

                row.style.display = (matchesSearch && matchesCategory) ? "" : "none";
            });
        }

        // Edit Data
        function editData(data) {
            document.getElementById('form-id').value = data.id;
            document.getElementById('form-pertanyaan').value = data.pertanyaan;
            document.getElementById('form-jawaban').value = data.jawaban;
            document.getElementById('form-kategori').value = data.kategori;
            document.getElementById('form-kesulitan').value = data.kesulitan;
            
            window.scrollTo({ top: 0, behavior: 'smooth' });
            
            Swal.fire({
                icon: 'info',
                title: 'Mode Edit Aktif',
                text: 'Silakan ubah data pada form di atas.',
                timer: 2000,
                showConfirmButton: false
            });
        }

        // Reset Form
        function resetForm() {
            document.getElementById('mainForm').reset();
            document.getElementById('form-id').value = '';
        }

        // Delete Confirmation
        function confirmDelete(e, form) {
            e.preventDefault();
            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: "Data teka-teki ini akan dihapus permanen!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#6366f1',
                cancelButtonColor: '#ef4444',
                confirmButtonText: 'Ya, Hapus!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    form.submit();
                }
            });
        }

        // Export to JSON
        function exportData() {
            const data = <?= json_encode($allData) ?>;
            const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data, null, 4));
            const downloadAnchorNode = document.createElement('a');
            downloadAnchorNode.setAttribute("href", dataStr);
            downloadAnchorNode.setAttribute("download", "teka_teki_export.json");
            document.body.appendChild(downloadAnchorNode);
            downloadAnchorNode.click();
            downloadAnchorNode.remove();
            
            Swal.fire('Berhasil!', 'Data berhasil diekspor ke JSON.', 'success');
        }

        // Success Alert after Redirect
        <?php if (isset($_GET['status']) && $_GET['status'] == 'success'): ?>
            Swal.fire('Berhasil!', 'Data telah diperbarui.', 'success');
        <?php endif; ?>
    </script>
</body>
</html>