<?php
declare(strict_types=1);

/* ================= AUTH ================= */
require_once __DIR__ . '/../security/auth_guard_web.php';
require_once __DIR__ . '/../partials/main.php';

/* ================= VALIDATION ================= */
if (empty($_SESSION['employee_id'])) {
    header('Location: ' . ADMIN_BASE_URL . 'login.php');
    exit;
}

if (empty($_GET['id']) || !ctype_digit($_GET['id'])) {
    header('Location: ' . ADMIN_BASE_URL . 'home-sliders/list.php');
    exit;
}

$sliderId = (int) $_GET['id'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Edit Home Slider']); ?>
<?php include '../partials/head-css.php'; ?>
</head>

<body>
<div id="layout-wrapper">

<?php include '../partials/header.php'; ?>
<?php include '../partials/sidebar.php'; ?>
<?php include '../partials/horizontal.php'; ?>

<main class="app-wrapper">
<div class="container-fluid">

<?php includeFileWithVariables('../partials/page-title.php', [
    'title_sub' => 'CMS',
    'title'     => 'Edit Home Page Slider'
]); ?>

<form id="sliderForm" enctype="multipart/form-data">

<input type="hidden" name="id" value="<?= $sliderId ?>">

<div class="card">
<div class="card-body">

<div class="row g-3">

<!-- TITLE -->
<div class="col-md-6">
    <label class="form-label">Title</label>
    <input type="text" name="title" class="form-control">
</div>

<!-- SUBTITLE -->
<div class="col-md-6">
    <label class="form-label">Subtitle</label>
    <input type="text" name="subtitle" class="form-control">
</div>

<!-- DESKTOP IMAGE -->
<div class="col-md-6">
    <label class="form-label">Desktop Image</label>
    <input type="file" name="desktop_image" class="form-control" accept="image/*">
    <div class="mt-2">
        <img id="desktopPreview" src="" width="150" class="rounded d-none">
    </div>
    <small class="text-muted">Leave empty to keep existing</small>
</div>

<!-- MOBILE IMAGE -->
<div class="col-md-6">
    <label class="form-label">Mobile Image</label>
    <input type="file" name="mobile_image" class="form-control" accept="image/*">
    <div class="mt-2">
        <img id="mobilePreview" src="" width="100" class="rounded d-none">
    </div>
    <small class="text-muted">Leave empty to keep existing</small>
</div>

<!-- PRIORITY -->
<div class="col-md-3">
    <label class="form-label">
        Priority <span class="text-danger">*</span>
    </label>
    <input type="number" name="priority" class="form-control" min="1" required>
</div>

<!-- STATUS -->
<div class="col-md-3">
    <label class="form-label">Status</label>
    <select name="is_active" class="form-select">
        <option value="1">Active</option>
        <option value="0">Inactive</option>
    </select>
</div>

<!-- LINK URL -->
<div class="col-md-6">
    <label class="form-label">CTA Link URL</label>
    <input type="url" name="link_url" class="form-control">
</div>

<!-- LINK TEXT -->
<div class="col-md-6">
    <label class="form-label">CTA Button Text</label>
    <input type="text" name="link_text" class="form-control">
</div>

</div>

</div>

<div class="card-footer d-flex justify-content-between">
    <a href="<?= ADMIN_BASE_URL ?>home-sliders/list.php" class="btn btn-light">
        Back
    </a>
    <button type="submit" class="btn btn-warning">
        <i class="bi bi-save me-1"></i> Update Slider
    </button>
</div>

</div>
</form>

</div>
</main>

<?php include '../partials/footer.php'; ?>
</div>

<?php include '../partials/vendor-scripts.php'; ?>

<script>
const SLIDER_ID  = <?= $sliderId ?>;
const API_LIST   = "<?= ADMIN_BASE_URL ?>api/home-sliders/list.php";
const API_UPDATE = "<?= ADMIN_BASE_URL ?>api/home-sliders/update.php";

/* ================= LOAD SLIDER ================= */
fetch(API_LIST, { credentials: 'include' })
.then(r => r.json())
.then(res => {
    if (res.status !== 'success') return;

    const slider = res.data.sliders.find(s => s.id == SLIDER_ID);
    if (!slider) {
        window.location.href = "<?= ADMIN_BASE_URL ?>home-sliders/list.php";
        return;
    }

    document.querySelector('[name="title"]').value = slider.title ?? '';
    document.querySelector('[name="subtitle"]').value = slider.subtitle ?? '';
    document.querySelector('[name="priority"]').value = slider.priority;
    document.querySelector('[name="is_active"]').value = slider.is_active;
    document.querySelector('[name="link_url"]').value = slider.link_url ?? '';
    document.querySelector('[name="link_text"]').value = slider.link_text ?? '';

    if (slider.desktop_image_url) {
        const d = document.getElementById('desktopPreview');
        d.src = slider.desktop_image_url;
        d.classList.remove('d-none');
    }

    if (slider.mobile_image_url) {
        const m = document.getElementById('mobilePreview');
        m.src = slider.mobile_image_url;
        m.classList.remove('d-none');
    }
});

/* ================= SUBMIT ================= */
document.getElementById('sliderForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const formData = new FormData(this);

    fetch(API_UPDATE, {
        method: 'POST',
        credentials: 'include',
        body: formData
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            alert(res.message || 'Failed to update slider');
            return;
        }

        window.location.href =
            "<?= ADMIN_BASE_URL ?>home-sliders/list.php";
    })
    .catch(() => alert('Server error'));
});
</script>

</body>
</html>
