<?php
require_once __DIR__.'/../inc/config.php';
require_once __DIR__.'/../inc/db.php';
require_once __DIR__.'/../inc/helpers.php';
require_once __DIR__.'/../inc/csrf.php';

// ... require_once ...
if(empty($_SESSION['admin_id'])){ header('Location: login.php'); exit; } // 1. Semak login dahulu
if ($_SESSION['admin_role'] !== 'admin') { // 2. Kemudian baru semak role
    exit('Akses disekat. Anda tiada kebenaran untuk melihat halaman ini.');
}

if(empty($_SESSION['admin_id'])){ header('Location: login.php'); exit; }

$feedback_msg = '';
$feedback_type = 'error';

// BLOK KOD BARU YANG DIPERTINGKAT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify()) {
    $action = $_POST['action'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if ($action === 'delete' && $id > 0) {
        try {
            db()->prepare("DELETE FROM packages WHERE id=?")->execute([$id]);
            $feedback_msg = 'Pakej telah berjaya dipadam.';
            $feedback_type = 'success';
        } catch (PDOException $e) {
            $feedback_msg = 'Gagal memadam. Pakej ini mungkin telah digunakan dalam rekod pesanan sedia ada.';
            $feedback_type = 'error';
        }
    } 
    elseif ($action === 'save') {
        $name = trim($_POST['name'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $features = trim($_POST['features'] ?? '');
        $subtitle = trim($_POST['subtitle'] ?? ''); // <-- TAMBAH INI
        $best_seller = !empty($_POST['best_seller']) ? 1 : 0;
        $active = !empty($_POST['active']) ? 1 : 0;

        if ($name && $price > 0) {
            if ($id > 0) {
                // KEMAS KINI QUERY INI
                db()->prepare("UPDATE packages SET name=?, price=?, features=?, best_seller=?, active=?, subtitle=?, description=? WHERE id=?")->execute([$name, $price, $features, $best_seller, $active, $subtitle, $_POST['description'] ?? '', $id]);
                $feedback_msg = 'Pakej berjaya dikemaskini.';
            } else {
                // KEMAS KINI QUERY INI
                db()->prepare("INSERT INTO packages(name, price, features, best_seller, active, subtitle, description) VALUES(?,?,?,?,?,?,?)")->execute([$name, $price, $features, $best_seller, $active, $subtitle, $_POST['description'] ?? '']);

                $feedback_msg = 'Pakej baru berjaya ditambah.';
            }
            $feedback_type = 'success';
        } else {
            $feedback_msg = 'Nama dan Harga pakej diperlukan.';
        }
    }
}

// Dapatkan semua pakej untuk dipaparkan dalam senarai
$packages = db()->query("SELECT * FROM packages ORDER BY id ASC")->fetchAll();
$editing_package = null;

// Bahagian ini memeriksa jika URL mempunyai `?edit=...`
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $st = db()->prepare("SELECT * FROM packages WHERE id=?");
    $st->execute([$edit_id]);
    $editing_package = $st->fetch();
}
?>
<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../public/assets/css/style.css"><title>Urus Pakej</title>
<style>
    .admin-wrapper { display: flex; align-items: flex-start; gap: 24px; } .admin-sidebar { width: 220px; flex-shrink: 0; } .admin-content { flex-grow: 1; } .feedback { padding: 12px; border-radius: 12px; margin-bottom: 20px; } .feedback.success { background-color: #dcfce7; color: #166534; } .feedback.error { background-color: #fee2e2; color: #991b1b; } table { width: 100%; border-collapse: collapse; } th, td { padding: 10px; text-align: left; border-bottom: 1px solid #e5e7eb; } th { background-color: #f8fafc; } .form-group label { display: block; margin-bottom: 16px; font-weight: 600; } .form-group input, .form-group textarea, .form-group select { width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 8px; margin-top: 6px; box-sizing: border-box; } .form-check { margin-top: 10px; }
</style>
</head><body><div class="container">
<div class="admin-wrapper">
    <aside class="admin-sidebar"><?php require_once '_menu.php'; ?></aside>
    <main class="admin-content">
        <h1>Urus Pakej</h1>
        <?php if ($feedback_msg): ?><div class="feedback <?= $feedback_type ?>"><?= e($feedback_msg) ?></div><?php endif; ?>

        <div class="card">
            <h2>Senarai Pakej</h2>
            <table>
                <tr><th>ID</th><th>Nama Pakej</th><th>Harga</th><th>Status</th><th>Tindakan</th></tr>
                <?php foreach($packages as $p): ?>
                <tr>
                    <td><?= $p['id'] ?></td>
                    <td><?= e($p['name']) ?> <?= $p['best_seller'] ? '<span style="font-size:10px; background-color:#fef9c3; color:#b45309; padding:2px 6px; border-radius:999px;">Paling Laris</span>' : '' ?></td>
                    <td><?= money($p['price']) ?></td>
                    <td><?= $p['active'] ? 'Aktif' : 'Tidak Aktif' ?></td>
                    <td>
                        <a href="?edit=<?= $p['id'] ?>" class="cta" style="font-size:12px; padding:6px 10px; background-color:#4f46e5;">Edit</a>
                        
                        <form action="packages.php" method="post" style="display:inline-block;" onsubmit="return confirm('Anda pasti mahu padam pakej ini?');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= $p['id'] ?>">
                            <button type="submit" style="background-color:#ef4444; color:white; border:none; border-radius: 8px; padding:6px 10px; font-size:12px; cursor:pointer;">Padam</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>

        <div class="card">
            <h2><?= $editing_package ? 'Edit Pakej #' . e((string)$editing_package['id']) : 'Tambah Pakej Baru' ?></h2>
            <div class="admin-note">
            <strong>NOTA:</strong><br>
            Untuk <b>BOLD</b>, gunakan: <code>&lt;b&gt;Teks Anda&lt;/b&gt;</code><br>
            Untuk <span style="color:red;">WARNA</span>, gunakan: <code>&lt;span style="color:red;"&gt;Teks Anda&lt;/span&gt;</code><br><br>
        </div>
            
            
            <form action="packages.php" method="post">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" value="<?= $editing_package['id'] ?? 0 ?>">
                <div class="form-group"><label>Nama Pakej<input name="name" value="<?= e($editing_package['name'] ?? '') ?>" required></label></div>
                <div class="form-group"><label>Harga (cth: 35.00)<input type="number" step="0.01" name="price" value="<?= e((string)($editing_package['price'] ?? '')) ?>" required></label></div>
                <div class="form-group"><label>Subtitle (cth: Nilai Sebenar RM102 / Jimat RM07)
                <input name="subtitle" value="<?= e($editing_package['subtitle'] ?? '') ?>">
                </label></div>
                
                <div class="form-group"><label>Butiran Kandungan Pakej (untuk senarai pembungkusan)
                <textarea name="description" rows="3" placeholder="cth: 6 Pek Vanilla Blue 1kg"><?= e($editing_package['description'] ?? '') ?></textarea>
                </label></div>
                
                <div class="form-group"><label>Ciri-ciri (satu per baris, gunakan simbol paip |)<textarea name="features" rows="4"><?= e($editing_package['features'] ?? '') ?></textarea></label></div>
                <div class="form-check"><label><input type="checkbox" name="best_seller" value="1" <?= ($editing_package['best_seller'] ?? 0) ? 'checked' : '' ?>> Tandakan sebagai Paling Laris</label></div>
                <div class="form-check"><label><input type="checkbox" name="active" value="1" <?= ($editing_package['active'] ?? 1) ? 'checked' : '' ?>> Aktifkan Pakej</label></div>
                <button type="submit" class="cta" style="margin-top:20px;"><?= $editing_package ? 'Simpan Perubahan' : 'Tambah Pakej Baru' ?></button>
                <?php if ($editing_package): ?><a href="packages.php" style="margin-left:10px;">Batal</a><?php endif; ?>
            </form>
            
            
        </div>
    </main>
</div>
</div></body></html>