<?php
session_start();

// ==========================================
// PENGATURAN ADMIN & DATABASE
// ==========================================
$ADMIN_PASSWORD = 'texa'; // SILAKAN GANTI PASSWORD INI
$DATA_FILE = 'database.json'; // Nama file database otomatis

// Inisialisasi Data Default jika file database belum ada di hosting
if (!file_exists($DATA_FILE)) {
    $defaultData = [
        "header" => [
            "title" => "texa.studio",
            "subtitle" => "Platform All-in-One Akses Tools AI Premium (ChatGPT, Gemini, Midjourney, & Lainnya)"
        ],
        "products" => [
            [ "id" => 1, "title" => "ChatGPT Plus", "category" => "AI Text Assistant", "price" => "Rp 250rb", "image" => "https://images.unsplash.com/photo-1677442136019-21780ecad995?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Akses premium ke ChatGPT model terbaru. Sangat cocok untuk menulis artikel, coding, dan analisis data dengan penalaran tingkat lanjut. Langganan 1 bulan full garansi.", "link" => "#" ],
            [ "id" => 2, "title" => "Gemini Advanced", "category" => "Multimodal AI", "price" => "Rp 299rb", "image" => "https://images.unsplash.com/photo-1697577418970-95d99b5a55cf?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Model AI paling canggih dari Google. Mendukung multimodal (teks, gambar, dokumen, kode). Terintegrasi dengan ekosistem Google Workspace.", "link" => "#" ],
            [ "id" => 3, "title" => "Midjourney v6", "category" => "AI Image Generator", "price" => "Rp 450rb", "image" => "https://images.unsplash.com/photo-1686191128892-3b37013f73ff?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Hasilkan gambar fotorealistik dan karya seni digital memukau hanya dengan teks (prompt). Versi 6 memiliki pemahaman bahasa yang jauh lebih baik.", "link" => "#" ],
            [ "id" => 4, "title" => "OpenAI Sora API", "category" => "AI Video Generator", "price" => "Rp 750rb", "image" => "https://images.unsplash.com/photo-1682687220742-aba13b6e50ba?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Ubah teks Anda menjadi video beresolusi tinggi yang sangat realistis hingga 1 menit. Cocok untuk kreator konten dan pembuat iklan.", "link" => "#" ],
            [ "id" => 5, "title" => "Claude 3 Opus", "category" => "Advanced Reasoning", "price" => "Rp 350rb", "image" => "https://images.unsplash.com/photo-1620712943543-bcc4688e7485?auto=format&fit=crop&w=600&h=400&q=80", "description" => "AI cerdas dengan nuansa tulisan yang lebih natural seperti manusia. Sangat ahli dalam membaca dokumen PDF panjang dan meringkasnya.", "link" => "#" ],
            [ "id" => 6, "title" => "GitHub Copilot", "category" => "AI Code Assistant", "price" => "Rp 150rb", "image" => "https://images.unsplash.com/photo-1655635643532-fa9ba2648cbe?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Asisten coding bertenaga AI yang siap menemani Anda ngoding. Auto-complete baris kode dan temukan bug dengan lebih cepat.", "link" => "#" ],
            [ "id" => 7, "title" => "Canva Magic Studio", "category" => "AI Design Tool", "price" => "Rp 120rb", "image" => "https://images.unsplash.com/photo-1611162617474-5b21e879e113?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Suite lengkap AI dari Canva untuk menghapus background instan, meresize desain ke berbagai ukuran socmed otomatis, dan membuat presentasi ciamik.", "link" => "#" ],
            [ "id" => 8, "title" => "Notion AI", "category" => "AI Workspace", "price" => "Rp 180rb", "image" => "https://images.unsplash.com/photo-1611224923853-80b023f02d71?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Notion yang diperkuat AI. Bisa menulis draf meeting, merapikan catatan, dan mengekstrak poin-poin penting langsung di dalam workspace Anda.", "link" => "#" ],
            [ "id" => 9, "title" => "Runway Gen-2", "category" => "AI Video Editor", "price" => "Rp 550rb", "image" => "https://images.unsplash.com/photo-1633419461186-7d40a38105ec?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Editor video AI di browser. Fitur inpainting video, text-to-video, dan alat manipulasi video profesional lainnya.", "link" => "#" ],
            [ "id" => 10, "title" => "ElevenLabs Pro", "category" => "AI Voice Generator", "price" => "Rp 200rb", "image" => "https://images.unsplash.com/photo-1589903308904-1010c2294adc?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Hasilkan suara AI (text-to-speech) yang paling emosional dan realistis di pasaran saat ini. Bisa melakukan voice cloning dari suara Anda sendiri.", "link" => "#" ],
            [ "id" => 11, "title" => "Jasper AI", "category" => "AI Copywriter", "price" => "Rp 399rb", "image" => "https://images.unsplash.com/photo-1542621334-a2542d773e41?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Platform AI terfokus untuk pemasar/marketer. Punya ratusan template siap pakai untuk menulis artikel blog, iklan FB, email marketing, dll.", "link" => "#" ],
            [ "id" => 12, "title" => "Leonardo AI", "category" => "AI Image Creator", "price" => "Rp 250rb", "image" => "https://images.unsplash.com/photo-1678286742832-26543bb49959?auto=format&fit=crop&w=600&h=400&q=80", "description" => "Alternatif Midjourney yang powerful dengan fitur pengaturan presisi dan kustomisasi model aset game serta ilustrasi tingkat dewa.", "link" => "#" ]
        ],
        "viewMode" => "grid"
    ];
    file_put_contents($DATA_FILE, json_encode($defaultData, JSON_PRETTY_PRINT));
}

// ==========================================
// API & ROUTING BACKEND
// ==========================================
// 1. Membaca Input mentah (raw data) untuk request JSON dari javascript
$rawInput = file_get_contents('php://input');
$jsonInput = json_decode($rawInput, true);

// 2. Proses Login
if (isset($_POST['action']) && $_POST['action'] === 'login') {
    if ($_POST['password'] === $ADMIN_PASSWORD) {
        $_SESSION['admin_logged_in'] = true;
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Password salah!']);
    }
    exit;
}

// 3. Proses Logout
if (isset($_POST['action']) && $_POST['action'] === 'logout') {
    session_destroy();
    echo json_encode(['status' => 'success']);
    exit;
}

// 4. Proses Simpan Data ke Database JSON (Hanya jika login)
if (isset($jsonInput['action']) && $jsonInput['action'] === 'save_data') {
    header('Content-Type: application/json');
    if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
        if (isset($jsonInput['data'])) {
            // Tulis dan simpan ke file
            $saveResult = file_put_contents($DATA_FILE, json_encode($jsonInput['data'], JSON_PRETTY_PRINT));
            
            if ($saveResult !== false) {
                echo json_encode(['status' => 'success']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Gagal menulis ke server, periksa file permission database.json']);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Payload data kosong!']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Akses ditolak']);
    }
    exit;
}

// Membaca Data untuk ditampilkan di HTML
$appDataJson = file_get_contents($DATA_FILE);
$isAdminLoggedIn = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true ? 'true' : 'false';
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Texa Studio</title>
    
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:200,400,600,700" rel="stylesheet">
    
    <style>
        body { background: #f4f7f6; font-family: 'Open Sans', sans-serif; padding-top: 70px; }
        .navbar-custom { background-color: #fff; border-bottom: 2px solid #20e3b2; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .navbar-custom .navbar-brand { color: #1a1a1a; font-weight: 700; letter-spacing: 1px;}
        #navbar-admin { background-color: #1a1a1a; border-color: #000; border-bottom: none; }
        #navbar-admin .navbar-brand, #navbar-admin .navbar-nav>li>a { color: #fff; }
        #navbar-admin .navbar-nav>li>a:hover { color: #20e3b2; }
        .admin-badge { background: #e74c3c; padding: 3px 8px; border-radius: 4px; font-size: 12px; margin-left: 5px;}
        
        .navbar-brand { display: flex !important; align-items: center; height: 50px; padding-top: 0; padding-bottom: 0; }
        .jumbotron-store { background: linear-gradient(135deg, #0cebeb, #20e3b2, #29ffc6); color: #fff; border-radius: 12px; margin-top: 10px; padding: 50px 20px; text-shadow: 1px 1px 3px rgba(0,0,0,0.15); box-shadow: 0 5px 15px rgba(32, 227, 178, 0.2); }
        .store-body { background: transparent; padding: 0; box-shadow: none; }
        .well-controls { background: #fff; border: none; border-radius: 8px; padding: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .item { transition: all 0.3s ease; margin-bottom: 30px; }
        .thumbnail { margin-bottom: 0; padding: 0; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.08); border: none; background: #fff; position: relative; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .thumbnail:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.15); }
        .thumbnail img { object-fit: cover; width: 100%; height: 200px; }
        .category { position: absolute; top: 12px; left: 12px; background: rgba(26, 26, 26, 0.85); padding: 5px 12px; border-radius: 20px; color: #20e3b2; font-weight: 600; font-size: 11px; z-index: 2; }
        .category-name { margin: 0; font-size: 11px; letter-spacing: 0.5px; text-transform: uppercase;}
        .caption { padding: 20px; }
        .list-group-item-heading { font-weight: 700; font-size: 17px; margin-bottom: 8px; color: #1a1a1a; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .lead { font-weight: 700; font-size: 18px; color: #333; margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 15px; }
        .card-actions { display: flex; gap: 10px; width: 100%; }
        .card-actions .btn { flex: 1; border-radius: 6px; font-weight: 600; font-size: 13px; padding: 8px 0; transition: all 0.2s; }
        .btn-details { background: transparent; border: 1px solid #ddd; color: #555; }
        .btn-details:hover { background: #f8f9fa; color: #000; border-color: #ccc; }
        .btn-success { background: linear-gradient(to right, #0cebeb, #20e3b2); border: none; color: #000; }
        .btn-success:hover { opacity: 0.85; color: #000; }
        
        .item.list-group-item { width: 100%; padding: 0 15px; float: none; clear: both; margin-bottom: 20px; }
        .item.list-group-item .thumbnail { display: flex; flex-direction: row; width: 100%; }
        .item.list-group-item .thumbnail img { width: 35%; height: 220px; }
        .item.list-group-item .caption { width: 65%; display: flex; flex-direction: column; justify-content: center; padding: 25px; }
        .item.list-group-item .lead { border-bottom: none; padding-bottom: 0; }
        .item.list-group-item .card-actions { justify-content: flex-start; margin-top: auto;}
        .item.list-group-item .card-actions .btn { flex: none; width: 140px; }
        
        @media (max-width: 767px) {
            .jumbotron-store { padding: 30px 15px; }
            .jumbotron-store h1 { font-size: 28px; }
            .item.list-group-item .thumbnail { flex-direction: column; }
            .item.list-group-item .thumbnail img { width: 100%; height: 200px; }
            .item.list-group-item .caption { width: 100%; padding: 15px; }
            .item.list-group-item .card-actions { width: 100%; display: flex; }
            .item.list-group-item .card-actions .btn { flex: 1; width: auto; }
        }
        
        #view-admin, #view-store, #navbar-admin, #navbar-store, #view-login, #view-product-detail { display: none; }
        .admin-header-settings, .admin-products-settings { background: #fff; padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); margin-bottom: 25px; }
        .table>tbody>tr>td { vertical-align: middle; }
        .product-thumb-admin { width: 60px; height: 60px; object-fit: cover; border-radius: 6px; }
        .table-responsive { border: none; }
        .brand-logo { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; margin-right: 10px; border: 2px solid #20e3b2; box-shadow: 0 0 10px #20e3b2, 0 0 20px #20e3b2; animation: glow-pulse 1.5s infinite alternate; flex-shrink: 0; }
        .brand-name { text-transform: uppercase; font-weight: 900; font-size: 21px; letter-spacing: 1.5px; color: #000; text-shadow: 0 1px 1px rgba(0,0,0,0.1); }
        #navbar-admin .brand-name { color: #fff; text-shadow: none; }
        @keyframes glow-pulse { 0% { box-shadow: 0 0 5px #20e3b2, 0 0 10px rgba(32, 227, 178, 0.5); } 100% { box-shadow: 0 0 15px #20e3b2, 0 0 30px rgba(32, 227, 178, 0.8); } }
        
        /* CSS Halaman Detail */
        .detail-wrapper { background: #fff; border-radius: 12px; padding: 30px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); margin-top: 15px; }
        .detail-image { width: 100%; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); object-fit: cover; max-height: 400px; }
        .detail-title { font-weight: 800; color: #1a1a1a; margin-top: 15px; margin-bottom: 10px; font-size: 32px; }
        .detail-price { color: #20e3b2; font-weight: 700; font-size: 28px; margin-top: 0; }
        .detail-description { font-size: 16px; line-height: 1.8; color: #555; white-space: pre-wrap; margin-bottom: 30px; }
        .btn-back { margin-bottom: 20px; font-weight: 600; color: #555; border: none; background: #eee; padding: 8px 20px; border-radius: 20px; }
        .btn-back:hover { background: #ddd; }
    </style>
</head>
<body>

    <!-- Navigasi Publik -->
    <nav id="navbar-store" class="navbar navbar-custom navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" id="nav-brand-text" href="#/"></a>
        </div>
      </div>
    </nav>

    <!-- Navigasi Admin -->
    <nav id="navbar-admin" class="navbar navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-admin" style="border-color:#333;">
                <span class="icon-bar" style="background-color:#fff;"></span>
                <span class="icon-bar" style="background-color:#fff;"></span>
                <span class="icon-bar" style="background-color:#fff;"></span>
            </button>
          <a class="navbar-brand" href="#/">
              <img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMDZ1aWRqZWt6Z3U4dGVldWxhOGd2YnF6dGMzeDB3cWcwZWdwb2t2ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dXlUFmuOWFRlHYgc9i/giphy.gif" alt="Logo" class="brand-logo"><span class="brand-name">Texa.Studio</span> <span class="admin-badge">Admin</span>
          </a>
        </div>
        <div class="collapse navbar-collapse" id="navbar-collapse-admin">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#/" onclick="navigateTo('#/')"><span class="glyphicon glyphicon-globe"></span> Lihat Tampilan Publik</a></li>
            <li><a href="#" onclick="doLogout()"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>
          </ul>
        </div>
      </div>
    </nav>

    <!-- ========================================== -->
    <!--            HALAMAN LOGIN ADMIN             -->
    <!-- ========================================== -->
    <div id="view-login" class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4" style="margin-top: 100px;">
                <div class="well" style="background: #fff; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); padding: 30px;">
                    <div class="text-center" style="margin-bottom: 20px;">
                        <img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMDZ1aWRqZWt6Z3U4dGVldWxhOGd2YnF6dGMzeDB3cWcwZWdwb2t2ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dXlUFmuOWFRlHYgc9i/giphy.gif" alt="Logo" class="brand-logo" style="width:60px; height:60px; margin:0 auto 15px;">
                        <h3 style="font-weight: 700; margin:0;">Login Pengelola</h3>
                    </div>
                    <div class="form-group">
                        <label>Password Admin</label>
                        <input type="password" id="login-password" class="form-control" placeholder="Masukkan password">
                    </div>
                    <button class="btn btn-success btn-block" onclick="doLogin()" style="border-radius: 6px; font-weight: bold; margin-top: 20px;">Masuk Sistem</button>
                    <p id="login-error" class="text-danger text-center" style="margin-top:15px; display:none;"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- ========================================== -->
    <!--              TAMPILAN TOKO                 -->
    <!-- ========================================== -->
    <div id="view-store" class="container store-body">
        <div class="jumbotron text-center jumbotron-store">
            <h1 id="store-title" style="font-weight: 700; letter-spacing: 1px; margin-bottom: 10px;"></h1>
            <p id="store-subtitle" style="font-size: 16px; color: #fff; opacity: 0.9;"></p>
        </div>
        <div class="well-controls">
            <div id="view" class="btn-group">
                <a href="#" id="grid" class="btn btn-default btn-sm active"><span class="glyphicon glyphicon-th"></span> Grid</a>
                <a href="#" id="list" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-th-list"></span> List</a> 
            </div>
        </div>
        <div id="products-container" class="row"></div>
    </div>

    <!-- ========================================== -->
    <!--         HALAMAN DETAIL PRODUK              -->
    <!-- ========================================== -->
    <div id="view-product-detail" class="container">
        <button class="btn btn-back" onclick="navigateTo('#/')"><span class="glyphicon glyphicon-arrow-left"></span> Kembali ke Daftar</button>
        <div class="detail-wrapper">
            <div class="row">
                <div class="col-md-6">
                    <img id="detail-image" src="" alt="Product" class="detail-image">
                </div>
                <div class="col-md-6" style="padding-top: 15px;">
                    <span id="detail-category" class="label" style="background-color: #1a1a1a; color: #20e3b2; padding: 6px 15px; border-radius: 20px; letter-spacing: 1px; text-transform: uppercase;"></span>
                    <h2 id="detail-title" class="detail-title"></h2>
                    <h3 id="detail-price" class="detail-price"></h3>
                    <hr>
                    <h4><strong>Detail & Deskripsi</strong></h4>
                    <p id="detail-description" class="detail-description"></p>
                    
                    <a id="detail-link" href="#" target="_blank" class="btn btn-success btn-lg" style="border-radius: 8px; font-weight: bold; padding: 12px 30px; font-size: 16px; box-shadow: 0 4px 15px rgba(32, 227, 178, 0.4);"><span class="glyphicon glyphicon-shopping-cart"></span> Dapatkan Akses Sekarang</a>
                </div>
            </div>
        </div>
    </div>


    <!-- ========================================== -->
    <!--            DASHBOARD ADMIN                 -->
    <!-- ========================================== -->
    <div id="view-admin" class="container">
        <h2 style="margin-bottom: 25px; font-weight: 700; color: #1a1a1a;">Dashboard Pengelola</h2>
        
        <div class="admin-header-settings">
            <h4 style="font-weight: 600;"><span class="glyphicon glyphicon-text-size"></span> Pengaturan Teks Header</h4>
            <hr>
            <div class="row">
                <div class="col-md-6 form-group">
                    <label>Judul Toko (Nama Brand)</label>
                    <input type="text" id="input-header-title" class="form-control">
                </div>
                <div class="col-md-6 form-group">
                    <label>Deskripsi/Subtitle Toko</label>
                    <input type="text" id="input-header-subtitle" class="form-control">
                </div>
            </div>
            <button class="btn btn-primary" onclick="saveHeader()"><span class="glyphicon glyphicon-floppy-disk"></span> Simpan Header</button>
        </div>

        <div class="admin-products-settings">
            <div class="row" style="margin-bottom: 20px;">
                <div class="col-xs-12 col-sm-6">
                    <h4 style="font-weight: 600; margin-top: 5px;"><span class="glyphicon glyphicon-list-alt"></span> Kelola Produk AI</h4>
                </div>
                <div class="col-xs-12 col-sm-6 text-right">
                    <button class="btn btn-success" onclick="openProductModal()"><span class="glyphicon glyphicon-plus"></span> Tambah Produk Baru</button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead style="background: #f8f9fa;">
                        <tr>
                            <th>Gambar</th>
                            <th>Info Produk</th>
                            <th>Harga</th>
                            <th>Link</th>
                            <th class="text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="admin-products-tbody"></tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal Form Produk -->
    <div class="modal fade" id="productModal" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content" style="border-radius: 12px; border: none;">
          <div class="modal-header" style="background: #f8f9fa; border-radius: 12px 12px 0 0;">
            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="productModalLabel" style="font-weight: 600;">Tambah/Edit Produk</h4>
          </div>
          <div class="modal-body">
            <input type="hidden" id="form-product-id">
            <div class="row">
                <div class="col-md-6 form-group">
                    <label>Nama Produk</label>
                    <input type="text" class="form-control" id="form-product-title">
                </div>
                <div class="col-md-6 form-group">
                    <label>Kategori</label>
                    <input type="text" class="form-control" id="form-product-category">
                </div>
            </div>
            <div class="form-group">
                <label>Harga</label>
                <input type="text" class="form-control" id="form-product-price">
            </div>
            <div class="form-group">
                <label>Deskripsi Produk Lengkap</label>
                <textarea class="form-control" id="form-product-description" rows="4" placeholder="Jelaskan fitur, kelebihan, atau durasi akses produk..."></textarea>
            </div>
            <div class="form-group">
                <label>URL Gambar Mockup</label>
                <input type="text" class="form-control" id="form-product-image">
            </div>
            <div class="form-group" style="background: #f4f7f6; padding: 10px; border-radius: 6px; border: 1px dashed #ccc;">
                <label><span class="glyphicon glyphicon-upload"></span> Atau Unggah Gambar Lokal</label>
                <input type="file" class="form-control" id="form-product-image-file" accept="image/*" style="border: none; background: transparent; padding-left: 0; box-shadow: none;">
                <small class="text-muted">Pilih gambar dari perangkat. (Disarankan foto di bawah 2MB agar load cepat)</small>
            </div>
            <div class="form-group">
                <label>Link Redirect "Beli Akses"</label>
                <input type="text" class="form-control" id="form-product-link">
            </div>
          </div>
          <div class="modal-footer" style="border-top: none; padding-top: 0;">
            <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
            <button type="button" class="btn btn-primary" onclick="saveProduct()">Simpan Produk</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Script -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script>
        // Data dari PHP
        let appData = <?php echo $appDataJson; ?>;
        let isAdminLoggedIn = <?php echo $isAdminLoggedIn; ?>;

        // Memastikan deskripsi default tidak kosong jika file lama sudah ada
        if (appData && appData.products) {
            appData.products = appData.products.map(p => {
                if(!p.description) p.description = "Produk AI premium dari Texa Studio.";
                return p;
            });
        }

        // ==========================================
        //         FUNGSI KOMUNIKASI SERVER
        // ==========================================
        function doLogin() {
            const pwd = $('#login-password').val();
            $.post('', { action: 'login', password: pwd }, function(response) {
                const res = JSON.parse(response);
                if(res.status === 'success') {
                    isAdminLoggedIn = true;
                    router(); // Refresh halaman
                } else {
                    $('#login-error').text(res.message).show();
                }
            });
        }

        function doLogout() {
            $.post('', { action: 'logout' }, function(response) {
                isAdminLoggedIn = false;
                window.location.hash = '';
                router();
            });
        }

        function syncDataToServer(callback) {
            const oldHtml = $('.admin-header-settings .btn-primary, #productModal .btn-primary').html();
            
            $.ajax({
                url: '',
                type: 'POST',
                data: JSON.stringify({ action: 'save_data', data: appData }),
                contentType: 'application/json; charset=utf-8',
                success: function(response) {
                    try {
                        const res = typeof response === 'string' ? JSON.parse(response) : response;
                        if(res.status === 'success') {
                            if(callback) callback();
                        } else {
                            alert("Terjadi kesalahan sistem: " + res.message);
                        }
                    } catch(e) {
                        alert("Gagal merespons dari server. File JSON mungkin terlalu besar (batas server PHP). Coba gambar dengan ukuran lebih kecil.");
                    }
                },
                error: function(xhr) {
                    alert("Koneksi gagal atau file gambar terlalu besar untuk ditangani server (" + xhr.status + ").");
                }
            });
        }

        // ==========================================
        //             ROUTING SYSTEM
        // ==========================================
        function router() {
            const hash = window.location.hash;

            // Sembunyikan semua tampilan utama
            $('#view-admin, #navbar-admin, #view-login, #view-store, #navbar-store, #view-product-detail').hide();

            if (hash === '#admin') {
                if(isAdminLoggedIn) {
                    $('#view-admin, #navbar-admin').fadeIn();
                    renderAdminTable();
                } else {
                    $('#view-login').fadeIn();
                }
            } else if (hash.startsWith('#product-')) {
                // Rute untuk Halaman Detail
                const productId = parseInt(hash.replace('#product-', ''));
                $('#navbar-store, #view-product-detail').fadeIn();
                renderProductDetail(productId);
            } else {
                // Halaman Utama Toko
                $('#view-store, #navbar-store').fadeIn();
                renderStore();
            }
        }

        function navigateTo(route) { 
            window.location.hash = route; 
            // router() dipanggil secara otomatis oleh event hashchange
        }

        // ==========================================
        //        FUNGSI RENDER TAMPILAN
        // ==========================================
        function renderStore() {
            $('#nav-brand-text').html(`<img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMDZ1aWRqZWt6Z3U4dGVldWxhOGd2YnF6dGMzeDB3cWcwZWdwb2t2ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dXlUFmuOWFRlHYgc9i/giphy.gif" alt="Logo" class="brand-logo"><span class="brand-name">${appData.header.title}</span>`);
            $('#store-title').text(appData.header.title);
            $('#store-subtitle').text(appData.header.subtitle);

            const container = $('#products-container');
            container.empty();

            appData.products.forEach(prod => {
                const gridClasses = appData.viewMode === 'list' ? 'item list-group-item' : 'item col-xs-12 col-sm-6 col-md-4 col-lg-3 grid-group-item';
                const html = `
                <div class="${gridClasses}">
                    <div class="thumbnail">
                        <div class="category"><h5 class="category-name">${prod.category}</h5></div>
                        <img src="${prod.image}" alt="${prod.title}" loading="lazy" />
                        <div class="caption">
                            <h4 class="list-group-item-heading">${prod.title}</h4>
                            <p class="lead">${prod.price}</p>
                            <div class="card-actions">
                                <a class="btn btn-details" href="#product-${prod.id}">Detail</a>
                                <a class="btn btn-success" href="${prod.link}" target="_blank">Beli Akses</a>
                            </div>
                        </div>
                    </div>
                </div>`;
                container.append(html);
            });
        }

        function renderProductDetail(id) {
            const prod = appData.products.find(p => p.id === id);
            if (prod) {
                // Pasang teks navbar agar konsisten
                $('#nav-brand-text').html(`<img src="https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMDZ1aWRqZWt6Z3U4dGVldWxhOGd2YnF6dGMzeDB3cWcwZWdwb2t2ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dXlUFmuOWFRlHYgc9i/giphy.gif" alt="Logo" class="brand-logo"><span class="brand-name">${appData.header.title}</span>`);
                
                $('#detail-image').attr('src', prod.image);
                $('#detail-category').text(prod.category);
                $('#detail-title').text(prod.title);
                $('#detail-price').text(prod.price);
                $('#detail-description').text(prod.description || 'Tidak ada deskripsi tersedia.');
                $('#detail-link').attr('href', prod.link);
            } else {
                // Jika produk tidak ditemukan, kembali ke home
                navigateTo('#/');
            }
        }

        function renderAdminTable() {
            $('#input-header-title').val(appData.header.title);
            $('#input-header-subtitle').val(appData.header.subtitle);

            const tbody = $('#admin-products-tbody');
            tbody.empty();

            appData.products.forEach(prod => {
                const tr = `
                <tr>
                    <td><img src="${prod.image}" class="product-thumb-admin" alt="thumb"></td>
                    <td><strong style="font-size: 15px;">${prod.title}</strong><br><span class="text-muted" style="font-size: 12px;">${prod.category}</span></td>
                    <td><strong>${prod.price}</strong></td>
                    <td><a href="${prod.link}" target="_blank" class="btn btn-default btn-xs">Cek Link</a></td>
                    <td class="text-center">
                        <button class="btn btn-sm btn-primary" onclick="editProduct(${prod.id})" title="Edit"><span class="glyphicon glyphicon-pencil"></span></button>
                        <button class="btn btn-sm btn-danger" onclick="deleteProduct(${prod.id})" title="Hapus"><span class="glyphicon glyphicon-trash"></span></button>
                    </td>
                </tr>`;
                tbody.append(tr);
            });
        }

        // ==========================================
        //        FUNGSI CRUD ADMIN
        // ==========================================
        function saveHeader() {
            appData.header.title = $('#input-header-title').val();
            appData.header.subtitle = $('#input-header-subtitle').val();
            syncDataToServer(function() {
                const btn = $('.admin-header-settings .btn-primary');
                btn.html('<span class="glyphicon glyphicon-ok"></span> Tersimpan!');
                btn.removeClass('btn-primary').addClass('btn-success');
                setTimeout(() => { btn.html('<span class="glyphicon glyphicon-floppy-disk"></span> Simpan Header'); btn.removeClass('btn-success').addClass('btn-primary'); }, 2000);
            });
        }

        function openProductModal() {
            $('#form-product-id').val('');
            $('#form-product-title, #form-product-category, #form-product-price, #form-product-description, #form-product-image, #form-product-link, #form-product-image-file').val('');
            $('#productModalLabel').text('Tambah Produk Baru');
            $('#productModal').modal('show');
        }

        function editProduct(id) {
            const prod = appData.products.find(p => p.id === id);
            if(prod) {
                $('#form-product-id').val(prod.id);
                $('#form-product-title').val(prod.title);
                $('#form-product-category').val(prod.category);
                $('#form-product-price').val(prod.price);
                $('#form-product-description').val(prod.description || '');
                $('#form-product-image').val(prod.image);
                $('#form-product-link').val(prod.link);
                $('#form-product-image-file').val('');
                $('#productModalLabel').text('Edit Produk');
                $('#productModal').modal('show');
            }
        }

        function saveProduct() {
            const fileInput = document.getElementById('form-product-image-file');
            
            // Tampilkan tombol memuat
            const saveBtn = $('#productModal .btn-primary');
            saveBtn.html('<span class="glyphicon glyphicon-refresh" style="animation: spin 1s infinite linear;"></span> Menyimpan...');
            saveBtn.prop('disabled', true);

            if (fileInput.files && fileInput.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) { processSaveProduct(e.target.result, saveBtn); };
                reader.readAsDataURL(fileInput.files[0]);
            } else {
                const imageUrl = $('#form-product-image').val() || 'https://images.unsplash.com/photo-1620712943543-bcc4688e7485?auto=format&fit=crop&w=600&h=400&q=80';
                processSaveProduct(imageUrl, saveBtn);
            }
        }

        function processSaveProduct(imageSrc, saveBtn) {
            const idVal = $('#form-product-id').val();
            const prodData = {
                title: $('#form-product-title').val() || 'Tanpa Nama',
                category: $('#form-product-category').val() || '-',
                price: $('#form-product-price').val() || '-',
                description: $('#form-product-description').val() || 'Tidak ada deskripsi tersedia.',
                image: imageSrc,
                link: $('#form-product-link').val() || '#'
            };

            if (idVal) {
                const index = appData.products.findIndex(p => p.id === parseInt(idVal));
                if(index !== -1) appData.products[index] = { id: parseInt(idVal), ...prodData };
            } else {
                const newId = appData.products.length > 0 ? Math.max(...appData.products.map(p => p.id)) + 1 : 1;
                appData.products.push({ id: newId, ...prodData });
            }

            syncDataToServer(function() {
                saveBtn.html('Simpan Produk').prop('disabled', false);
                $('#productModal').modal('hide');
                renderAdminTable();
            });
            
            // Cadangan jika gagal sync
            setTimeout(() => { saveBtn.html('Simpan Produk').prop('disabled', false); }, 3000);
        }

        function deleteProduct(id) {
            if(confirm("Yakin ingin menghapus produk ini?")) {
                appData.products = appData.products.filter(p => p.id !== id);
                syncDataToServer(function() { renderAdminTable(); });
            }
        }

        // ==========================================
        //               INISIALISASI
        // ==========================================
        $(document).ready(function() {
            // Tambah style spin animasi
            $('<style>@keyframes spin { 100% { transform: rotate(360deg); } }</style>').appendTo('head');

            router();
            $(window).on('hashchange', router);

            // Fitur Enter untuk Login
            $('#login-password').keypress(function(e) { if(e.which == 13) doLogin(); });

            $('#list').click(function(e){
                e.preventDefault(); appData.viewMode = 'list';
                $(this).addClass('active'); $('#grid').removeClass('active');
                renderStore(); syncDataToServer();
            });
            $('#grid').click(function(e){
                e.preventDefault(); appData.viewMode = 'grid';
                $(this).addClass('active'); $('#list').removeClass('active');
                renderStore(); syncDataToServer();
            });
        });
    </script>
</body>
</html>