<?php
$page_title = "Kelola Produk Kue";
$header_title = "Manajemen Produk Toko Kue Edelys";
require_once __DIR__ . '/../includes/admin_header.php';

$message = '';
$error = '';

// 1. PROSES TAMBAH KATEGORI BARU
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_category') {
    $new_category_name = trim($_POST['new_category_name']);
    if (empty($new_category_name)) {
        $error = "Nama kategori kue baru tidak boleh kosong.";
    } else {
        try {
            $stmt = $db->prepare("INSERT INTO categories (name) VALUES (?)");
            $stmt->execute([$new_category_name]);
            $message = "Kategori kue baru '" . htmlspecialchars($new_category_name) . "' berhasil ditambahkan.";
        } catch (PDOException $e) {
            $error = "Gagal menambah kategori. Kategori '" . htmlspecialchars($new_category_name) . "' mungkin sudah ada.";
        }
    }
}

// 2. PROSES SIMPAN / UPDATE PRODUK
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_product') {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $name = trim($_POST['name']);
    $category_select = trim($_POST['category_select']);
    $category_custom = trim($_POST['category_custom']);
    $price = floatval($_POST['price']);
    $description = trim($_POST['description']);
    
    // Tentukan kategori akhir
    $category = $category_select;
    if ($category_select === 'new_custom' && !empty($category_custom)) {
        $category = $category_custom;
        // Simpan otomatis ke master categories jika belum ada
        try {
            $stmt_cat = $db->prepare("INSERT IGNORE INTO categories (name) VALUES (?)");
            $stmt_cat->execute([$category]);
        } catch (Exception $e) {}
    }

    // Handle Gambar Kue (Upload file ATAU pilih dari yang sudah ada)
    $image_url = isset($_POST['image_url_existing']) ? trim($_POST['image_url_existing']) : '';
    
    if (isset($_FILES['product_image']) && $_FILES['product_image']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['product_image'];
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($ext, $allowed_extensions)) {
            $error = "Format file gambar kue tidak didukung. Gunakan JPG, JPEG, PNG, atau WEBP.";
        } elseif ($file['size'] > 5 * 1024 * 1024) {
            $error = "Ukuran file foto kue terlalu besar. Maksimal 5MB.";
        } else {
            $upload_dir = __DIR__ . '/../assets/uploads/products';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $filename = 'cake_' . time() . '_' . rand(100, 999) . '.' . $ext;
            $dest = $upload_dir . '/' . $filename;
            
            if (move_uploaded_file($file['tmp_name'], $dest)) {
                $image_url = 'assets/uploads/products/' . $filename;
            } else {
                $error = "Gagal mengunggah foto kue ke folder tujuan.";
            }
        }
    }

    if (empty($error)) {
        if (empty($name) || empty($category) || $price <= 0 || empty($description)) {
            $error = "Semua kolom wajib diisi dengan benar (harga harus lebih dari 0).";
        } elseif (empty($image_url) && $id == 0) {
            $error = "Harap unggah foto kue atau pilih gambar kue pendukung.";
        } else {
            if ($id > 0) {
                // Update produk yang ada
                // Jika tidak ada gambar baru diunggah & tidak ada opsi terpilih, tetap pakai image_url lama
                if (empty($image_url)) {
                    $stmt_old = $db->prepare("SELECT image_url FROM products WHERE id = ?");
                    $stmt_old->execute([$id]);
                    $image_url = $stmt_old->fetchColumn();
                }

                try {
                    $stmt = $db->prepare("UPDATE products SET name = ?, category = ?, price = ?, description = ?, image_url = ? WHERE id = ?");
                    $stmt->execute([$name, $category, $price, $description, $image_url, $id]);
                    $message = "Produk '" . htmlspecialchars($name) . "' berhasil diperbarui.";
                } catch (PDOException $e) {
                    $error = "Gagal memperbarui produk: " . $e->getMessage();
                }
            } else {
                // Tambah produk baru
                $initial_stock = isset($_POST['stock']) ? intval($_POST['stock']) : 0;
                if ($initial_stock < 0) {
                    $initial_stock = 0;
                }
                
                $db->beginTransaction();
                try {
                    $stmt = $db->prepare("INSERT INTO products (name, category, price, stock, description, image_url, is_active) VALUES (?, ?, ?, ?, ?, ?, 1)");
                    $stmt->execute([$name, $category, $price, $initial_stock, $description, $image_url]);
                    $new_product_id = $db->lastInsertId();
                    
                    // Catat ke log stok awal
                    if ($initial_stock > 0) {
                        $log_stmt = $db->prepare("INSERT INTO stock_logs (product_id, quantity_change, type, notes) VALUES (?, ?, 'in', ?)");
                        $log_stmt->execute([$new_product_id, $initial_stock, 'Stok awal saat menambahkan produk baru']);
                    }
                    
                    $db->commit();
                    $message = "Produk baru '" . htmlspecialchars($name) . "' berhasil ditambahkan.";
                } catch (Exception $e) {
                    $db->rollBack();
                    $error = "Gagal menambahkan produk baru: " . $e->getMessage();
                }
            }
        }
    }
}

// 3. PROSES AKTIFKAN / NONAKTIFKAN PRODUK
if (isset($_GET['toggle_active']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $status = intval($_GET['toggle_active']);
    
    try {
        $stmt = $db->prepare("UPDATE products SET is_active = ? WHERE id = ?");
        $stmt->execute([$status, $id]);
        $message = "Status produk berhasil diperbarui.";
    } catch (PDOException $e) {
        $error = "Gagal mengubah status keaktifan produk: " . $e->getMessage();
    }
}

// 4. EDIT MODE: Load Data ke Form
$edit_product = null;
if (isset($_GET['edit_id'])) {
    $edit_id = intval($_GET['edit_id']);
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_product = $stmt->fetch();
}

// 5. AMBIL SEMUA PRODUK & KATEGORI
$products = $db->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();

$categories_stmt = $db->query("SELECT name FROM categories ORDER BY name ASC");
$all_categories = $categories_stmt->fetchAll(PDO::FETCH_COLUMN);

// Jika master categories belum terisi dari DB, beri default
if (empty($all_categories)) {
    $all_categories = ['Cake', 'Cheesecake', 'Crepe', 'Kue Basah', 'Kue Kering'];
}
?>

<?php if (!empty($message)): ?>
    <div class="alert-box alert-success">
        <i class="fa-solid fa-circle-check"></i> <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<?php if (!empty($error)): ?>
    <div class="alert-box alert-danger">
        <i class="fa-solid fa-triangle-exclamation"></i> <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<div style="display: grid; grid-template-columns: 1.3fr 1.1fr; gap: 2rem; align-items: start;">
    
    <!-- Bagian Kiri: Tabel Produk & Modal Kategori -->
    <div>
        <!-- Panel Form Tambah Kategori Baru -->
        <div class="panel" style="margin-bottom: 1.5rem; background: #FFFDF9; border-left: 4px solid var(--accent);">
            <div class="panel-header" style="margin-bottom: 0.8rem;">
                <h3 class="panel-title" style="font-size: 1.05rem;"><i class="fa-solid fa-folder-plus" style="color: var(--accent);"></i> Tambah Kategori Kue Baru</h3>
            </div>
            <form action="products.php" method="POST" style="display: flex; gap: 0.8rem; align-items: center;">
                <input type="hidden" name="action" value="add_category">
                <input type="text" name="new_category_name" class="form-control" placeholder="Contoh: Tart Special, Brownies, Donat" required style="flex-grow: 1;">
                <button type="submit" class="btn-admin btn-admin-primary" style="white-space: nowrap;">
                    <i class="fa-solid fa-plus"></i> Tambah Kategori
                </button>
            </form>
        </div>

        <!-- Tabel Produk -->
        <div class="panel">
            <div class="panel-header">
                <h2 class="panel-title"><i class="fa-solid fa-cookie-bite"></i> Daftar Produk Kue</h2>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Gambar</th>
                            <th>Kue</th>
                            <th>Harga</th>
                            <th>Stok</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($products) > 0): ?>
                            <?php foreach ($products as $p): ?>
                                <tr>
                                    <td>
                                        <div style="width: 50px; height: 50px; border-radius: 6px; overflow: hidden; background-color: #F7F5F0; border: 1px solid var(--border-color);">
                                            <img src="../<?php echo htmlspecialchars($p['image_url']); ?>" alt="" style="width: 100%; height: 100%; object-fit: cover;">
                                        </div>
                                    </td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($p['name']); ?></strong>
                                        <div style="font-size: 0.8rem; color: var(--text-muted);"><i class="fa-solid fa-tag"></i> <?php echo htmlspecialchars($p['category']); ?></div>
                                    </td>
                                    <td style="font-weight: 600;">Rp <?php echo number_format($p['price'], 0, ',', '.'); ?></td>
                                    <td>
                                        <span style="font-weight: bold; color: <?php echo $p['stock'] <= 5 ? 'var(--danger)' : 'var(--text-dark)'; ?>;">
                                            <?php echo $p['stock']; ?> pcs
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($p['is_active'] == 1): ?>
                                            <span class="badge badge-completed">Aktif</span>
                                        <?php else: ?>
                                            <span class="badge badge-cancelled">Nonaktif</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="action-buttons">
                                            <a href="products.php?edit_id=<?php echo $p['id']; ?>" class="btn-admin btn-admin-outline" style="padding: 0.3rem 0.6rem; font-size: 0.8rem;" title="Edit Kue">
                                                <i class="fa-solid fa-pen-to-square"></i>
                                            </a>
                                            
                                            <?php if ($p['is_active'] == 1): ?>
                                                <a href="products.php?toggle_active=0&id=<?php echo $p['id']; ?>" class="btn-admin btn-admin-danger" style="padding: 0.3rem 0.6rem; font-size: 0.8rem;" title="Nonaktifkan Kue" onclick="return confirm('Apakah Anda yakin ingin menonaktifkan kue ini?')">
                                                    <i class="fa-solid fa-eye-slash"></i>
                                                </a>
                                            <?php else: ?>
                                                <a href="products.php?toggle_active=1&id=<?php echo $p['id']; ?>" class="btn-admin btn-admin-success" style="padding: 0.3rem 0.6rem; font-size: 0.8rem;" title="Aktifkan Kue">
                                                    <i class="fa-solid fa-eye"></i>
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 3rem;">Belum ada kue di katalog.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Bagian Kanan: Form Tambah/Edit Produk -->
    <div class="panel" style="border-top: 4px solid var(--accent);">
        <div class="panel-header" style="border-bottom: 1px solid var(--border-color); padding-bottom: 0.8rem; margin-bottom: 1.2rem;">
            <h2 class="panel-title">
                <i class="fa-solid <?php echo $edit_product ? 'fa-pen-to-square' : 'fa-circle-plus'; ?>"></i> 
                <?php echo $edit_product ? 'Edit Detail Kue' : 'Tambah Kue Baru'; ?>
            </h2>
            <?php if ($edit_product): ?>
                <a href="products.php" style="color: var(--text-muted); font-size: 0.85rem;"><i class="fa-solid fa-circle-xmark"></i> Batal Edit</a>
            <?php endif; ?>
        </div>

        <form action="products.php<?php echo $edit_product ? '?edit_id='.$edit_product['id'] : ''; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="save_product">
            <?php if ($edit_product): ?>
                <input type="hidden" name="id" value="<?php echo $edit_product['id']; ?>">
            <?php endif; ?>

            <div class="form-group">
                <label for="name">Nama Kue</label>
                <input type="text" name="name" id="name" class="form-control" required placeholder="Contoh: Premium Red Velvet Cake" value="<?php echo $edit_product ? htmlspecialchars($edit_product['name']) : ''; ?>">
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="category_select">Kategori Kue</label>
                    <select name="category_select" id="category_select" class="form-control" onchange="toggleCustomCategory(this.value)">
                        <?php foreach ($all_categories as $cat_option): ?>
                            <option value="<?php echo htmlspecialchars($cat_option); ?>" <?php echo ($edit_product && $edit_product['category'] == $cat_option) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat_option); ?>
                            </option>
                        <?php endforeach; ?>
                        <option value="new_custom">+ Ketik Kategori Baru...</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="price">Harga Jual (Rp)</label>
                    <input type="number" name="price" id="price" class="form-control" required min="1000" step="1000" placeholder="250000" value="<?php echo $edit_product ? intval($edit_product['price']) : ''; ?>">
                </div>
            </div>

            <!-- Input Kategori Kustom jika dipilih "+ Ketik Kategori Baru..." -->
            <div class="form-group" id="custom_category_group" style="display: none;">
                <label for="category_custom" style="color: var(--accent);">Nama Kategori Baru</label>
                <input type="text" name="category_custom" id="category_custom" class="form-control" placeholder="Tuliskan nama kategori kue baru di sini...">
            </div>

            <!-- Stok awal (Hanya tampil saat menambah produk baru) -->
            <?php if (!$edit_product): ?>
                <div class="form-group">
                    <label for="stock">Stok Awal Kue (Pcs)</label>
                    <input type="number" name="stock" id="stock" class="form-control" required min="0" placeholder="10" value="0">
                </div>
            <?php endif; ?>

            <!-- Unggah Foto Kue Baru -->
            <div class="form-group" style="background: #FAF8F5; padding: 1rem; border-radius: 8px; border: 1px dashed var(--accent);">
                <label for="product_image" style="font-weight: 600; display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.4rem;">
                    <i class="fa-solid fa-camera-retro" style="color: var(--accent);"></i> Upload Foto Kue Baru
                </label>
                
                <?php if ($edit_product && !empty($edit_product['image_url'])): ?>
                    <div style="display: flex; align-items: center; gap: 0.8rem; margin-bottom: 0.8rem; background: white; padding: 0.5rem; border-radius: 6px; border: 1px solid var(--border-color);">
                        <img src="../<?php echo htmlspecialchars($edit_product['image_url']); ?>" alt="" style="width: 45px; height: 45px; object-fit: cover; border-radius: 4px;">
                        <span style="font-size: 0.8rem; color: var(--text-muted);">Foto saat ini: <?php echo htmlspecialchars(basename($edit_product['image_url'])); ?></span>
                    </div>
                <?php endif; ?>

                <input type="file" name="product_image" id="product_image" accept="image/*" class="form-control" style="background: white; padding: 0.4rem; font-size: 0.85rem;">
                <small style="display: block; font-size: 0.75rem; color: var(--text-muted); margin-top: 0.4rem;">
                    Format: JPG, JPEG, PNG, WEBP (Max 5MB). Foto yang diunggah akan otomatis menjadi gambar utama produk.
                </small>

                <div style="margin-top: 0.8rem; border-top: 1px dashed #E0D6CE; padding-top: 0.6rem;">
                    <label for="image_url_existing" style="font-size: 0.8rem; color: var(--text-muted);">Atau Pilih dari Preset Gambar Default (opsional):</label>
                    <select name="image_url_existing" id="image_url_existing" class="form-control" style="font-size: 0.85rem; padding: 0.4rem 0.8rem;">
                        <option value="">-- Gunakan Foto Upload Di Atas --</option>
                        <option value="assets/images/chocolate_fudge.jpg" <?php echo ($edit_product && $edit_product['image_url'] == 'assets/images/chocolate_fudge.jpg') ? 'selected' : ''; ?>>Signature Chocolate Fudge Cake</option>
                        <option value="assets/images/strawberry_shortcake.jpg" <?php echo ($edit_product && $edit_product['image_url'] == 'assets/images/strawberry_shortcake.jpg') ? 'selected' : ''; ?>>Strawberry Shortcake</option>
                        <option value="assets/images/red_velvet.jpg" <?php echo ($edit_product && $edit_product['image_url'] == 'assets/images/red_velvet.jpg') ? 'selected' : ''; ?>>Premium Red Velvet Cake</option>
                        <option value="assets/images/matcha_crepes.jpg" <?php echo ($edit_product && $edit_product['image_url'] == 'assets/images/matcha_crepes.jpg') ? 'selected' : ''; ?>>Matcha Mille Crepes</option>
                        <option value="assets/images/classic_tiramisu.jpg" <?php echo ($edit_product && $edit_product['image_url'] == 'assets/images/classic_tiramisu.jpg') ? 'selected' : ''; ?>>Classic Tiramisu Cake</option>
                        <option value="assets/images/newyork_cheesecake.jpg" <?php echo ($edit_product && $edit_product['image_url'] == 'assets/images/newyork_cheesecake.jpg') ? 'selected' : ''; ?>>Classic New York Cheesecake</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="description">Deskripsi & Penjelasan Kue</label>
                <textarea name="description" id="description" class="form-control" rows="5" required placeholder="Tuliskan penjelasan rasa, tekstur, bahan utama, dan ukuran kue..." style="resize: vertical;"><?php echo $edit_product ? htmlspecialchars($edit_product['description']) : ''; ?></textarea>
            </div>

            <button type="submit" class="btn-admin btn-admin-primary" style="width: 100%; justify-content: center; padding: 0.7rem; font-size: 0.95rem;">
                <i class="fa-solid fa-floppy-disk"></i> <?php echo $edit_product ? 'Simpan Perubahan Kue' : 'Tambahkan Kue'; ?>
            </button>
        </form>
    </div>

</div>

<script>
function toggleCustomCategory(val) {
    var group = document.getElementById('custom_category_group');
    var input = document.getElementById('category_custom');
    if (val === 'new_custom') {
        group.style.display = 'block';
        input.required = true;
        input.focus();
    } else {
        group.style.display = 'none';
        input.required = false;
    }
}
</script>

<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
