<?php
// File: admin/crud_promo.php
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once '../includes/db_connect.php';
require_once '../includes/cache.php';
require_once '../includes/functions.php';
require_once '../includes/security.php';
secureSessionStart();
require_once '../includes/upload_helper.php';

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

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

// --- LOGIC DELETE ---
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    try {
        $stmt = $pdo->prepare("SELECT gambar_url, video_id FROM promo WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        $row = $stmt->fetch();
        if ($row) {
            if (!empty($row['gambar_url'])) deleteFile($row['gambar_url']);
            if (!empty($row['video_id']) && strpos($row['video_id'], 'uploads/') !== false) deleteFile($row['video_id']);
        }
        $pdo->prepare("DELETE FROM promo WHERE id = ?")->execute([$_GET['id']]);
        
        // FIX: Bersihkan cache setelah hapus supaya hilang dari tampilan!
        cacheFlush(); 
        
        header("Location: crud_promo.php?msg=deleted"); exit;
    } catch (Exception $e) { $error = $e->getMessage(); }
}

// --- LOGIC SAVE ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    verifyCsrf();
    cacheFlush(); // Hapus cache setelah perubahan data
    try {
        $id = $_POST['id'] ?? null;
        $judul = $_POST['judul'];
        $desc = $_POST['deskripsi']; 
        $type = $_POST['tipe'];
        $expired = $_POST['expired'];
        $is_feat = isset($_POST['is_featured']) ? 1 : 0;
        $meta_desc = $_POST['meta_description'];

        // Upload Image
        $img = $_POST['existing_image'] ?? '';
        if (!empty($_FILES['gambar_upload']['name'])) {
            $up = uploadImage($_FILES['gambar_upload'], "../uploads/promo/", "prm");
            if ($up) { deleteFile($img); $img = $up; }
        } elseif (!empty($_POST['gambar_url_external'])) { $img = $_POST['gambar_url_external']; }

        // Upload Video
        $vid = $_POST['existing_video'] ?? '';
        if ($type == 'video') {
            if (!empty($_FILES['video_upload']['name'])) {
                $upVid = uploadVideo($_FILES['video_upload'], "../uploads/promo/");
                if ($upVid) { deleteFile($vid); $vid = $upVid; }
            } elseif (!empty($_POST['video_url_external'])) { $vid = $_POST['video_url_external']; }
        } else {
            if(!empty($vid)) deleteFile($vid);
            $vid = '';
        }

        if ($id) {
            $pdo->prepare("UPDATE promo SET judul=?, deskripsi=?, tipe=?, gambar_url=?, video_id=?, tanggal_berakhir=?, is_featured=?, meta_description=? WHERE id=?")
                ->execute([$judul, $desc, $type, $img, $vid, $expired, $is_feat, $meta_desc, $id]);
        } else {
            $pdo->prepare("INSERT INTO promo (judul, deskripsi, tipe, gambar_url, video_id, tanggal_berakhir, is_featured, meta_description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
                ->execute([$judul, $desc, $type, $img, $vid, $expired, $is_feat, $meta_desc]);
        }
        header("Location: crud_promo.php?msg=saved"); exit;
    } catch (Exception $e) { $error = $e->getMessage(); }
}

$promos = getAllPromos($pdo);
$edit = null;
if ($view == 'edit' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("SELECT * FROM promo WHERE id = ?");
    $stmt->execute([$_GET['id']]);
    $edit = $stmt->fetch();
}

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

<!-- SCRIPT TINYMCE (VERSI GRATIS/OPEN SOURCE VIA CDNJS) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.2/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: '#editor_content', // ID target textarea
    height: 300,
    menubar: false,
    plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
    toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table | align lineheight | numlist bullist indent outdent | emoticons charmap | removeformat',
    branding: false,
    promotion: false
  });
</script>

<main class="flex-1 overflow-y-auto p-6 md:p-10 bg-gray-50 w-full">
    <?php if($error): ?><div class="bg-red-100 text-red-700 p-4 rounded mb-4"><i class="fa-solid fa-triangle-exclamation"></i> <?= $error ?></div><?php endif; ?>
    
    <!-- FIX: Pesan Notifikasi Lebih Rapi -->
    <?php if(isset($_GET['msg'])): ?>
        <?php 
            $msgText = 'Berhasil!';
            if($_GET['msg'] == 'saved') $msgText = 'Promo berhasil disimpan!';
            if($_GET['msg'] == 'deleted') $msgText = 'Promo berhasil dihapus!';
        ?>
        <div class="bg-green-100 text-green-700 p-4 rounded mb-6 font-bold flex items-center gap-2 shadow-sm">
            <i class="fa-solid fa-check-circle"></i> <?= $msgText ?>
        </div>
    <?php endif; ?>

    <?php if ($view == 'list'): ?>
        <div class="flex flex-col sm:flex-row justify-between mb-6 gap-4">
            <h1 class="text-3xl font-bold text-gray-800">Promo Spesial</h1>
            <div class="flex gap-2">
                <a href="ai_generator.php?mode=promo" class="bg-indigo-600 text-white px-4 py-2 rounded-lg font-bold shadow-sm flex items-center gap-2 hover:bg-indigo-700 transition">
                    <i class="fa-solid fa-wand-magic-sparkles"></i> Generate AI
                </a>
                <a href="?view=add" class="bg-blue-600 text-white px-4 py-2 rounded-lg font-bold shadow-sm flex items-center gap-2 hover:bg-blue-700 transition">
                    <i class="fa-solid fa-plus"></i> Tambah Manual
                </a>
            </div>
        </div>

        <div class="bg-white shadow rounded-xl overflow-x-auto border border-gray-200">
            <table class="w-full text-left border-collapse">
                <thead class="bg-gray-800 text-white text-sm uppercase">
                    <tr><th class="p-4">Media</th><th class="p-4">Judul</th><th class="p-4">Tipe</th><th class="p-4">Expired</th><th class="p-4 text-center">Aksi</th></tr>
                </thead>
                <tbody class="text-sm text-gray-700">
                    <?php if(empty($promos)): ?>
                        <tr><td colspan="5" class="p-6 text-center text-gray-400 italic">Belum ada promo aktif.</td></tr>
                    <?php else: ?>
                        <?php foreach($promos as $p): ?>
                        <tr class="border-b hover:bg-gray-50 transition">
                            <td class="p-4">
                                <?php if($p['tipe']=='video'): ?>
                                    <span class="text-xs bg-red-100 text-red-600 font-bold px-3 py-1.5 rounded-lg border border-red-200 flex w-fit items-center gap-1"><i class="fa-solid fa-play"></i> Video</span>
                                <?php else: ?>
                                    <img src="<?= (strpos($p['image'],'http')===0?$p['image']:'../'.$p['image']) ?>" class="h-12 w-20 object-cover rounded border shadow-sm" onerror="this.onerror=null; this.src='../assets/images/no-image.jpg';">
                                <?php endif; ?>
                            </td>
                            <td class="p-4 font-bold text-gray-800">
                                <?= htmlspecialchars($p['title']) ?>
                                <?php if(isset($p['is_featured']) && $p['is_featured'] == 1): ?>
                                    <span class="block mt-1 text-[10px] bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded-full w-fit uppercase font-bold">Featured</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 capitalize font-medium"><?= $p['tipe'] ?></td>
                            <td class="p-4 text-xs font-bold <?= (strtotime($p['expired']) < time()) ? 'text-gray-400' : 'text-red-600' ?>">
                                <i class="fa-regular fa-clock"></i> <?= date('d M Y', strtotime($p['expired'])) ?>
                            </td>
                            <td class="p-4 text-center">
                                <div class="flex justify-center gap-2">
                                    <a href="?view=edit&id=<?= $p['id'] ?>" class="bg-blue-50 text-blue-600 w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-600 hover:text-white transition border border-blue-100"><i class="fa-solid fa-pen text-xs"></i></a>
                                    <a href="?action=delete&id=<?= $p['id'] ?>" onclick="return confirm('Yakin hapus promo ini?')" class="bg-red-50 text-red-600 w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-600 hover:text-white transition border border-red-100"><i class="fa-solid fa-trash text-xs"></i></a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

    <?php else: ?>
        <form method="POST" enctype="multipart/form-data" class="bg-white p-8 rounded-xl shadow-sm border border-gray-100 max-w-4xl mx-auto">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-black text-gray-800 uppercase"><?= isset($edit['id']) ? 'Edit' : 'Tambah' ?> Promo</h2>
                <a href="crud_promo.php" class="text-sm font-bold text-gray-500 hover:text-gray-800"><i class="fa-solid fa-arrow-left"></i> Kembali</a>
            </div>
            
            <?= csrfInput() ?>
            <input type="hidden" name="id" value="<?= $edit['id']??'' ?>">
            <input type="hidden" name="existing_image" value="<?= $edit['gambar_url']??'' ?>">
            <input type="hidden" name="existing_video" value="<?= $edit['video_id']??'' ?>">

            <div class="mb-5">
                <label class="block text-sm font-bold mb-2 text-gray-700 uppercase tracking-widest">Judul Promo</label>
                <input type="text" name="judul" value="<?= htmlspecialchars($edit['judul']??'') ?>" class="w-full border p-3 bg-gray-50 rounded-lg outline-none focus:ring-2 focus:ring-blue-500" required>
            </div>

            <!-- META DESCRIPTION (SEO) -->
            <div class="mb-5">
                <label class="block text-sm font-bold mb-2 text-blue-600 uppercase tracking-widest">Meta Description (SEO)</label>
                <textarea name="meta_description" rows="2" class="w-full border p-3 bg-gray-50 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500" placeholder="Ringkasan singkat untuk Google Search..."><?= htmlspecialchars($edit['meta_description']??'') ?></textarea>
            </div>

            <!-- TINYMCE EDITOR -->
            <div class="mb-5">
                <label class="block text-sm font-bold mb-2 text-gray-700 uppercase tracking-widest">Deskripsi Lengkap</label>
                <textarea id="editor_content" name="deskripsi"><?= htmlspecialchars($edit['deskripsi']??'') ?></textarea>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <label class="block text-sm font-bold mb-2 text-gray-700 uppercase tracking-widest">Tipe Media</label>
                    <select name="tipe" class="w-full border p-3 bg-gray-50 rounded-lg outline-none focus:ring-2 focus:ring-blue-500" onchange="toggleMedia(this.value)">
                        <option value="image" <?= (($edit['tipe']??'')=='image')?'selected':'' ?>>Gambar (Banner)</option>
                        <option value="video" <?= (($edit['tipe']??'')=='video')?'selected':'' ?>>Video Animasi</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-bold mb-2 text-gray-700 uppercase tracking-widest">Berlaku Sampai</label>
                    <input type="date" name="expired" value="<?= $edit['tanggal_berakhir'] ?? date('Y-m-d', strtotime('+1 month')) ?>" class="w-full border p-3 bg-gray-50 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>

            <div class="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg flex items-center gap-3">
                <input type="checkbox" name="is_featured" value="1" class="w-5 h-5 text-blue-600 rounded cursor-pointer" <?= ($edit['is_featured']??0)?'checked':'' ?>> 
                <label class="font-bold text-gray-700 cursor-pointer text-sm">Tampilkan Promo Ini di Halaman Home Paling Depan</label>
            </div>

            <!-- TAB GAMBAR -->
            <div id="field-gambar" class="<?= (($edit['tipe']??'')=='video')?'hidden':'' ?> mb-8 p-6 border border-dashed border-gray-300 rounded-xl bg-gray-50">
                <label class="block text-sm font-bold mb-3 text-gray-700 uppercase tracking-widest"><i class="fa-solid fa-image"></i> Gambar Banner Promo</label>
                <input type="file" name="gambar_upload" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-gray-200 file:text-gray-700 hover:file:bg-gray-300 cursor-pointer mb-3 bg-white border p-1 rounded-full">
                <input type="text" name="gambar_url_external" value="<?= $edit['gambar_url']??'' ?>" class="w-full border p-3 rounded-lg text-sm bg-white outline-none focus:ring-2 focus:ring-blue-500" placeholder="Atau paste URL Gambar Eksternal...">
                <?php if(!empty($edit['gambar_url']) && ($edit['tipe']??'image') == 'image'): ?>
                    <div class="mt-4">
                        <p class="text-xs text-gray-500 mb-1 font-bold">Preview:</p>
                        <img src="<?= strpos($edit['gambar_url'], 'http') === 0 ? $edit['gambar_url'] : '../'.$edit['gambar_url'] ?>" class="h-32 object-cover rounded-lg border shadow-sm">
                    </div>
                <?php endif; ?>
            </div>

            <!-- TAB VIDEO -->
            <div id="field-video" class="<?= (($edit['tipe']??'')=='video')?'':'hidden' ?> mb-8 p-6 border border-dashed border-blue-300 rounded-xl bg-blue-50">
                <label class="block text-sm font-bold mb-3 text-blue-800 uppercase tracking-widest"><i class="fa-solid fa-video"></i> Sumber Video Promo</label>
                <div class="mb-4">
                    <label class="text-xs uppercase font-bold text-gray-500 mb-2 block">1. Upload Video Lokal (MP4)</label>
                    <input type="file" name="video_upload" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-100 file:text-blue-700 hover:file:bg-blue-200 cursor-pointer bg-white border p-1 rounded-full" accept="video/mp4,video/webm">
                    <?php if(!empty($edit['video_id']) && strpos($edit['video_id'], 'uploads/') !== false): ?>
                        <p class="text-xs text-green-600 mt-2 font-bold"><i class="fa-solid fa-check"></i> Video saat ini: <?= basename($edit['video_id']) ?></p>
                    <?php endif; ?>
                </div>
                <div>
                    <label class="text-xs uppercase font-bold text-gray-500 mb-2 block">2. Atau Gunakan ID Youtube</label>
                    <input type="text" name="video_url_external" value="<?= (strpos($edit['video_id']??'', 'uploads/') === false) ? ($edit['video_id']??'') : '' ?>" class="w-full border p-3 rounded-lg text-sm bg-white outline-none focus:ring-2 focus:ring-blue-500" placeholder="Contoh: dQw4w9WgXcQ">
                </div>
            </div>

            <div class="flex justify-end pt-4 border-t border-gray-100">
                <button type="submit" class="bg-blue-600 text-white px-10 py-3 rounded-lg font-bold hover:bg-blue-700 shadow-lg transition transform hover:-translate-y-0.5 flex items-center gap-2">
                    <i class="fa-solid fa-save"></i> Simpan Promo
                </button>
            </div>
        </form>

        <script>
            function toggleMedia(type) {
                document.getElementById('field-gambar').classList.toggle('hidden', type === 'video');
                document.getElementById('field-video').classList.toggle('hidden', type === 'image');
            }
        </script>
    <?php endif; ?>
</main>
<?php require 'includes/footer.php'; ?>