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

// Logik untuk simpan tajuk utama bahagian
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_title'])) {
    if (csrf_verify()) {
        set_setting('FEATURES_TITLE', $_POST['features_title'] ?? '');
        $feedback_msg = 'Tajuk bahagian telah berjaya disimpan.';
        $feedback_type = 'success';
    }
}

function handle_feature_image_upload(string $file_input_name) {
    if (isset($_FILES[$file_input_name]) && $_FILES[$file_input_name]['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES[$file_input_name];
        $upload_dir = __DIR__ . '/../public/uploads/';
        $upload_url = PUBLIC_URL . 'uploads/';

        $filename = preg_replace('/[^a-zA-Z0-9-_\.]/', '', basename($file['name']));
        $unique_filename = uniqid() . '_' . $filename;
        $destination = $upload_dir . $unique_filename;

        if (move_uploaded_file($file['tmp_name'], $destination)) {
            return $upload_url . $unique_filename;
        }
    }
    return null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify()) {
    $action = $_POST['action'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if ($action === 'delete' && $id > 0) {
        db()->prepare("DELETE FROM features WHERE id=?")->execute([$id]);
        $feedback_msg = 'Ciri telah berjaya dipadam.';
        $feedback_type = 'success';
    } elseif ($action === 'save') {
        $headline = trim($_POST['headline'] ?? '');
        $text = trim($_POST['text'] ?? '');
        $active = !empty($_POST['active']) ? 1 : 0;
        $image_url = $_POST['existing_image_url'] ?? '';

        $new_image_url = handle_feature_image_upload('image_file');
        if ($new_image_url) {
            $image_url = $new_image_url;
        }

        if ($headline && $text && $image_url) {
            if ($id > 0) {
                db()->prepare("UPDATE features SET image_url=?, headline=?, text=?, active=? WHERE id=?")->execute([$image_url, $headline, $text, $active, $id]);
                $feedback_msg = 'Ciri berjaya dikemaskini.';
            } else {
                db()->prepare("INSERT INTO features(image_url, headline, text, active) VALUES(?,?,?,?)")->execute([$image_url, $headline, $text, $active]);
                $feedback_msg = 'Ciri baru berjaya ditambah.';
            }
            $feedback_type = 'success';
        } else {
            $feedback_msg = 'Imej Ikon, Tajuk, dan Teks diperlukan.';
        }
    }
}

$features = db()->query("SELECT * FROM features ORDER BY id ASC")->fetchAll();
$editing_feature = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $st = db()->prepare("SELECT * FROM features WHERE id=?");
    $st->execute([$edit_id]);
    $editing_feature = $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 Ciri-ciri</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 { 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 Ciri-ciri Produk</h1>
        
        <div class="card">
    <h2>Tetapan Bahagian</h2>
    <form action="features.php" method="post">
        <?= csrf_field() ?>
        <div class="form-group">
            <label>Tajuk Utama Bahagian Ciri-ciri
                <input name="features_title" value="<?= e(setting('FEATURES_TITLE', 'Kenapa Ia Pilihan Peniaga Bijak?')) ?>">
            </label>
        </div>
        <button type="submit" name="save_title" class="cta">Simpan Tajuk</button>
    </form>
</div>
        
        <?php if ($feedback_msg): ?><div class="feedback <?= $feedback_type ?>"><?= e($feedback_msg) ?></div><?php endif; ?>

        <div class="card">
            <h2>Senarai Ciri-ciri</h2>
            <table>
                <tr><th>ID</th><th>Ikon</th><th>Tajuk</th><th>Status</th><th>Tindakan</th></tr>
                <?php foreach($features as $f): ?>
                <tr>
                    <td><?= $f['id'] ?></td>
                    <td><img src="<?= e($f['image_url']) ?>" alt="" style="width:40px; height:40px; object-fit:contain;"></td>
                    <td style="max-width:300px;"><?= e($f['headline']) ?></td>
                    <td><?= $f['active'] ? 'Aktif' : 'Tidak Aktif' ?></td>
                    <td>
                        <a href="?edit=<?= $f['id'] ?>" class="cta" style="font-size:12px; padding:6px 10px; background-color:#4f46e5;">Edit</a>
                        <form action="features.php" method="post" style="display:inline-block;" onsubmit="return confirm('Anda pasti mahu padam ini?');">
                            <?= csrf_field() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= $f['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_feature ? 'Edit Ciri' : 'Tambah Ciri Baru' ?></h2>
            <form action="features.php" method="post" enctype="multipart/form-data">
                <?= csrf_field() ?><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= $editing_feature['id'] ?? 0 ?>">
                <div class="form-group"><label>Imej Ikon<input type="file" name="image_file" <?= $editing_feature ? '' : 'required' ?>><input type="hidden" name="existing_image_url" value="<?= e($editing_feature['image_url'] ?? '') ?>"></label></div>
                <div class="form-group"><label>Tajuk<input name="headline" value="<?= e($editing_feature['headline'] ?? '') ?>" required></label></div>
                <div class="form-group"><label>Teks<textarea name="text" rows="3" required><?= e($editing_feature['text'] ?? '') ?></textarea></label></div>
                <div class="form-check"><label><input type="checkbox" name="active" value="1" <?= ($editing_feature['active'] ?? 1) ? 'checked' : '' ?>> Aktifkan</label></div>
                <button type="submit" class="cta" style="margin-top:20px;"><?= $editing_feature ? 'Simpan Perubahan' : 'Tambah Ciri' ?></button>
                <?php if ($editing_feature): ?><a href="features.php" style="margin-left:10px;">Batal</a><?php endif; ?>
            </form>
        </div>
    </main>
</div>
</div></body></html>