<?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 = '';

// 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) {
            deleteFile($row['gambar_url']);
            if (strpos($row['video_id'], 'uploads/') !== false) deleteFile($row['video_id']);
        }
        $pdo->prepare("DELETE FROM promo WHERE id = ?")->execute([$_GET['id']]);
        header("Location: crud_promo.php?msg=deleted"); exit;
    } catch (Exception $e) { $error = $e->getMessage(); }
}

// 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 {
            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"><?= $error ?></div><?php endif; ?>
    <?php if(isset($_GET['msg'])): ?><div class="bg-green-100 text-green-700 p-4 rounded mb-4">Berhasil!</div><?php endif; ?>

    <?php if ($view == 'list'): ?>
        <div class="flex justify-between mb-4">
            <h1 class="text-2xl font-bold">Promo</h1>
            <a href="?view=add" class="bg-blue-600 text-white px-4 py-2 rounded">Tambah Promo</a>
        </div>
        <div class="bg-white shadow rounded overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-gray-800 text-white"><tr><th class="p-3">Media</th><th class="p-3">Judul</th><th class="p-3">Tipe</th><th class="p-3">Expired</th><th class="p-3">Aksi</th></tr></thead>
                <tbody>
                    <?php foreach($promos as $p): ?>
                    <tr class="border-b">
                        <td class="p-3">
                            <?php if($p['tipe']=='video'): ?><span class="text-xs bg-red-100 text-red-600 px-2 py-1 rounded">Video</span>
                            <?php else: ?><img src="<?= (strpos($p['image'],'http')===0?$p['image']:'../'.$p['image']) ?>" class="h-10 w-16 object-cover rounded"><?php endif; ?>
                        </td>
                        <td class="p-3 font-bold"><?= htmlspecialchars($p['title']) ?></td>
                        <td class="p-3 capitalize"><?= $p['tipe'] ?></td>
                        <td class="p-3 text-sm text-red-500"><?= $p['expired'] ?></td>
                        <td class="p-3">
                            <a href="?view=edit&id=<?= $p['id'] ?>" class="text-blue-600 mr-2"><i class="fa-solid fa-pen"></i></a>
                            <a href="?action=delete&id=<?= $p['id'] ?>" onclick="return confirm('Hapus?')" class="text-red-600"><i class="fa-solid fa-trash"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

    <?php else: ?>
        <form method="POST" enctype="multipart/form-data" class="bg-white p-6 rounded shadow max-w-4xl mx-auto">
        <?= 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-4">
                <label class="block font-bold mb-1">Judul Promo</label>
                <input type="text" name="judul" value="<?= htmlspecialchars($edit['judul']??'') ?>" class="w-full border p-2 rounded" required>
            </div>

            <!-- META DESCRIPTION (SEO) -->
            <div class="mb-4">
                <label class="block font-bold mb-1 text-sm text-blue-600">Meta Description (SEO)</label>
                <textarea name="meta_description" rows="2" class="w-full border p-2 rounded text-sm text-gray-600" placeholder="Ringkasan singkat..."><?= htmlspecialchars($edit['meta_description']??'') ?></textarea>
            </div>

            <!-- TINYMCE EDITOR -->
            <div class="mb-4">
                <label class="block font-bold mb-1">Deskripsi Promo</label>
                <textarea id="editor_content" name="deskripsi"><?= htmlspecialchars($edit['deskripsi']??'') ?></textarea>
            </div>

            <div class="grid grid-cols-2 gap-4 mb-4">
                <div>
                    <label class="block font-bold mb-1">Tipe</label>
                    <select name="tipe" class="w-full border p-2 rounded" onchange="toggleMedia(this.value)">
                        <option value="image" <?= (($edit['tipe']??'')=='image')?'selected':'' ?>>Gambar</option>
                        <option value="video" <?= (($edit['tipe']??'')=='video')?'selected':'' ?>>Video</option>
                    </select>
                </div>
                <div>
                    <label class="block font-bold mb-1">Expired</label>
                    <input type="date" name="expired" value="<?= $edit['tanggal_berakhir'] ?? date('Y-m-d', strtotime('+1 month')) ?>" class="w-full border p-2 rounded">
                </div>
            </div>

            <div class="mb-4 bg-yellow-50 p-2 rounded"><input type="checkbox" name="is_featured" value="1" <?= ($edit['is_featured']??0)?'checked':'' ?>> <label>Tampilkan di Home (Utama)</label></div>

            <div id="field-gambar" class="<?= (($edit['tipe']??'')=='video')?'hidden':'' ?> mb-4 p-4 border border-dashed rounded bg-gray-50">
                <label class="block font-bold mb-1">Gambar Banner</label>
                <input type="file" name="gambar_upload" class="w-full border p-1 mb-2 bg-white">
                <input type="text" name="gambar_url_external" value="<?= $edit['gambar_url']??'' ?>" class="w-full border p-1 text-sm" placeholder="URL...">
                <?php if(!empty($edit['gambar_url']) && ($edit['tipe']??'image') == 'image'): ?>
                    <div class="mt-2"><img src="<?= strpos($edit['gambar_url'], 'http') === 0 ? $edit['gambar_url'] : '../'.$edit['gambar_url'] ?>" class="h-24 rounded border"></div>
                <?php endif; ?>
            </div>

            <div id="field-video" class="<?= (($edit['tipe']??'')=='video')?'':'hidden' ?> mb-4 p-4 border border-dashed rounded bg-blue-50">
                <label class="block font-bold mb-1 text-blue-800">Video Source</label>
                <div class="mb-2">
                    <label class="text-xs uppercase font-bold text-gray-500">Upload (MP4)</label>
                    <input type="file" name="video_upload" class="w-full border p-1 mb-1 bg-white" accept="video/mp4">
                    <?php if(!empty($edit['video_id']) && strpos($edit['video_id'], 'uploads/') !== false): ?>
                        <p class="text-xs text-green-600 mt-1">Video terupload: <?= basename($edit['video_id']) ?></p>
                    <?php endif; ?>
                </div>
                <div>
                    <label class="text-xs uppercase font-bold text-gray-500">Youtube ID</label>
                    <input type="text" name="video_url_external" value="<?= (strpos($edit['video_id']??'', 'uploads/') === false) ? ($edit['video_id']??'') : '' ?>" class="w-full border p-1 text-sm" placeholder="Contoh: dQw4w9WgXcQ">
                </div>
            </div>

            <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded font-bold hover:bg-blue-700">Simpan Promo</button>
        </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'; ?>