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

$upload_dir = __DIR__ . '/../public/uploads/';
$upload_url = PUBLIC_URL . 'uploads/';
$feedback_msg = '';
$feedback_type = 'error';

// Proses muat naik fail (kekal sama)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['media_file'])) {
    if (csrf_verify()) {
        $file = $_FILES['media_file'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            $max_size = 2*1024*1024;
            if ($file['size'] > $max_size) { $feedback_msg = 'Ralat: Saiz fail melebihi had 2MB.'; }
            else {
                $allowed_types = ['image/jpeg','image/png','image/gif','image/webp'];
                if (!in_array($file['type'], $allowed_types)) { $feedback_msg = 'Ralat: Jenis fail tidak dibenarkan.'; }
                else {
                    $filename = preg_replace('/[^a-zA-Z0-9-_\.]/','',basename($file['name']));
                    $unique_filename = uniqid().'_'.$filename;
                    if (move_uploaded_file($file['tmp_name'], $upload_dir.$unique_filename)) {
                        $feedback_msg = 'Fail berjaya dimuat naik!'; $feedback_type = 'success';
                    } else { $feedback_msg = 'Ralat: Gagal memindahkan fail.'; }
                }
            }
        } else { $feedback_msg = 'Ralat semasa memuat naik.'; }
    } else { $feedback_msg = 'Ralat CSRF.'; }
}

// *** LOGIK BARU: Proses untuk tetapkan imej ke slot tertentu ***
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_image'])) {
    if (csrf_verify()) {
        $image_url_to_set = $_POST['image_url'] ?? '';
        $image_slot_key = $_POST['image_slot'] ?? '';
        
        $allowed_keys = ['LOGO_URL', 'FAVICON_URL','HERO_IMAGE_URL', 'GUARANTEE_IMAGE_URL', 'TRUST_LOGO_1_URL', 'TRUST_LOGO_2_URL', 'TRUST_LOGO_3_URL'];

        if ($image_url_to_set && in_array($image_slot_key, $allowed_keys)) {
            set_setting($image_slot_key, $image_url_to_set);
            $feedback_msg = 'Imej telah berjaya ditetapkan!';
            $feedback_type = 'success';
        } else {
             $feedback_msg = 'Ralat: Slot imej tidak sah.';
        }
    } else {
        $feedback_msg = 'Ralat CSRF. Sila cuba lagi.';
    }
}

$images = glob($upload_dir . '*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
?>
<!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>Pengurusan Media</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; }
    .media-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px; }
    .media-item { border: 1px solid #e5e7eb; border-radius: 8px; overflow: hidden; display: flex; flex-direction: column; }
    .media-item img { width: 100%; height: 150px; object-fit: cover; }
    .media-item .info { padding: 8px; background: #f8fafc; flex-grow: 1; }
    .media-item .info input { width: 100%; font-size: 11px; padding: 4px; border: 1px solid #ccc; border-radius: 4px; margin-bottom: 8px; }
    .media-item .actions select { width: 100%; padding: 6px; margin-bottom: 6px; border-radius: 6px; border: 1px solid #ccc;}
    .media-item .actions button { background-color: #4f46e5; color: white; border: none; padding: 6px 8px; border-radius: 6px; font-size: 12px; width: 100%; cursor: pointer; }
</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>Pengurusan Media</h1>
        <?php if ($feedback_msg): ?><div class="feedback <?= $feedback_type ?>"><?= e($feedback_msg) ?></div><?php endif; ?>
        <div class="card">
            <h2>Muat Naik Imej Baru</h2>
            <form method="post" enctype="multipart/form-data">
                <?= csrf_field() ?><p>Pilih fail imej (JPG, PNG, GIF, WEBP). Saiz maksimum: 2MB.</p>
                <input type="file" name="media_file" required>
                <button type="submit" class="cta" style="margin-top:12px;">Muat Naik</button>
            </form>
        </div>
        <div class="card">
            <h2>Galeri Media</h2>
            <div class="media-grid">
                <?php foreach (array_reverse($images) as $image_path):
                    $filename = basename($image_path); $file_url = PUBLIC_URL.'uploads/'.$filename;
                ?>
                <div class="media-item">
                    <img src="<?= e($file_url) ?>" alt="<?= e($filename) ?>">
                    <div class="info">
                        <input type="text" value="<?= e($file_url) ?>" readonly onclick="this.select();" title="URL Imej">
                        <form method="post" class="actions">
                            <?= csrf_field() ?>
                            <input type="hidden" name="image_url" value="<?= e($file_url) ?>">
                            <select name="image_slot" required>
                                <option value="">-- Tetapkan Untuk --</option>
                                <option value="LOGO_URL">logo syarikat</option>
                                <option value="FAVICON_URL">logo favicon syarikat</option>
                                <option value="HERO_IMAGE_URL">Imej Utama (Hero)</option>
                                <option value="GUARANTEE_IMAGE_URL">Logo Jaminan</option>
                                <option value="TRUST_LOGO_1_URL">Logo Keyakinan 1</option>
                                <option value="TRUST_LOGO_2_URL">Logo Keyakinan 2</option>
                                <option value="TRUST_LOGO_3_URL">Logo Keyakinan 3</option>
                            </select>
                            <button type="submit" name="assign_image" value="1">Tetapkan</button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </main>
</div>
</div></body></html>