<?php
// File: admin/crud_produk.php

// 1. Error Reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 2. Session Check
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require '../includes/db_connect.php';
require '../includes/functions.php';
require '../includes/upload_helper.php';

// Cek Login
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit; }

$view = $_GET['view'] ?? 'list';
$error = '';
$success = '';

// --- LOGIC HANDLING (CRUD) ---

// 1. DELETE
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    try {
        $stmt = $pdo->prepare("SELECT gambar_utama_url, brosur_url FROM produk WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        $row = $stmt->fetch();
        if ($row) {
            deleteFile($row['gambar_utama_url']);
            deleteFile($row['brosur_url']);
        }
        $pdo->prepare("DELETE FROM produk WHERE id = ?")->execute([$_GET['id']]);
        echo "<script>window.location='crud_produk.php?msg=deleted';</script>";
        exit;
    } catch (PDOException $e) {
        $error = "Gagal menghapus: " . $e->getMessage();
    }
}

// 2. SAVE (INSERT / UPDATE)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Cek post_max_size overflow
    if (empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
        $error = "File terlalu besar! Cek setting upload_max_filesize di server.";
    } else {
        try {
            $id = $_POST['id'] ?? null;
            $nama_mobil = $_POST['nama_mobil'] ?? '';
            $kategori = $_POST['kategori'] ?? 'MPV';
            $deskripsi = $_POST['deskripsi'] ?? '';
            $video_id = $_POST['video_youtube_id'] ?? '';
            $is_featured = isset($_POST['is_featured']) ? 1 : 0;

            if (empty($nama_mobil)) {
                throw new Exception("Nama Mobil wajib diisi!");
            }

            // Varian
            $variants = [];
            $harga_otr_min = 0; 
            if (isset($_POST['varian_nama']) && is_array($_POST['varian_nama'])) {
                foreach ($_POST['varian_nama'] as $index => $v_nama) {
                    $raw_harga = $_POST['varian_harga'][$index] ?? '0';
                    $v_harga = str_replace(['.', ','], '', $raw_harga); 
                    if (!empty($v_nama)) {
                        $variants[] = ['nama' => $v_nama, 'harga' => (float)$v_harga];
                    }
                }
            }
            if (!empty($variants)) $harga_otr_min = min(array_column($variants, 'harga'));
            else $harga_otr_min = (float)str_replace(['.', ','], '', $_POST['harga_otr_manual'] ?? '0');
            if ($harga_otr_min == 0 && isset($_POST['harga_otr'])) $harga_otr_min = (float)str_replace(['.', ','], '', $_POST['harga_otr']);
            $varian_json = json_encode($variants);

            // 1. Image
            $gambar_url = $_POST['existing_image'] ?? ''; 
            if (!empty($_FILES['gambar_utama']['name'])) {
                try {
                    $up = uploadImage($_FILES['gambar_utama'], "../uploads/mobil/", "prod");
                    if ($up) {
                        deleteFile($gambar_url);
                        $gambar_url = $up;
                    }
                } catch (Exception $e) { throw new Exception("Gagal Upload Gambar: " . $e->getMessage()); }
            } elseif (!empty($_POST['gambar_url_external'])) {
                $gambar_url = $_POST['gambar_url_external'];
            }

            // 2. Brosur
            $brosur_url = $_POST['existing_brosur'] ?? '';
            if (!empty($_FILES['brosur_file']['name'])) {
                try {
                    $upPdf = uploadPDF($_FILES['brosur_file'], "../uploads/brosur/");
                    if ($upPdf) {
                        deleteFile($brosur_url);
                        $brosur_url = $upPdf;
                    }
                } catch (Exception $e) { throw new Exception("Gagal Upload Brosur: " . $e->getMessage()); }
            }

            if ($id) {
                $pdo->prepare("UPDATE produk SET nama_mobil=?, harga_otr=?, kategori=?, deskripsi=?, gambar_utama_url=?, video_youtube_id=?, varian=?, is_featured=?, brosur_url=? WHERE id=?")
                    ->execute([$nama_mobil, $harga_otr_min, $kategori, $deskripsi, $gambar_url, $video_id, $varian_json, $is_featured, $brosur_url, $id]);
            } else {
                $pdo->prepare("INSERT INTO produk (nama_mobil, harga_otr, kategori, deskripsi, gambar_utama_url, video_youtube_id, varian, is_featured, brosur_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
                    ->execute([$nama_mobil, $harga_otr_min, $kategori, $deskripsi, $gambar_url, $video_id, $varian_json, $is_featured, $brosur_url]);
            }
            echo "<script>window.location='crud_produk.php?msg=saved';</script>"; exit;

        } catch (Exception $e) { $error = $e->getMessage(); }
    }
}

$products = getAllProducts($pdo);
$editData = null; $editVariants = [];
if ($view == 'edit' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("SELECT * FROM produk WHERE id = ?");
    $stmt->execute([$_GET['id']]);
    $editData = $stmt->fetch();
    if (!empty($editData['varian'])) $editVariants = json_decode($editData['varian'], true);
}

$page_title = 'Kelola Produk';
require 'includes/header.php';
?>

<main class="flex-1 overflow-y-auto p-4 md:p-10 bg-gray-50 w-full">
    <?php if($error): ?><div class="bg-red-100 text-red-700 p-4 rounded mb-4 border border-red-200 text-sm"><strong>Error:</strong> <?= $error ?></div><?php endif; ?>
    <?php if(isset($_GET['msg']) && $_GET['msg'] == 'saved'): ?><div class="bg-green-100 text-green-700 p-4 rounded mb-4 flex items-center gap-2 text-sm"><i class="fa-solid fa-check-circle"></i> Data berhasil disimpan!</div><?php endif; ?>
    <?php if(isset($_GET['msg']) && $_GET['msg'] == 'deleted'): ?><div class="bg-red-100 text-red-700 p-4 rounded mb-4 flex items-center gap-2 text-sm"><i class="fa-solid fa-trash-can"></i> Data berhasil dihapus!</div><?php endif; ?>

    <?php if ($view == 'list'): ?>
        <!-- VIEW: LIST (Mobile Optimized) -->
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
            <div>
                <h1 class="text-2xl font-bold text-gray-800">Daftar Produk</h1>
                <p class="text-xs text-gray-500">Geser tabel ke kiri untuk melihat opsi lainnya.</p>
            </div>
            <a href="crud_produk.php?view=add" class="w-full sm:w-auto text-center bg-green-600 text-white px-4 py-2 rounded-lg font-bold hover:bg-green-700 shadow flex items-center justify-center gap-2 text-sm">
                <i class="fa-solid fa-plus"></i> Tambah Mobil
            </a>
        </div>

        <div class="bg-white rounded-lg shadow overflow-hidden border border-gray-200">
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse whitespace-nowrap">
                    <thead class="bg-gray-100 text-gray-600 text-xs uppercase font-semibold border-b">
                        <tr>
                            <th class="py-3 px-4">Foto</th>
                            <th class="py-3 px-4">Model</th>
                            <th class="py-3 px-4">Harga Mulai</th>
                            <th class="py-3 px-4 text-center">Status</th>
                            <th class="py-3 px-4 text-center">Brosur</th> <!-- KOLOM BARU -->
                            <th class="py-3 px-4 text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody class="text-gray-700 text-sm divide-y divide-gray-100">
                        <?php if(empty($products)): ?>
                            <tr><td colspan="6" class="text-center p-6 text-gray-400 text-sm">Belum ada data mobil.</td></tr>
                        <?php else: ?>
                            <?php foreach($products as $p): 
                                $imgSrc = (!empty($p['gambar_utama_url']) && strpos($p['gambar_utama_url'], 'http') === 0) ? $p['gambar_utama_url'] : '../'.($p['gambar_utama_url'] ?: 'assets/images/no-image.jpg');
                                $is_featured = $p['is_featured'] ?? 0;
                            ?>
                            <tr class="hover:bg-gray-50 transition">
                                <td class="py-3 px-4">
                                    <img src="<?= $imgSrc ?>" class="h-10 w-16 object-cover rounded border bg-gray-50" onerror="this.src='https://via.placeholder.com/100x60?text=No+Img'">
                                </td>
                                <td class="py-3 px-4">
                                    <div class="font-bold text-gray-900"><?= htmlspecialchars($p['nama_mobil']) ?></div>
                                    <span class="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded"><?= htmlspecialchars($p['kategori']) ?></span>
                                </td>
                                <td class="py-3 px-4 text-red-600 font-bold font-mono text-xs"><?= formatRupiah($p['harga_otr']) ?></td>
                                
                                <td class="py-3 px-4 text-center">
                                    <?php if($is_featured == 1): ?>
                                        <span class="inline-flex items-center gap-1 bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded text-[10px] font-bold border border-yellow-200 uppercase">
                                            <i class="fa-solid fa-star text-[10px]"></i> Fav
                                        </span>
                                    <?php else: ?>
                                        <span class="text-gray-300 text-xs">-</span>
                                    <?php endif; ?>
                                </td>

                                <!-- KOLOM STATUS BROSUR -->
                                <td class="py-3 px-4 text-center">
                                    <?php if(!empty($p['brosur_url'])): ?>
                                        <span class="text-green-600 text-xs font-bold bg-green-50 px-2 py-1 rounded-full"><i class="fa-solid fa-check"></i> Ada</span>
                                    <?php else: ?>
                                        <span class="text-gray-400 text-xs">-</span>
                                    <?php endif; ?>
                                </td>

                                <td class="py-3 px-4 text-center">
                                    <div class="flex justify-center items-center gap-2">
                                        <a href="crud_produk.php?view=edit&id=<?= $p['id'] ?>" class="w-8 h-8 flex items-center justify-center bg-blue-50 text-blue-600 rounded hover:bg-blue-600 hover:text-white transition" title="Edit">
                                            <i class="fa-solid fa-pen text-xs"></i>
                                        </a>
                                        <a href="crud_produk.php?action=delete&id=<?= $p['id'] ?>" onclick="return confirm('Yakin hapus mobil ini?')" class="w-8 h-8 flex items-center justify-center bg-red-50 text-red-600 rounded hover:bg-red-600 hover:text-white transition" title="Hapus">
                                            <i class="fa-solid fa-trash text-xs"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    <?php elseif ($view == 'add' || $view == 'edit'): ?>
        <!-- VIEW: FORM (Mobile Optimized) -->
        <div class="max-w-4xl mx-auto pb-20">
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-xl md:text-2xl font-bold text-gray-800"><?= $view == 'add' ? 'Tambah Mobil' : 'Edit Mobil' ?></h1>
                <a href="crud_produk.php" class="text-gray-500 hover:text-gray-800 flex items-center gap-2 font-bold text-sm px-3 py-2 rounded hover:bg-gray-100 transition">
                    <i class="fa-solid fa-arrow-left"></i> <span class="hidden sm:inline">Kembali</span>
                </a>
            </div>

            <form method="POST" enctype="multipart/form-data" class="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
                <input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">
                <input type="hidden" name="existing_image" value="<?= $editData['gambar_utama_url'] ?? '' ?>">
                <input type="hidden" name="existing_brosur" value="<?= $editData['brosur_url'] ?? '' ?>">

                <!-- Info Umum -->
                <div class="mb-6 border-b pb-4">
                    <h3 class="text-base font-bold text-gray-800 mb-4 flex items-center gap-2"><i class="fa-solid fa-circle-info text-blue-600"></i> Info Dasar</h3>
                    
                    <div class="mb-4 bg-yellow-50 border border-yellow-100 p-3 rounded-lg flex items-center gap-3">
                        <input type="checkbox" name="is_featured" id="is_featured" value="1" class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500" <?= (isset($editData['is_featured']) && $editData['is_featured'] == 1) ? 'checked' : '' ?>>
                        <label for="is_featured" class="text-sm font-bold text-gray-700 cursor-pointer">Jadikan Produk Unggulan</label>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Nama Model <span class="text-red-500">*</span></label>
                            <input type="text" name="nama_mobil" value="<?= htmlspecialchars($editData['nama_mobil'] ?? '') ?>" class="w-full p-2.5 border rounded text-sm focus:ring-2 focus:ring-blue-500 outline-none" required placeholder="Contoh: All New Raize">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Kategori <span class="text-red-500">*</span></label>
                            <select name="kategori" class="w-full p-2.5 border rounded text-sm bg-white focus:ring-2 focus:ring-blue-500 outline-none">
                                <?php 
                                    $cat = $editData['kategori'] ?? ''; 
                                    $cats = ['MPV', 'SUV', 'Sedan', 'Hatchback', 'Commercial', 'Hybrid/EV'];
                                    foreach($cats as $c) {
                                        $sel = ($cat == $c) ? 'selected' : '';
                                        echo "<option value='$c' $sel>$c</option>";
                                    }
                                ?>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Varian -->
                <div class="mb-6 border-b pb-4">
                    <div class="flex justify-between items-center mb-2">
                        <h3 class="text-base font-bold text-gray-800 flex items-center gap-2"><i class="fa-solid fa-tags text-green-600"></i> Varian</h3>
                        <button type="button" onclick="addVariantRow()" class="bg-blue-50 text-blue-600 px-3 py-1 rounded text-xs font-bold border border-blue-200 hover:bg-blue-100 transition"><i class="fa-solid fa-plus"></i> Tambah</button>
                    </div>
                    
                    <div id="variant-container" class="space-y-2">
                        <?php 
                        $vars = !empty($editVariants) ? $editVariants : [['nama'=>'','harga'=>'']];
                        if (empty($vars)) $vars = [['nama'=>'','harga'=>'']];
                        foreach($vars as $v): 
                            $vName = $v['nama'] ?? '';
                            $vPrice = (isset($v['harga']) && $v['harga'] !== '') ? number_format((float)$v['harga'],0,',','.') : '';
                        ?>
                        <div class="variant-row flex gap-2 items-center bg-gray-50 p-2 rounded border border-gray-200">
                            <input type="text" name="varian_nama[]" value="<?= htmlspecialchars($vName) ?>" class="flex-1 p-2 border rounded text-xs focus:outline-none focus:border-blue-500" placeholder="Tipe (Cth: 1.0 G)" required>
                            <input type="text" name="varian_harga[]" value="<?= $vPrice ?>" onkeyup="formatRupiahInput(this)" class="w-24 sm:w-32 p-2 border rounded text-xs text-right font-mono focus:outline-none focus:border-blue-500" placeholder="Harga" required>
                            <button type="button" onclick="removeVariantRow(this)" class="text-red-500 hover:text-red-700 px-2"><i class="fa-solid fa-trash"></i></button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <p class="text-xs text-gray-500 mt-3 flex items-center gap-1">
                        <i class="fa-solid fa-circle-info"></i> Harga terendah dari daftar ini otomatis jadi harga "Mulai Dari".
                    </p>
                    <input type="hidden" name="harga_otr_manual" value="0">
                </div>

                <!-- Media -->
                <div class="mb-6">
                    <h3 class="text-base font-bold text-gray-800 mb-4 flex items-center gap-2"><i class="fa-solid fa-images text-purple-600"></i> Media</h3>
                    
                    <div class="grid grid-cols-1 gap-4">
                        <!-- Gambar -->
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Gambar Utama</label>
                            <div class="p-3 bg-gray-50 rounded border border-dashed border-gray-300">
                                <input type="file" name="gambar_utama" class="block w-full text-xs text-gray-500 file:mr-2 file:py-1 file:px-3 file:rounded file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 mb-2">
                                <input type="text" name="gambar_url_external" value="<?= htmlspecialchars($editData['gambar_utama_url'] ?? '') ?>" class="w-full p-2 border rounded text-xs" placeholder="Atau paste URL gambar...">
                                <?php if(!empty($editData['gambar_utama_url'])): ?>
                                    <div class="mt-2"><img src="<?= strpos($editData['gambar_utama_url'], 'http') === 0 ? $editData['gambar_utama_url'] : '../'.$editData['gambar_utama_url'] ?>" class="h-16 object-contain border bg-white rounded"></div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Video & PDF -->
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Youtube ID</label>
                                <input type="text" name="video_youtube_id" value="<?= htmlspecialchars($editData['video_youtube_id'] ?? '') ?>" class="w-full p-2 border rounded text-sm" placeholder="Contoh: dQw4w9WgXcQ">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Brosur PDF</label>
                                <input type="file" name="brosur_file" accept="application/pdf" class="block w-full text-xs border p-1.5 rounded bg-white">
                                <?php if(!empty($editData['brosur_url'])): ?><p class="text-xs text-green-600 mt-1 font-bold"><i class="fa-solid fa-check"></i> File Tersedia</p><?php endif; ?>
                            </div>
                        </div>

                        <!-- Deskripsi -->
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Deskripsi</label>
                            <textarea name="deskripsi" rows="4" class="w-full p-2 border rounded text-sm" placeholder="Tulis deskripsi singkat..."><?= htmlspecialchars($editData['deskripsi'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>

                <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-4 border-t">
                    <a href="crud_produk.php" class="w-full sm:w-auto px-6 py-2.5 rounded-lg text-gray-600 hover:bg-gray-100 font-bold text-center border border-gray-300 text-sm transition">Batal</a>
                    <button type="submit" class="w-full sm:w-auto px-8 py-2.5 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 shadow-md transition text-sm flex items-center justify-center gap-2">
                        <i class="fa-solid fa-save"></i> Simpan Data
                    </button>
                </div>
            </form>
        </div>

        <script>
            function addVariantRow() {
                const container = document.getElementById('variant-container');
                const div = document.createElement('div');
                div.className = 'variant-row flex gap-2 items-center bg-gray-50 p-2 rounded border border-gray-200 animate-fade-in-up';
                div.innerHTML = `
                    <input type="text" name="varian_nama[]" class="flex-1 p-2 border rounded text-xs focus:outline-none focus:border-blue-500" placeholder="Tipe" required>
                    <input type="text" name="varian_harga[]" onkeyup="formatRupiahInput(this)" class="w-24 sm:w-32 p-2 border rounded text-xs text-right font-mono focus:outline-none focus:border-blue-500" placeholder="Harga" required>
                    <button type="button" onclick="removeVariantRow(this)" class="text-red-500 hover:text-red-700 px-2"><i class="fa-solid fa-trash"></i></button>
                `;
                container.appendChild(div);
            }

            function removeVariantRow(btn) {
                const container = document.getElementById('variant-container');
                if(container.children.length > 1) {
                    btn.closest('.variant-row').remove();
                } else {
                    alert('Minimal harus ada 1 tipe mobil!');
                }
            }
        </script>
    <?php endif; ?>
</main>
<?php require 'includes/footer.php'; ?>