<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

// Check integrated authentication
$integratedAuth = new IntegratedAdminAuth();
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update session data
$_SESSION['admin_data'] = $adminData;

// CRITICAL: Set current site ID for proper data isolation
$_SESSION['current_site_id'] = $adminData['site_id'] ?? 1;

$db = new Database();
$pdo = null;
try {
    $pdo = $db->getConnection();
} catch (Exception $e) {
    error_log("Database connection error: " . $e->getMessage());
}
$currentTab = isset($_GET['tab']) ? $_GET['tab'] : '2d';

// Handle form submissions
if ($_POST && $pdo) {
    try {
        
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'add':
                    $table = "buku_mimpi_" . $_POST['tipe'];
                    $angka = trim($_POST['angka']);
                    $angka2 = trim($_POST['angka2'] ?? ''); // Second number for 3D/4D
                    $judul_mimpi = trim($_POST['judul_mimpi']);
                    
                    // Get current site ID for multi-tenant isolation
                    $siteId = SiteManager::getInstance()->getSiteId();
                    
                    // Handle image upload
                    $imagePath = null;
                    if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
                        $uploadDir = '../assets/images/buku-mimpi/';
                        if (!is_dir($uploadDir)) {
                            mkdir($uploadDir, 0755, true);
                        }
                        
                        $imageExt = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                        $imageName = 'mimpi_' . $_POST['tipe'] . '_' . $angka . '_' . time() . '.' . $imageExt;
                        $fullPath = $uploadDir . $imageName;
                        
                        if (move_uploaded_file($_FILES['image']['tmp_name'], $fullPath)) {
                            $imagePath = $imageName;
                        }
                    }
                    
                    // Check if table has angka2 column (3D/4D) or not (2D) - add site_id for isolation
                    if ($_POST['tipe'] === '2d') {
                        $stmt = $pdo->prepare("INSERT INTO {$table} (angka, judul_mimpi, image_path, site_id) VALUES (?, ?, ?, ?)");
                        $stmt->execute([$angka, $judul_mimpi, $imagePath, $siteId]);
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO {$table} (angka, angka2, judul_mimpi, image_path, site_id) VALUES (?, ?, ?, ?, ?)");
                        $stmt->execute([$angka, $angka2, $judul_mimpi, $imagePath, $siteId]);
                    }
                    
                    $_SESSION['success'] = "Data berhasil ditambahkan!";
                    break;
                
                case 'edit':
                    $table = "buku_mimpi_" . $_POST['tipe'];
                    $id = $_POST['id'];
                    $angka = trim($_POST['angka']);
                    $angka2 = trim($_POST['angka2'] ?? ''); // Second number for 3D/4D
                    $judul_mimpi = trim($_POST['judul_mimpi']);
                    
                    // Get current site ID for multi-tenant isolation
                    $siteId = SiteManager::getInstance()->getSiteId();
                    
                    // Handle image upload
                    $imagePath = $_POST['existing_image'];
                    if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
                        $uploadDir = '../assets/images/buku-mimpi/';
                        $imageExt = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                        $imageName = 'mimpi_' . $_POST['tipe'] . '_' . $angka . '_' . time() . '.' . $imageExt;
                        $fullPath = $uploadDir . $imageName;
                        
                        if (move_uploaded_file($_FILES['image']['tmp_name'], $fullPath)) {
                            // Delete old image
                            if ($imagePath && file_exists($uploadDir . $imagePath)) {
                                unlink($uploadDir . $imagePath);
                            }
                            $imagePath = $imageName;
                        }
                    }
                    
                    // Check if table has angka2 column (3D/4D) or not (2D) - add site_id for isolation
                    if ($_POST['tipe'] === '2d') {
                        $stmt = $pdo->prepare("UPDATE {$table} SET angka = ?, judul_mimpi = ?, image_path = ? WHERE id = ? AND site_id = ?");
                        $stmt->execute([$angka, $judul_mimpi, $imagePath, $id, $siteId]);
                    } else {
                        $stmt = $pdo->prepare("UPDATE {$table} SET angka = ?, angka2 = ?, judul_mimpi = ?, image_path = ? WHERE id = ? AND site_id = ?");
                        $stmt->execute([$angka, $angka2, $judul_mimpi, $imagePath, $id, $siteId]);
                    }
                    
                    $_SESSION['success'] = "Data berhasil diupdate!";
                    break;
                
                case 'delete':
                    $table = "buku_mimpi_" . $_POST['tipe'];
                    $id = $_POST['id'];
                    
                    // Get current site ID for multi-tenant isolation
                    $siteId = SiteManager::getInstance()->getSiteId();
                    
                    // Get image path before delete - with site isolation
                    $stmt = $pdo->prepare("SELECT image_path FROM {$table} WHERE id = ? AND site_id = ?");
                    $stmt->execute([$id, $siteId]);
                    $item = $stmt->fetch();
                    
                    if ($item && $item['image_path']) {
                        $imagePath = '../assets/images/buku-mimpi/' . $item['image_path'];
                        if (file_exists($imagePath)) {
                            unlink($imagePath);
                        }
                    }
                    
                    $stmt = $pdo->prepare("DELETE FROM {$table} WHERE id = ? AND site_id = ?");
                    $stmt->execute([$id, $siteId]);
                    
                    $_SESSION['success'] = "Data berhasil dihapus!";
                    break;
            }
        }
    } catch (Exception $e) {
        $_SESSION['error'] = "Error: " . $e->getMessage();
    }
    
    header("Location: buku-mimpi.php?tab=" . $currentTab);
    exit;
}

// Pagination parameters
$page = max(1, (int)($_GET['page'] ?? 1));
$itemsPerPage = 20;
$offset = ($page - 1) * $itemsPerPage;

// Get data for current tab with pagination
$items = [];
$totalItems = 0;
$totalPages = 1;

if ($pdo) {
    try {
        $table = "buku_mimpi_" . $currentTab;
        
        // Use site-isolated method instead of direct query
        switch($currentTab) {
            case '2d':
                $allItems = $db->getBukuMimpi2D();
                break;
            case '3d':
                $allItems = $db->getBukuMimpi3D();
                break;
            case '4d':
                $allItems = $db->getBukuMimpi4D();
                break;
            default:
                $allItems = [];
        }
        
        // Calculate pagination
        $totalItems = count($allItems);
        $totalPages = ceil($totalItems / $itemsPerPage);
        
        // Get paginated items
        $items = array_slice($allItems, $offset, $itemsPerPage);
        
    } catch (Exception $e) {
        // Table might not exist yet or other database error
        error_log("Error fetching buku mimpi data: " . $e->getMessage());
        $items = [];
        $totalItems = 0;
        $totalPages = 0;
    }
}

include 'admin-sidebar-template.php';
?>

<div class="container">
    <?php if (!$pdo): ?>
        <div class="alert alert-danger">
            <h4><i class="fas fa-exclamation-triangle"></i> Database Connection Error</h4>
            <p>Tidak dapat terhubung ke database. Kemungkinan penyebab:</p>
            <ul>
                <li>Ekstensi <code>pdo_mysql</code> tidak aktif di PHP</li>
                <li>Service MySQL tidak berjalan</li>
                <li>Konfigurasi database salah</li>
            </ul>
            <p><strong>Solusi:</strong> Lihat panduan di file <code>BUKU-MIMPI-FIX-PDO.md</code></p>
        </div>
        <style>
            .alert { padding: 20px; margin: 20px 0; border-radius: 8px; }
            .alert-danger { background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; }
            .alert h4 { margin: 0 0 10px 0; }
            .alert ul { margin: 10px 0; padding-left: 20px; }
            .alert code { background: #fff; padding: 2px 4px; border-radius: 3px; }
        </style>
    <?php else: ?>
    
    <div class="page-header">
        <h1><i class="bi bi-moon"></i> Kelola Buku Mimpi</h1>
        <p>Kelola daftar mimpi untuk angka 2D, 3D, dan 4D</p>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success">
            <i class="bi bi-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-error">
            <i class="bi bi-exclamation-circle"></i> <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
        </div>
    <?php endif; ?>

    <!-- Tab Navigation -->
    <div class="tab-navigation">
        <a href="?tab=2d" class="tab-btn <?php echo $currentTab === '2d' ? 'active' : ''; ?>">
            <i class="bi bi-dice-2"></i> 2D
        </a>
        <a href="?tab=3d" class="tab-btn <?php echo $currentTab === '3d' ? 'active' : ''; ?>">
            <i class="bi bi-dice-3"></i> 3D
        </a>
        <a href="?tab=4d" class="tab-btn <?php echo $currentTab === '4d' ? 'active' : ''; ?>">
            <i class="bi bi-dice-4"></i> 4D
        </a>
    </div>

    <!-- Add Button -->
    <div class="action-header">
        <button onclick="openAddModal()" class="btn-primary">
            <i class="bi bi-plus-lg"></i> Tambah <?php echo strtoupper($currentTab); ?> Baru
        </button>
    </div>

    <!-- Data Table -->
    <div class="admin-card">
        <div class="card-header">
            <h3>Daftar Mimpi <?php echo strtoupper($currentTab); ?></h3>
            <span class="badge"><?php echo count($items); ?> items</span>
        </div>
        
        <div class="table-responsive">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Angka</th>
                        <th>Judul Mimpi</th>
                        <th>Gambar</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($items)): ?>
                        <?php foreach ($items as $item): ?>
                            <tr>
                                <td>
                                    <div class="number-display">
                                        <div class="number-badge badge-<?php echo $currentTab; ?>">
                                            <?php echo str_pad($item['angka'], strlen($currentTab), '0', STR_PAD_LEFT); ?>
                                        </div>
                                        <?php if ($currentTab !== '2d' && !empty($item['angka2'])): ?>
                                            <span class="number-separator">-</span>
                                            <div class="number-badge badge-<?php echo $currentTab; ?>">
                                                <?php echo str_pad($item['angka2'], strlen($currentTab), '0', STR_PAD_LEFT); ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td>
                                    <div class="item-title"><?php echo htmlspecialchars($item['judul_mimpi']); ?></div>
                                </td>
                                <td>
                                    <?php if ($item['image_path']): ?>
                                        <img src="../assets/images/buku-mimpi/<?php echo $item['image_path']; ?>" 
                                             alt="<?php echo htmlspecialchars($item['judul_mimpi']); ?>" 
                                             class="table-image">
                                    <?php else: ?>
                                        <span class="no-image">Tidak ada gambar</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-sm btn-outline-primary" 
                                                onclick="editItem(<?php echo htmlspecialchars(json_encode($item)); ?>)" 
                                                title="Edit">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" 
                                                onclick="deleteItem(<?php echo $item['id']; ?>, '<?php echo $currentTab; ?>')" 
                                                title="Hapus">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="4" class="no-data">
                                <i class="bi bi-inbox"></i>
                                <p>Belum ada data <?php echo strtoupper($currentTab); ?></p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
        <div class="pagination-container" style="margin-top: 20px; text-align: center;">
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?tab=<?php echo $currentTab; ?>&page=<?php echo ($page - 1); ?>" class="page-btn">
                        <i class="bi bi-chevron-left"></i> Prev
                    </a>
                <?php endif; ?>
                
                <?php
                // Mobile-friendly pagination: max 5 numbers
                $startPage = max(1, $page - 2);
                $endPage = min($totalPages, $page + 2);
                
                if ($startPage > 1): ?>
                    <a href="?tab=<?php echo $currentTab; ?>&page=1" class="page-btn">1</a>
                    <?php if ($startPage > 2): ?>
                        <span class="page-dots">...</span>
                    <?php endif; ?>
                <?php endif; ?>
                
                <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                    <a href="?tab=<?php echo $currentTab; ?>&page=<?php echo $i; ?>" 
                       class="page-btn <?php echo ($i === $page) ? 'active' : ''; ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endfor; ?>
                
                <?php if ($endPage < $totalPages): ?>
                    <?php if ($endPage < $totalPages - 1): ?>
                        <span class="page-dots">...</span>
                    <?php endif; ?>
                    <a href="?tab=<?php echo $currentTab; ?>&page=<?php echo $totalPages; ?>" class="page-btn"><?php echo $totalPages; ?></a>
                <?php endif; ?>
                
                <?php if ($page < $totalPages): ?>
                    <a href="?tab=<?php echo $currentTab; ?>&page=<?php echo ($page + 1); ?>" class="page-btn">
                        Next <i class="bi bi-chevron-right"></i>
                    </a>
                <?php endif; ?>
            </div>
            
            <div class="pagination-info" style="margin-top: 10px; color: #888; font-size: 12px;">
                Halaman <?php echo $page; ?> dari <?php echo $totalPages; ?> 
                (<?php echo $totalItems; ?> total items, menampilkan <?php echo count($items); ?> items)
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Add/Edit Modal -->
<div id="itemModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">Tambah Item Baru</h3>
            <button onclick="closeModal()" class="modal-close">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>
        
        <form id="itemForm" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" id="formAction" value="add">
            <input type="hidden" name="tipe" value="<?php echo $currentTab; ?>">
            <input type="hidden" name="id" id="itemId">
            <input type="hidden" name="existing_image" id="existingImage">
            
            <div class="form-group">
                <label for="angka">Angka <?php echo strtoupper($currentTab); ?> (Pertama)</label>
                <input type="text" 
                       id="angka" 
                       name="angka" 
                       required
                       placeholder="Contoh: 167, 22, 1234"
                       pattern="[0-9]+"
                       title="Hanya angka yang diperbolehkan">
            </div>
            
            <?php if ($currentTab !== '2d'): ?>
            <div class="form-group">
                <label for="angka2">Angka <?php echo strtoupper($currentTab); ?> (Kedua) - Opsional</label>
                <input type="text" 
                       id="angka2" 
                       name="angka2" 
                       placeholder="Contoh: 132, 45, 5678"
                       pattern="[0-9]*"
                       title="Hanya angka yang diperbolehkan (kosong jika tidak ada)">
                <small>Kosongkan jika hanya ada satu angka</small>
            </div>
            <?php endif; ?>
            
            <div class="form-group">
                <label for="judul_mimpi">Judul Mimpi</label>
                <textarea id="judul_mimpi" 
                         name="judul_mimpi" 
                         required
                         placeholder="Contoh: Kucing, Kalung, Kerbau"
                         rows="2"></textarea>
                <small>Pisahkan dengan koma untuk beberapa mimpi</small>
            </div>
            
            <div class="form-group">
                <label for="image">Gambar (Opsional)</label>
                <input type="file" id="image" name="image" accept="image/*">
                <div id="currentImage" style="display: none;">
                    <p>Gambar saat ini:</p>
                    <img id="previewImage" src="" alt="Current image" class="preview-image">
                </div>
            </div>
            
            <div class="modal-actions">
                <button type="button" onclick="closeModal()" class="btn-secondary">
                    <i class="bi bi-x-lg"></i> Batal
                </button>
                <button type="submit" class="btn-primary">
                    <i class="bi bi-save"></i> Simpan
                </button>
            </div>
        </form>
    </div>
</div>

<style>
    .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
    .page-header { text-align: center; margin-bottom: 30px; }
    .page-header h1 { font-size: 2.5rem; margin-bottom: 10px; color: #d4af37; }
    .page-header p { color: #aaa; }
    
    .alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; }
    .alert-success { background: linear-gradient(135deg, #00b894, #00cec9); color: white; }
    .alert-error { background: linear-gradient(135deg, #e74c3c, #c0392b); color: white; }
    
    .tab-navigation { display: flex; justify-content: center; margin-bottom: 30px; background: rgba(255,255,255,0.1); border-radius: 10px; padding: 5px; }
    .tab-btn { padding: 12px 24px; background: transparent; color: #000000; text-decoration: none; border-radius: 8px; transition: all 0.3s ease; margin: 0 5px; }
    .tab-btn:hover { background: rgba(255,255,255,0.2); }
    .tab-btn.active { background: linear-gradient(135deg, #667eea, #764ba2); }
    
    .action-header { text-align: center; margin-bottom: 20px; }
    .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 8px 16px; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.9rem; }
    .btn-secondary { background: #6c757d; color: white; padding: 8px 16px; border: none; border-radius: 6px; cursor: pointer; font-size: 0.9rem; }
    
    .admin-card { background: rgba(255,255,255,0.1); border-radius: 15px; overflow: hidden; }
    .card-header { display: flex; justify-content: space-between; align-items: center; padding: 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
    .badge { background: #667eea; color: white; padding: 4px 12px; border-radius: 20px; font-size: 0.9rem; }
    
    .table-responsive { overflow-x: auto; }
    .admin-table { width: 100%; }
    .admin-table th, .admin-table td { padding: 15px; text-align: left; border-bottom: 1px solid rgba(255,255,255,0.1); }
    .admin-table th { background: rgba(255,255,255,0.05); font-weight: 600; }
    
    .number-display { display: flex; align-items: center; gap: 8px; }
    .number-badge { padding: 8px 16px; border-radius: 20px; font-weight: bold; color: white; display: inline-block; }
    .number-separator { color: #fff; font-weight: bold; font-size: 1.2rem; }
    .badge-2d { background: linear-gradient(135deg, #ff6b6b, #ee5a24); }
    .badge-3d { background: linear-gradient(135deg, #4ecdc4, #44a08d); }
    .badge-4d { background: linear-gradient(135deg, #a8edea, #fed6e3); color: #333; }
    
    .table-image { width: 60px; height: 60px; object-fit: cover; border-radius: 8px; }
    .no-image { color: #888; font-style: italic; }
    .no-data { text-align: center; padding: 40px; color: #888; }
    
    /* Action buttons akan menggunakan Bootstrap btn-group */
    
    .modal { 
        display: none; 
        position: fixed; 
        z-index: 1000; 
        left: 0; 
        top: 0; 
        width: 100%; 
        height: 100%; 
        background: rgba(0,0,0,0.7);
        overflow-y: auto;
    }
    .modal-content { 
        background: #2d3748; 
        margin: 2% auto; 
        padding: 0; 
        border-radius: 15px; 
        width: 90%; 
        max-width: 500px;
        max-height: 90vh;
        overflow-y: auto;
    }
    .modal-header { 
        display: flex; 
        justify-content: space-between; 
        align-items: center; 
        padding: 15px 20px; 
        border-bottom: 1px solid rgba(255,255,255,0.1); 
        position: sticky;
        top: 0;
        background: #2d3748;
        z-index: 10;
    }
    .modal-close { background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; }
    
    .form-group { padding: 10px 20px; }
    .form-group label { display: block; margin-bottom: 5px; font-weight: 600; font-size: 0.9rem; }
    .form-group input, .form-group textarea { 
        width: 100%; 
        padding: 8px 12px; 
        background: rgba(255,255,255,0.1); 
        border: 1px solid rgba(255,255,255,0.2); 
        border-radius: 6px; 
        color: #fff;
        font-size: 0.9rem;
        box-sizing: border-box;
    }
    .form-group textarea { resize: vertical; min-height: 60px; }
    .form-group small { color: #aaa; font-size: 0.8rem; margin-top: 3px; display: block; }
    
    .modal-actions { 
        padding: 12px 15px; 
        display: flex; 
        gap: 8px; 
        justify-content: flex-end;
        position: sticky;
        bottom: 0;
        background: #2d3748;
        border-top: 1px solid rgba(255,255,255,0.1);
        z-index: 10;
    }
    .preview-image { max-width: 120px; height: auto; border-radius: 6px; margin-top: 8px; }
    
    /* Pagination Styles */
    .pagination-container {
        margin-top: 20px;
        text-align: center;
    }
    
    .pagination {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        flex-wrap: wrap;
        justify-content: center;
    }
    
    .page-btn {
        display: inline-flex;
        align-items: center;
        padding: 6px 10px;
        background: rgba(255,255,255,0.1);
        color: #fff;
        text-decoration: none;
        border-radius: 4px;
        border: 1px solid rgba(255,255,255,0.2);
        font-size: 12px;
        font-weight: 500;
        transition: all 0.3s ease;
        gap: 4px;
        min-width: 32px;
        height: 32px;
        justify-content: center;
    }
    
    .page-btn:hover {
        background: #667eea;
        color: #fff;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
    }
    
    .page-btn.active {
        background: #667eea;
        color: #fff;
        font-weight: bold;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
    }
    
    .page-dots {
        color: #888;
        padding: 0 4px;
    }
    
    .pagination-info {
        margin-top: 10px;
        color: #888;
        font-size: 12px;
    }

    /* Responsive modal for mobile */
    @media (max-width: 768px) {
        .modal-content { 
            margin: 1% auto; 
            width: 95%; 
            max-width: none;
        }
        .form-group { padding: 8px 15px; }
        .modal-header { padding: 12px 15px; }
        .modal-actions { padding: 12px 15px; }
        
        .page-btn {
            padding: 4px 6px;
            font-size: 10px;
            min-width: 24px;
            height: 28px;
        }
    }
</style>

<script>
    function openAddModal() {
        document.getElementById('modalTitle').textContent = 'Tambah <?php echo strtoupper($currentTab); ?> Baru';
        document.getElementById('formAction').value = 'add';
        document.getElementById('itemForm').reset();
        document.getElementById('itemId').value = '';
        document.getElementById('currentImage').style.display = 'none';
        document.getElementById('itemModal').style.display = 'block';
    }
    
    function editItem(item) {
        document.getElementById('modalTitle').textContent = 'Edit <?php echo strtoupper($currentTab); ?>';
        document.getElementById('formAction').value = 'edit';
        document.getElementById('itemId').value = item.id;
        document.getElementById('angka').value = item.angka;
        
        // Handle angka2 field for 3D/4D only
        const angka2Field = document.getElementById('angka2');
        if (angka2Field) {
            angka2Field.value = item.angka2 || '';
        }
        
        document.getElementById('judul_mimpi').value = item.judul_mimpi;
        document.getElementById('existingImage').value = item.image_path || '';
        
        if (item.image_path) {
            document.getElementById('currentImage').style.display = 'block';
            document.getElementById('previewImage').src = '../assets/images/buku-mimpi/' + item.image_path;
        } else {
            document.getElementById('currentImage').style.display = 'none';
        }
        
        document.getElementById('itemModal').style.display = 'block';
    }
    
    function deleteItem(id, tipe) {
        if (confirm('Apakah Anda yakin ingin menghapus item ini?')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="${id}">
                <input type="hidden" name="tipe" value="${tipe}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
    }
    
    function closeModal() {
        document.getElementById('itemModal').style.display = 'none';
    }
    
    // Close modal when clicking outside
    window.onclick = function(event) {
        const modal = document.getElementById('itemModal');
        if (event.target === modal) {
            closeModal();
        }
    }
</script>

<?php endif; ?>
<?php include 'admin-sidebar-footer.php'; ?>