<?php
declare(strict_types=1);

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

/* ================= VALIDATION ================= */
$id = (int) ($_GET['id'] ?? 0);
if ($id <= 0) {
    header('Location: index.php');
    exit;
}

$db = Database::getInstance();

/* ================= LOAD SECTION ================= */
$stmt = $db->prepare("
    SELECT * FROM retail_product_sections WHERE id = :id
");
$stmt->execute(['id' => $id]);
$section = $stmt->fetch();

if (!$section) {
    header('Location: index.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Edit Section']); ?>
<?php include '../partials/head-css.php'; ?>

<style>
.media-preview {
    width: 100%;
    aspect-ratio: 4 / 3;
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: .5rem;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
}
.media-preview img,
.media-preview video {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
</style>
</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 Product Section'
]); ?>

<div class="row g-4">

<!-- ================= CURRENT MEDIA ================= -->
<div class="col-lg-6">
<div class="card shadow-sm h-100">
<div class="card-header">
    <strong>Current Media</strong>
</div>
<div class="card-body">

<div class="media-preview mb-3">
<?php if ($section['file_type'] === 'Image'): ?>
    <img src="<?= $section['file_path'] ?>" alt="">
<?php else: ?>
    <?php if (!empty($section['thumbnail_path'])): ?>
        <img src="<?= $section['thumbnail_path'] ?>" alt="">
    <?php else: ?>
        <video src="<?= $section['file_path'] ?>" controls></video>
    <?php endif; ?>
<?php endif; ?>
</div>

<p class="text-muted mb-0">
    <small>Upload a new file to replace existing media</small>
</p>

</div>
</div>
</div>

<!-- ================= EDIT FORM ================= -->
<div class="col-lg-6">
<div class="card shadow-sm">
<div class="card-body">

<form id="editSectionForm">

<input type="hidden" id="section_id" value="<?= $section['id'] ?>">

<div class="row g-3">

<!-- SECTION TITLE -->
<div class="col-md-12">
    <label class="form-label">Section Title</label>
    <input type="text" id="section_title"
           class="form-control"
           value="<?= htmlspecialchars($section['section_title']) ?>">
</div>

<!-- PREVIEW TYPE -->
<div class="col-md-6">
    <label class="form-label">Preview Type</label>
    <select id="preview_type" class="form-select">
        <?php foreach (['Desktop','Mobile','Both'] as $p): ?>
            <option value="<?= $p ?>"
                <?= $section['preview_type'] === $p ? 'selected' : '' ?>>
                <?= $p ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>

<!-- PRIORITY -->
<div class="col-md-3">
    <label class="form-label">Priority</label>
    <input type="number" id="priority"
           class="form-control"
           value="<?= $section['priority'] ?>">
</div>

<!-- STATUS -->
<div class="col-md-3">
    <label class="form-label">Status</label>
    <select id="status" class="form-select">
        <option value="Draft" <?= $section['status'] === 'Draft' ? 'selected' : '' ?>>Draft</option>
        <option value="Active" <?= $section['status'] === 'Active' ? 'selected' : '' ?>>Active</option>
        <option value="InActive" <?= $section['status'] === 'InActive' ? 'selected' : '' ?>>Inactive</option>
    </select>
</div>

<!-- ALT TEXT -->
<div class="col-md-6">
    <label class="form-label">Alt Text</label>
    <input type="text" id="alt_text"
           class="form-control"
           value="<?= htmlspecialchars($section['alt_text']) ?>">
</div>

<!-- CAPTION -->
<div class="col-md-6">
    <label class="form-label">Caption</label>
    <input type="text" id="caption"
           class="form-control"
           value="<?= htmlspecialchars($section['caption']) ?>">
</div>

<!-- MEDIA REPLACE -->
<div class="col-md-12">
    <label class="form-label">Replace Media (optional)</label>
    <input type="file" id="media_file" class="form-control">
</div>

</div>

<div class="text-end mt-4">
    <a href="view-section.php?id=<?= $section['id'] ?>.php" class="btn btn-light me-2">Cancel</a>
    <button class="btn btn-warning">
        <i class="bi bi-save me-1"></i> Update Section
    </button>
</div>

</form>

</div>
</div>
</div>

</div>
</main>

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

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

<script>
const API_UPLOAD =
    "<?= ADMIN_BASE_URL ?>api/retail-product-sections/upload-media.php";
const API_UPDATE =
    "<?= ADMIN_BASE_URL ?>api/retail-product-sections/update.php";

document.getElementById('editSectionForm')
.addEventListener('submit', async function (e) {

    e.preventDefault();

    const statusEl = document.getElementById('status'); // ✅ FIX

    let filePath = "<?= $section['file_path'] ?>";
    let thumbPath = "<?= $section['thumbnail_path'] ?>";

    if (media_file.files.length) {

        const fd = new FormData();
        fd.append('file_type', "<?= $section['file_type'] ?>");
        fd.append('file', media_file.files[0]);

        const uploadRes = await fetch(API_UPLOAD, {
            method: 'POST',
            credentials: 'include',
            body: fd
        }).then(r => r.json());

        if (uploadRes.status !== 'success') {
            alert(uploadRes.message || 'Media upload failed');
            return;
        }

        filePath  = uploadRes.data.file_path;
        thumbPath = uploadRes.data.thumbnail_path || null;
    }

    const payload = {
        id: section_id.value,
        section_title: section_title.value || null,
        preview_type: preview_type.value,
        priority: priority.value,
        status: statusEl.value, // ✅ ALWAYS PRESENT
        alt_text: alt_text.value || null,
        caption: caption.value || null,
        file_path: filePath,
        thumbnail_path: thumbPath
    };

    console.log('UPDATE PAYLOAD:', payload); // optional debug

    const res = await fetch(API_UPDATE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify(payload)
    }).then(r => r.json());

    if (res.status !== 'success') {
        alert(res.message || 'Update failed');
        return;
    }

    window.location.href =
        "view-section.php?id=<?= $section['id'] ?>";
});
</script>

</body>
</html>
