<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/integrated-admin-auth.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 || !isset($adminData['admin_type']) || $adminData['admin_type'] !== 'master') {
    if (!$adminData) {
        session_destroy();
        header('Location: login.php');
    } else {
        header('Location: login.php?error=insufficient_permissions');
    }
    exit;
}

// Get admin info from validated session
$currentSite = $adminData['site_access'] ?? 'master';
$isMasterAdmin = ($adminData['admin_type'] === 'master');

// Only allow access for Master Admin (already verified above, but double-check)
if (!$isMasterAdmin) {
    header('Location: dashboard.php');
    exit;
}

// Database configuration - jangan timpa konfigurasi pusat jika sudah ada
if (!defined('DB_HOST')) define('DB_HOST', 'localhost');
if (!defined('DB_USER')) define('DB_USER', 'linkslot88_autopred97841dellon9781a');
if (!defined('DB_PASS')) define('DB_PASS', 'prediksiautomanjur9854ikjbnienfxx');
if (!defined('DB_NAME')) define('DB_NAME', 'linkslot88_autoprediksikjmngpfjr941');

$title = "Master Buku Mimpi";
$currentPage = "master-buku-mimpi";

// Get sites data for site selection
$sites = [
    'mayortogel' => 'MayorTogel',
    'wajahtoto' => 'WajahToto', 
    'yuki585' => 'Yuki585'
];

// Handle form submission and tab state
$message = '';
$success = false;
$active_tab = $_GET['tab'] ?? 'add'; // Default to add tab

// Handle success message from redirect
if (isset($_GET['success'])) {
    $message = $_GET['success'];
    $success = true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $target_sites = isset($_POST['target_sites']) ? $_POST['target_sites'] : [];
    $kode_2d = isset($_POST['kode_2d']) ? trim($_POST['kode_2d']) : '';
    $mimpi = isset($_POST['mimpi']) ? trim($_POST['mimpi']) : '';
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    // Handle image upload - will be copied to each target site directory
    $uploaded_filename = null;
    $temp_upload_path = null;
    if (isset($_FILES['gambar_mimpi']) && $_FILES['gambar_mimpi']['error'] === UPLOAD_ERR_OK) {
        $file_info = pathinfo($_FILES['gambar_mimpi']['name']);
        $extension = strtolower($file_info['extension']);
        
        // Validate file type
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($extension, $allowed_types)) {
            // Check file size (2MB max)
            if ($_FILES['gambar_mimpi']['size'] <= 2 * 1024 * 1024) {
                // Generate unique filename (same format as admin biasa ADD operation)
                $uploaded_filename = uniqid() . '.' . $extension;
                
                // Temporarily store the uploaded file
                $temp_upload_path = sys_get_temp_dir() . '/' . $uploaded_filename;
                move_uploaded_file($_FILES['gambar_mimpi']['tmp_name'], $temp_upload_path);
            }
        }
    }
    
    if ($action === 'add') {
        if (!empty($target_sites) && !empty($kode_2d) && !empty($mimpi)) {
            $success_count = 0;
            $error_sites = [];
            
            foreach ($target_sites as $site_code) {
                try {
                    // Copy image to target site directory if image was uploaded
                    $site_image_url = null;
                    if ($uploaded_filename && $temp_upload_path) {
                        $site_upload_dir = "../{$site_code}/uploads/buku-mimpi/";
                        
                        // Create site upload directory if it doesn't exist
                        if (!is_dir($site_upload_dir)) {
                            mkdir($site_upload_dir, 0755, true);
                        }
                        
                        $site_upload_path = $site_upload_dir . $uploaded_filename;
                        
                        // Copy file to site directory
                        if (copy($temp_upload_path, $site_upload_path)) {
                            $site_image_url = 'uploads/buku-mimpi/' . $uploaded_filename;
                        }
                    }
                    
                    // Connect to specific site database
                    $pdo = (new Database())->getConnection();
                    
                    // Check if entry already exists
                    $check_sql = "SELECT id FROM buku_mimpi_{$site_code} WHERE angka_2d = ?";
                    $check_stmt = $pdo->prepare($check_sql);
                    $check_stmt->execute([$kode_2d]);
                    
                    if ($check_stmt->rowCount() == 0) {
                        // Insert new entry
                        $insert_sql = "INSERT INTO buku_mimpi_{$site_code} (description, angka_2d, image_url, created_at) VALUES (?, ?, ?, NOW())";
                        $insert_stmt = $pdo->prepare($insert_sql);
                        $insert_stmt->execute([$mimpi, $kode_2d, $site_image_url]);
                        $success_count++;
                    } else {
                        $error_sites[] = $sites[$site_code] . " (sudah ada)";
                    }
                    
                } catch (Exception $e) {
                    $error_sites[] = $sites[$site_code] . " (error: " . $e->getMessage() . ")";
                }
            }
            
            // Cleanup temporary file
            if ($temp_upload_path && file_exists($temp_upload_path)) {
                unlink($temp_upload_path);
            }
            
            if ($success_count > 0) {
                $success = true;
                $message = "Berhasil menambahkan buku mimpi ke $success_count situs.";
                if (!empty($error_sites)) {
                    $message .= " Gagal: " . implode(', ', $error_sites);
                }
                
                // Redirect to add tab to maintain active tab
                header("Location: master-buku-mimpi.php?tab=add&success=" . urlencode($message));
                exit;
                
            } else {
                $message = "Gagal menambahkan buku mimpi. " . implode(', ', $error_sites);
            }
        } else {
            $message = "Mohon lengkapi semua field yang diperlukan.";
        }
    }
    
 else if ($action === 'edit') {
        $edit_id = $_POST['edit_id'] ?? '';
        $edit_site = $_POST['edit_site'] ?? '';
        $edit_angka_2d = $_POST['edit_angka_2d'] ?? '';
        $edit_description = $_POST['edit_description'] ?? '';
        
        if (!empty($edit_id) && !empty($edit_site) && !empty($edit_angka_2d) && !empty($edit_description)) {
            try {
                // Handle image upload for edit
                $edit_image_url = $_POST['current_image_url'] ?? null;
                if ($uploaded_filename && $temp_upload_path) {
                    $site_upload_dir = "../{$edit_site}/uploads/buku-mimpi/";
                    
                    // Create site upload directory if it doesn't exist
                    if (!is_dir($site_upload_dir)) {
                        mkdir($site_upload_dir, 0755, true);
                    }
                    
                    $site_upload_path = $site_upload_dir . $uploaded_filename;
                    
                    // Copy file to site directory
                    if (copy($temp_upload_path, $site_upload_path)) {
                        // Delete old image if exists
                        if (!empty($_POST['current_image_url'])) {
                            $old_image_path = "../{$edit_site}/" . $_POST['current_image_url'];
                            if (file_exists($old_image_path)) {
                                unlink($old_image_path);
                            }
                        }
                        $edit_image_url = 'uploads/buku-mimpi/' . $uploaded_filename;
                    }
                }
                
                // Connect to database
                $pdo = new PDO(
                    "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                    DB_USER,
                    DB_PASS,
                    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                );
                
                // Update entry
                $update_sql = "UPDATE buku_mimpi_{$edit_site} SET description = ?, angka_2d = ?, image_url = ?, updated_at = NOW() WHERE id = ?";
                $update_stmt = $pdo->prepare($update_sql);
                $update_stmt->execute([$edit_description, $edit_angka_2d, $edit_image_url, $edit_id]);
                
                // Cleanup temporary file
                if ($temp_upload_path && file_exists($temp_upload_path)) {
                    unlink($temp_upload_path);
                }
                
                $success = true;
                $message = "Berhasil mengupdate buku mimpi di situs " . $sites[$edit_site];
                
                // Redirect to edit tab to maintain active tab
                header("Location: master-buku-mimpi.php?tab=edit&success=" . urlencode($message));
                exit;
                
            } catch (Exception $e) {
                $message = "Error mengupdate data: " . $e->getMessage();
            }
        } else {
            $message = "Mohon lengkapi semua field yang diperlukan untuk edit.";
        }
    } else if ($action === 'sync') {
        $source_site = $_POST['source_site'];
        $target_sites = $_POST['sync_target_sites'];
        
        if (!empty($source_site) && !empty($target_sites)) {
            try {
                $pdo = new PDO(
                    "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                    DB_USER,
                    DB_PASS,
                    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                );
                
                // Get data from source site
                $source_sql = "SELECT description, angka_2d, image_url FROM buku_mimpi_{$source_site} ORDER BY angka_2d";
                $source_stmt = $pdo->prepare($source_sql);
                $source_stmt->execute();
                $source_data = $source_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                $total_synced = 0;
                
                foreach ($target_sites as $target_site) {
                    if ($target_site !== $source_site) {
                        foreach ($source_data as $data) {
                            // Check if this data already exists in target site
                            $check_sql = "SELECT id FROM buku_mimpi_{$target_site} WHERE angka_2d = ?";
                            $check_stmt = $pdo->prepare($check_sql);
                            $check_stmt->execute([$data['angka_2d']]);
                            
                            if ($check_stmt->rowCount() == 0) {
                                // Insert new data
                                $insert_sql = "INSERT INTO buku_mimpi_{$target_site} (description, angka_2d, image_url, created_at) VALUES (?, ?, ?, NOW())";
                                $insert_stmt = $pdo->prepare($insert_sql);
                                $insert_stmt->execute([$data['description'], $data['angka_2d'], $data['image_url']]);
                                $total_synced++;
                            }
                        }
                    }
                }
                
                $success = true;
                $message = "Berhasil sync $total_synced entri buku mimpi dari {$sites[$source_site]}.";
                
                // Redirect to sync tab to maintain active tab
                header("Location: master-buku-mimpi.php?tab=sync&success=" . urlencode($message));
                exit;
                
            } catch (Exception $e) {
                $message = "Error sync: " . $e->getMessage();
            }
        }
    }
}

// Get current data from all sites for display
$all_data = [];
try {
    // TEMP DEBUG: log current DB constants (DO NOT LOG DB_PASS)
    error_log("DEBUG-BUKU-MIMPI: DB_HOST=" . (defined('DB_HOST') ? DB_HOST : '(undef)') . " DB_NAME=" . (defined('DB_NAME') ? DB_NAME : '(undef)') . " DB_USER=" . (defined('DB_USER') ? DB_USER : '(undef)'));

    $db = new Database();
    $pdo = $db->getConnection();
    
    $missing_tables = [];
    foreach ($sites as $site_code => $site_name) {
        $tableName = 'buku_mimpi_' . $site_code;
        // Check table exists using SiteConfig helper
        $exists = SiteConfig::tableExists($tableName);
        error_log("DEBUG-BUKU-MIMPI: tableExists({$tableName}) = " . ($exists ? 'true' : 'false'));
        if (!$exists) {
            $missing_tables[] = $site_code;
            $all_data[$site_code] = [];
            continue;
        }

        $sql = "SELECT angka_2d, description, image_url, created_at FROM {$tableName} ORDER BY angka_2d LIMIT 20";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $all_data[$site_code] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    if (!empty($missing_tables)) {
        $message = "Error loading data: missing tables for sites: " . implode(', ', $missing_tables);
    }
} catch (Exception $e) {
    $message = "Error loading data: " . $e->getMessage();
}

// Page-specific variables for master header
$pageTitle = "Master Admin - Master buku mimpi";
$pageDescription = 'Kelola buku mimpi untuk semua situs';

// Include master admin header
include 'admin-sidebar-template.php';
?>

<div class="container-fluid px-4">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="mb-0"><i class="bi bi-book me-2"></i>Master Buku Mimpi</h4>
                    <small class="text-muted">Kelola buku mimpi untuk semua situs</small>
                </div>
                
                <div class="card-body">
                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $success ? 'success' : 'danger'; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Tabs -->
                    <ul class="nav nav-tabs mb-4" role="tablist">
                        <li class="nav-item">
                            <button class="nav-link <?php echo $active_tab === 'add' ? 'active' : ''; ?>" data-bs-toggle="tab" data-bs-target="#add-tab">
                                <i class="bi bi-plus-circle me-1"></i>Tambah Buku Mimpi
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link <?php echo $active_tab === 'edit' ? 'active' : ''; ?>" data-bs-toggle="tab" data-bs-target="#edit-tab">
                                <i class="bi bi-pencil me-1"></i>Edit Buku Mimpi
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link <?php echo $active_tab === 'sync' ? 'active' : ''; ?>" data-bs-toggle="tab" data-bs-target="#sync-tab">
                                <i class="bi bi-arrow-repeat me-1"></i>Sync Antar Situs
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link <?php echo $active_tab === 'view' ? 'active' : ''; ?>" data-bs-toggle="tab" data-bs-target="#view-tab">
                                <i class="bi bi-eye me-1"></i>Lihat Data
                            </button>
                        </li>
                    </ul>

                    <div class="tab-content">
                        <!-- Add Tab -->
                        <div class="tab-pane fade <?php echo $active_tab === 'add' ? 'show active' : ''; ?>" id="add-tab">
                            <form method="POST" class="needs-validation" enctype="multipart/form-data" novalidate>
                                <input type="hidden" name="action" value="add">
                                <input type="hidden" name="tab" value="add">
                                
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Target Situs <span class="text-danger">*</span></label>
                                        <?php foreach ($sites as $code => $name): ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="target_sites[]" value="<?php echo $code; ?>" id="site_<?php echo $code; ?>">
                                            <label class="form-check-label" for="site_<?php echo $code; ?>">
                                                <?php echo $name; ?>
                                            </label>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="kode_2d" class="form-label">Angka 2D <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="kode_2d" name="kode_2d" 
                                                   pattern="[0-9]{2}" maxlength="2" required 
                                                   placeholder="00-99">
                                            <div class="invalid-feedback">Masukkan angka 2D (00-99)</div>
                                        </div>

                                        <div class="mb-3">
                                            <label for="mimpi" class="form-label">Deskripsi Mimpi <span class="text-danger">*</span></label>
                                            <textarea class="form-control" id="mimpi" name="mimpi" rows="4" required 
                                                     placeholder="Contoh: Kucing Hitam, Macan, Harimau, dll..."></textarea>
                                            <small class="form-text text-muted">Pisahkan dengan koma untuk beberapa mimpi</small>
                                            <div class="invalid-feedback">Masukkan deskripsi mimpi</div>
                                        </div>

                                        <div class="mb-3">
                                            <label for="gambar_mimpi" class="form-label">Upload Gambar Mimpi</label>
                                            <input type="file" class="form-control" id="gambar_mimpi" name="gambar_mimpi" 
                                                   accept="image/jpeg,image/jpg,image/png,image/gif">
                                            <small class="form-text text-muted">Format yang diterima: JPG, PNG, GIF (Maks. 2MB)</small>
                                        </div>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-plus-circle me-1"></i>Tambah ke Situs Terpilih
                                </button>
                            </form>
                        </div>

                        <!-- Edit Tab -->
                        <div class="tab-pane fade <?php echo $active_tab === 'edit' ? 'show active' : ''; ?>" id="edit-tab">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5 class="mb-0">Pilih Data untuk Edit</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="mb-3">
                                                <label class="form-label">Pilih Situs</label>
                                                <select id="edit-site-selector" class="form-control" onchange="loadEditData()">
                                                    <option value="">Pilih situs...</option>
                                                    <?php foreach ($sites as $code => $name): ?>
                                                    <option value="<?php echo $code; ?>"><?php echo $name; ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Data Buku Mimpi</label>
                                                <div class="mb-2">
                                                    <button type="button" class="btn btn-sm btn-info" onclick="testEditFunction()">
                                                        <i class="bi bi-bug me-1"></i>Test Edit Function
                                                    </button>
                                                </div>
                                                <div id="edit-data-list">
                                                    <p class="text-muted">Pilih situs untuk melihat data</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5 class="mb-0">Form Edit</h5>
                                        </div>
                                        <div class="card-body">
                                            <form method="POST" enctype="multipart/form-data" id="edit-form">
                                                <input type="hidden" name="action" value="edit">
                                                <input type="hidden" name="edit_id" id="edit-id-input">
                                                <input type="hidden" name="edit_site" id="edit-site-input">
                                                <input type="hidden" name="current_image_url" id="edit-current-image">
                                                <input type="hidden" name="tab" value="edit">
                                                
                                                <div class="mb-3">
                                                    <label for="edit_angka_2d" class="form-label">Angka 2D <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="edit_angka_2d" name="edit_angka_2d" 
                                                           pattern="[0-9]{2}" maxlength="2" required disabled>
                                                </div>

                                                <div class="mb-3">
                                                    <label for="edit_description" class="form-label">Deskripsi Mimpi <span class="text-danger">*</span></label>
                                                    <textarea class="form-control" id="edit_description" name="edit_description" rows="4" required disabled></textarea>
                                                </div>

                                                <div class="mb-3">
                                                    <label for="edit_gambar_mimpi" class="form-label">Upload Gambar Baru (Opsional)</label>
                                                    <input type="file" class="form-control" id="edit_gambar_mimpi" name="gambar_mimpi" 
                                                           accept="image/jpeg,image/jpg,image/png,image/gif" disabled>
                                                    <small class="form-text text-muted">Biarkan kosong jika tidak ingin mengubah gambar</small>
                                                    
                                                    <div id="current-image-preview" class="mt-2" style="display: none;">
                                                        <p class="small text-muted mb-1">Gambar saat ini:</p>
                                                        <img id="current-image" src="" alt="Current Image" 
                                                             style="max-width: 150px; max-height: 150px; border-radius: 8px; border: 2px solid #ddd;">
                                                    </div>
                                                </div>
                                                
                                                <button type="submit" class="btn btn-warning" id="edit-submit-btn" disabled>
                                                    <i class="bi bi-pencil me-1"></i>Update Data
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                        </div>

                        <!-- Sync Tab -->
                        <div class="tab-pane fade <?php echo $active_tab === 'sync' ? 'show active' : ''; ?>" id="sync-tab">
                            <form method="POST">
                                <input type="hidden" name="action" value="sync">
                                <input type="hidden" name="tab" value="sync">
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">Situs Sumber</label>
                                        <select name="source_site" class="form-control" required>
                                            <option value="">Pilih situs sumber</option>
                                            <?php foreach ($sites as $code => $name): ?>
                                            <option value="<?php echo $code; ?>"><?php echo $name; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Situs Target</label>
                                        <?php foreach ($sites as $code => $name): ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="sync_target_sites[]" value="<?php echo $code; ?>" id="sync_site_<?php echo $code; ?>">
                                            <label class="form-check-label" for="sync_site_<?php echo $code; ?>">
                                                <?php echo $name; ?>
                                            </label>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                
                                <div class="mt-3">
                                    <button type="submit" class="btn btn-warning">
                                        <i class="bi bi-arrow-repeat me-1"></i>Sync Data
                                    </button>
                                    <small class="text-muted ms-2">Data yang sudah ada tidak akan ditimpa</small>
                                </div>
                            </form>
                        </div>

                        <!-- View Tab -->
                        <div class="tab-pane fade <?php echo $active_tab === 'view' ? 'show active' : ''; ?>" id="view-tab">
                            <div class="row g-3">
                                <?php foreach ($sites as $site_code => $site_name): ?>
                                <div class="col-md-4">
                                    <div class="card h-100">
                                        <div class="card-header py-2">
                                            <h6 class="mb-0"><?php echo $site_name; ?></h6>
                                            <small class="text-muted"><?php echo count($all_data[$site_code] ?? []); ?> entri (20 terbaru)</small>
                                        </div>
                                        <div class="card-body p-0" style="max-height: 350px; overflow-y: auto;">
                                            <?php if (!empty($all_data[$site_code])): ?>
                                            <table class="table table-sm mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th style="width: 60px;">Gambar</th>
                                                        <th style="width: 60px;">2D</th>
                                                        <th>Deskripsi Mimpi</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($all_data[$site_code] as $row): ?>
                                                    <tr>
                                                        <td>
                                                            <?php if (!empty($row['image_url']) && file_exists('../' . $site_code . '/' . $row['image_url'])): ?>
                                                                <img src="../<?php echo $site_code; ?>/<?php echo htmlspecialchars($row['image_url']); ?>"  
                                                                     alt="Gambar Mimpi" class="img-thumbnail" 
                                                                     style="width: 40px; height: 40px; object-fit: cover;">
                                                            <?php else: ?>
                                                                <div class="bg-light d-flex align-items-center justify-content-center" 
                                                                     style="width: 40px; height: 40px; border-radius: 4px;">
                                                                    <i class="bi bi-image text-muted small"></i>
                                                                </div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><span class="badge bg-primary"><?php echo $row['angka_2d']; ?></span></td>
                                                        <td class="small">
                                                            <span class="text-muted"><?php echo htmlspecialchars(substr($row['description'], 0, 30)); ?><?php echo strlen($row['description']) > 30 ? '...' : ''; ?></span>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                            <?php else: ?>
                                            <div class="p-3 text-center text-muted">
                                                <i class="bi bi-inbox"></i><br>
                                                Belum ada data
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Form validation
(function() {
    'use strict';
    window.addEventListener('load', function() {
        var forms = document.getElementsByClassName('needs-validation');
        var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

// Auto format 2D code - hanya angka, maksimal 2 digit
document.getElementById('kode_2d').addEventListener('input', function(e) {
    let value = e.target.value.replace(/[^0-9]/g, '');
    if (value.length > 2) value = value.substr(0, 2);
    e.target.value = value;
});

// Format dengan leading zero ketika user selesai mengetik
document.getElementById('kode_2d').addEventListener('blur', function(e) {
    let value = e.target.value.replace(/[^0-9]/g, '');
    if (value.length === 1) {
        e.target.value = value.padStart(2, '0');
    } else if (value.length === 0) {
        e.target.value = '';
    }
});

// Image preview
document.getElementById('gambar_mimpi').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        // Check file type
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        if (!validTypes.includes(file.type)) {
            alert('Format file tidak valid! Gunakan JPG, PNG, atau GIF.');
            e.target.value = '';
            return;
        }
        
        // Check file size (2MB)
        if (file.size > 2 * 1024 * 1024) {
            alert('Ukuran file terlalu besar! Maksimal 2MB.');
            e.target.value = '';
            return;
        }
        
        // Show preview
        const reader = new FileReader();
        reader.onload = function(e) {
            let preview = document.getElementById('image-preview');
            if (!preview) {
                preview = document.createElement('div');
                preview.id = 'image-preview';
                preview.className = 'mt-2';
                e.target.parentElement.appendChild(preview);
            }
            preview.innerHTML = `
                <p class="small text-muted mb-1">Preview:</p>
                <img src="${e.target.result}" alt="Preview" 
                     style="max-width: 150px; max-height: 150px; border-radius: 8px; border: 2px solid #ddd;">
            `;
        };
        reader.readAsDataURL(file);
    }
});

// Wait for DOM to be ready and add tab event listeners
document.addEventListener('DOMContentLoaded', function() {// Check if all required form elements exist
    const requiredElements = [
        'edit-id-input',
        'edit-site-input', 
        'edit_angka_2d',
        'edit_description',
        'edit-current-image',
        'edit_gambar_mimpi',
        'edit-submit-btn'
    ];
    
    const missingElements = [];
    requiredElements.forEach(id => {
        if (!document.getElementById(id)) {
            missingElements.push(id);
        }
    });
    
    if (missingElements.length > 0) {
        console.error('Missing form elements:', missingElements);
    } else {}
    
    // Activate correct tab based on URL parameter
    const urlParams = new URLSearchParams(window.location.search);
    const activeTab = urlParams.get('tab');
    
    if (activeTab) {// Remove active class from all tabs and panes
        document.querySelectorAll('.nav-link').forEach(link => link.classList.remove('active'));
        document.querySelectorAll('.tab-pane').forEach(pane => {
            pane.classList.remove('show', 'active');
        });
        
        // Activate the target tab
        const targetTabButton = document.querySelector(`[data-bs-target="#${activeTab}-tab"]`);
        const targetTabPane = document.getElementById(`${activeTab}-tab`);
        
        if (targetTabButton && targetTabPane) {
            targetTabButton.classList.add('active');
            targetTabPane.classList.add('show', 'active');} else {
            console.error(`Tab elements not found for: ${activeTab}`);
        }
    }
    
    // Add event listener for edit tab activation
    const editTabButton = document.querySelector('[data-bs-target="#edit-tab"]');
    if (editTabButton) {
        editTabButton.addEventListener('shown.bs.tab', function() {// Reset form when tab is shown
            resetEditForm();
        });
    }
});

function resetEditForm() {
    // Reset form to initial disabled state
    const editAngka2d = document.getElementById('edit_angka_2d');
    const editDescription = document.getElementById('edit_description');
    const editGambarMimpi = document.getElementById('edit_gambar_mimpi');
    const editSubmitBtn = document.getElementById('edit-submit-btn');
    
    if (editAngka2d) {
        editAngka2d.value = '';
        editAngka2d.disabled = true;
    }
    if (editDescription) {
        editDescription.value = '';
        editDescription.disabled = true;
    }
    if (editGambarMimpi) editGambarMimpi.disabled = true;
    if (editSubmitBtn) editSubmitBtn.disabled = true;}

function testEditFunction() {// Direct form manipulation test
    const angka2d = document.getElementById('edit_angka_2d');
    const description = document.getElementById('edit_description');
    const submitBtn = document.getElementById('edit-submit-btn');
    
    if (!angka2d || !description) {
        alert('ERROR: Form elements tidak ditemukan!');
        console.error('Missing elements:', {angka2d: !!angka2d, description: !!description});
        return;
    }// Test 1: Direct value setting
    angka2d.value = '99';
    description.value = 'Test Description - Direct Assignment';
    
    // Test 2: Enable fields
    angka2d.disabled = false;
    description.disabled = false;
    if (submitBtn) submitBtn.disabled = false;
    
    // Test 3: Visual feedback
    angka2d.style.backgroundColor = '#e3f2fd';
    description.style.backgroundColor = '#e3f2fd';alert(`✅ DIRECT TEST SUCCESS!
    
Angka 2D: "${angka2d.value}"
Description: "${description.value}"
Angka disabled: ${angka2d.disabled}
Description disabled: ${description.disabled}
    
Sekarang coba ketik di form untuk memastikan bisa diisi!`);
    
    // Focus to first field
    angka2d.focus();
}

// Edit functionality
function loadEditData() {
    const siteCode = document.getElementById('edit-site-selector').value;
    const dataList = document.getElementById('edit-data-list');
    
    if (!siteCode) {
        dataList.innerHTML = '<p class="text-muted">Pilih situs untuk melihat data</p>';
        return;
    }
    
    dataList.innerHTML = '<p class="text-muted">Loading...</p>';
    
    // Fetch data using AJAX — use response.text() and try JSON.parse to surface invalid responses
    fetch('get-buku-mimpi-data.php', {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'site=' + encodeURIComponent(siteCode)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.text();
    })
    .then(text => {
        let data;
        try {
            data = JSON.parse(text);
        } catch (e) {
            console.error('Invalid JSON from get-buku-mimpi-data.php:', text);
            dataList.innerHTML = `<div class="alert alert-danger">Error: Invalid server response. Lihat console untuk detail.</div>`;
            return;
        }

        if (data.success) {
            if (data.items && data.items.length > 0) {
                let html = '<div class="list-group">';
                data.items.forEach((item, index) => {
                    html += `
                        <a href="#" class="list-group-item list-group-item-action edit-item" 
                           data-id="${item.id}"
                           data-site="${siteCode}"
                           data-angka2d="${item.angka_2d}"
                           data-description="${item.description.replace(/"/g, '&quot;')}"
                           data-imageurl="${item.image_url || ''}"
                           onclick="selectEditItemFromData(this); return false;">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge bg-primary me-2">${item.angka_2d}</span>
                                    ${item.description.substring(0, 50)}${item.description.length > 50 ? '...' : ''}
                                </div>
                                ${item.image_url ? '<i class="bi bi-image text-success"></i>' : '<i class="bi bi-image text-muted"></i>'}
                            </div>
                        </a>
                    `;
                });
                html += '</div>';
                dataList.innerHTML = html;
            } else {
                dataList.innerHTML = `<div class="alert alert-info">Tidak ada data buku mimpi untuk situs ${siteCode}</div>`;
            }
        } else {
            dataList.innerHTML = `<div class="alert alert-danger">Error: ${data.message || 'Unknown error'}</div>`;
        }
    })
    .catch(error => {
        console.error('Fetch error:', error);
        dataList.innerHTML = `<div class="alert alert-danger">
            <strong>Error loading data:</strong><br>
            ${error.message}<br>
            <small>Check console untuk detail lebih lanjut</small>
        </div>`;
    });
}

function selectEditItem(id, site, angka2d, description, imageUrl) {// Check if form elements exist
    const editIdInput = document.getElementById('edit-id-input');
    const editSiteInput = document.getElementById('edit-site-input');
    const editAngka2d = document.getElementById('edit_angka_2d');
    const editDescription = document.getElementById('edit_description');
    const editCurrentImage = document.getElementById('edit-current-image');if (!editAngka2d || !editDescription) {
        console.error('Required form elements not found!');
        alert('Error: Form elements tidak ditemukan. Silakan refresh halaman.');
        return;
    }
    
    // Decode HTML entities dari description
    const decodedDescription = description.replace(/&#39;/g, "'").replace(/&quot;/g, '"').replace(/\\\\/g, '\\');
    const decodedImageUrl = imageUrl.replace(/&#39;/g, "'").replace(/&quot;/g, '"');// Populate form
    editIdInput.value = id;
    editSiteInput.value = site;
    editAngka2d.value = angka2d;
    editDescription.value = decodedDescription;
    editCurrentImage.value = decodedImageUrl;// Show current image if exists
    const imagePreview = document.getElementById('current-image-preview');
    const currentImage = document.getElementById('current-image');
    
    if (decodedImageUrl && decodedImageUrl !== '') {
        // Construct proper image path
        currentImage.src = `../${site}/uploads/buku-mimpi/${decodedImageUrl}`;
        imagePreview.style.display = 'block';
        
        // Handle image load error
        currentImage.onerror = function() {this.src = `../uploads/buku-mimpi/${decodedImageUrl}`;
            this.onerror = function() {imagePreview.style.display = 'none';
            };
        };
    } else {
        imagePreview.style.display = 'none';
    }
    
    // Enable form fields
    const editGambarMimpi = document.getElementById('edit_gambar_mimpi');
    const editSubmitBtn = document.getElementById('edit-submit-btn');
    
    editAngka2d.disabled = false;
    editDescription.disabled = false;
    if (editGambarMimpi) editGambarMimpi.disabled = false;
    if (editSubmitBtn) editSubmitBtn.disabled = false;// Visual feedback
    editAngka2d.style.backgroundColor = 'white';
    editDescription.style.backgroundColor = 'white';
    
    // Scroll ke form edit
    const formContainer = document.querySelector('#edit-tab .col-md-6:last-child');
    if (formContainer) {
        formContainer.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'start' 
        });
    }
    
    // Focus ke field pertama yang bisa diedit
    setTimeout(() => {
        editAngka2d.focus();}, 500);}

function selectEditItemFromData(element) {    
    try {
        // Get data from element attributes
        const id = element.getAttribute('data-id');
        const site = element.getAttribute('data-site');
        const angka2d = element.getAttribute('data-angka2d');
        const description = (element.getAttribute('data-description') || '').replace(/&quot;/g, '"');
        const imageUrl = element.getAttribute('data-imageurl') || '';        
        // Validate required data
        if (!id || !site || !angka2d || !description) {
            throw new Error('Missing required data: ' + JSON.stringify({id: !!id, site: !!site, angka2d: !!angka2d, description: !!description}));
        }
        
        // Call original function
        selectEditItem(id, site, angka2d, description, imageUrl);
        
        // Set active visual state
        setActiveEditItem(element);
        
    } catch (error) {
        console.error('Error in selectEditItemFromData:', error);
        alert('Error selecting item: ' + error.message);
    }
}

function setActiveEditItem(element) {
    // Remove active class from all items
    document.querySelectorAll('.edit-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // Add active class to selected item
    element.classList.add('active');
}

// Auto format 2D code for edit
document.getElementById('edit_angka_2d').addEventListener('input', function(e) {
    let value = e.target.value.replace(/[^0-9]/g, '');
    if (value.length > 2) value = value.substr(0, 2);
    e.target.value = value;
});

document.getElementById('edit_angka_2d').addEventListener('blur', function(e) {
    let value = e.target.value.replace(/[^0-9]/g, '');
    if (value.length === 1) {
        e.target.value = value.padStart(2, '0');
    } else if (value.length === 0) {
        e.target.value = '';
    }
});
</script>

<style>
/* Reduce excessive spacing */
.container-fluid {
    padding-top: 0;
    padding-bottom: 0;
}

.card-body {
    padding: 1rem;
}

/* Fix for hidden empty space issue */
.tab-content {
    padding-top: 0;
    min-height: auto !important;
    overflow: visible;
}

.tab-pane {
    min-height: auto !important;
    height: auto !important;
}

.tab-pane:not(.show) {
    display: none !important;
    height: 0 !important;
    padding: 0 !important;
    margin: 0 !important;
}

.tab-pane.show.active {
    display: block !important;
    height: auto !important;
    min-height: auto !important;
}

/* DEBUG: Remove any potential invisible content causing space */
.tab-pane.fade:not(.show) {
    position: absolute !important;
    left: -9999px !important;
    height: 0 !important;
    overflow: hidden !important;
}

/* Ensure main card doesn't have excessive padding */
.card .card-body {
    padding: 1rem !important;
}

.row {
    margin: 0;
}

.col-md-4 {
    padding: 0.5rem;
}

/* Fix for edit columns layout */
.tab-pane .row {
    display: flex;
    flex-wrap: wrap;
}

.tab-pane .col-md-6 {
    flex: 0 0 50%;
    max-width: 50%;
    padding: 0.75rem;
}

.tab-pane .card {
    height: 100%;
    margin-bottom: 0;
}

/* Ensure proper column closure */
.tab-pane::after {
    content: "";
    display: table;
    clear: both;
}

/* Additional clearfix for row elements */
.row::after {
    content: "";
    display: table;
    clear: both;
}

/* Remove any unwanted margins/padding from cards and containers */
.card-body {
    padding: 1rem;
}

.container-fluid {
    padding: 0.75rem !important;
}

/* CRITICAL: Remove any Bootstrap default spacing that causes empty areas */
.nav-tabs {
    margin-bottom: 1rem !important;
}

/* Force tab content to have no extra space */
.tab-content {
    padding: 0 !important;
    margin: 0 !important;
}

/* Force active tab to be compact */
.tab-pane.fade.show.active {
    padding-top: 0 !important;
    margin-top: 0 !important;
}

/* Fix floating issues */
.tab-content .tab-pane {
    overflow: visible !important;
}

/* Ensure cards don't create extra space */
.card {
    overflow: hidden;
    box-sizing: border-box;
    margin-bottom: 0 !important;
}

.admin-card {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border: none;
    border-radius: 12px;
}

.card-header {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border-radius: 12px 12px 0 0 !important;
}

.nav-tabs .nav-link {
    border: none;
    color: #6c757d;
    background: transparent;
    border-radius: 8px;
    margin-right: 5px;
}

.nav-tabs .nav-link.active {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border: none;
}

.form-control:focus, .form-select:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
}

.btn-primary:hover {
    background: linear-gradient(135deg, #764ba2, #667eea);
    transform: translateY(-1px);
}

.badge {
    border-radius: 6px;
    font-weight: 500;
}

.img-thumbnail {
    border-radius: 8px;
    border: 2px solid #e9ecef;
}

.table th {
    background-color: #f8f9fa;
    border-top: none;
    font-weight: 600;
    color: #495057;
}

.card {
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

#image-preview img:hover {
    transform: scale(1.05);
    transition: transform 0.2s ease;
}

.edit-item.active {
    background-color: #e7f3ff !important;
    border-color: #007bff !important;
    color: #007bff !important;
}

.edit-item:hover {
    background-color: #f8f9fa;
    cursor: pointer;
}

.form-control:disabled {
    background-color: #f8f9fa;
    opacity: 0.6;
}

.form-control:enabled {
    background-color: white;
    opacity: 1;
    border-color: #ced4da;
}
</style>

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