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

$db = Database::getInstance();

/* ================= LOAD PRODUCTS ================= */
$stmt = $db->prepare("
    SELECT id, product_name
    FROM retail_products
    ORDER BY product_name ASC
");
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Add Section']); ?>
<?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' => 'Catalog',
    'title'     => 'Add Product Section'
]); ?>

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

<form id="addSectionForm">

<div class="row g-3">

<!-- PRODUCT -->
<div class="col-md-4">
    <label class="form-label">Select Product *</label>
    <select id="product_id" class="form-select" required>
        <option value="">-- Select Product --</option>
        <?php foreach ($products as $p): ?>
            <option value="<?= (int)$p['id'] ?>">
                <?= htmlspecialchars($p['product_name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>

<!-- SECTION TITLE -->
<div class="col-md-4">
    <label class="form-label">Section Title</label>
    <input type="text" id="section_title" class="form-control">
</div>

<!-- SECTION KEY -->
<div class="col-md-4">
    <label class="form-label">Section Key</label>
    <input type="text" id="section_key"
           class="form-control"
           placeholder="hero, gallery, feature_1">
</div>

<!-- FILE TYPE -->
<div class="col-md-3">
    <label class="form-label">File Type *</label>
    <select id="file_type" class="form-select" required>
        <option value="Image">Image</option>
        <option value="Video">Video</option>
    </select>
</div>

<!-- PREVIEW -->
<div class="col-md-3">
    <label class="form-label">Preview *</label>
    <select id="preview_type" class="form-select" required>
        <option value="Desktop">Desktop</option>
        <option value="Mobile">Mobile</option>
        <option value="Both">Both</option>
    </select>
</div>

<!-- FILE -->
<div class="col-md-6">
    <label class="form-label">Upload File *</label>
    <input type="file" id="media_file" class="form-control" required>
</div>

<!-- PRIORITY -->
<div class="col-md-2">
    <label class="form-label">Priority *</label>
    <input type="number" id="priority"
           class="form-control"
           min="0" required>
</div>

<!-- ALT -->
<div class="col-md-5">
    <label class="form-label">Alt Text</label>
    <input type="text" id="alt_text" class="form-control">
</div>

<!-- CAPTION -->
<div class="col-md-5">
    <label class="form-label">Caption</label>
    <input type="text" id="caption" class="form-control">
</div>

<div class="col-md-3 align-self-end">
    <button class="btn btn-success w-100">
        <i class="bi bi-plus-lg me-1"></i> Add Section
    </button>
</div>

</div>
</form>

</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_CREATE =
    "<?= ADMIN_BASE_URL ?>api/retail-product-sections/create.php";

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

    e.preventDefault();

    const productId = product_id.value;
    if (!productId) {
        alert('Please select a product');
        return;
    }

    const file = media_file.files[0];
    if (!file) {
        alert('Please upload a file');
        return;
    }

    const fileType = file_type.value;

    /* ================= UPLOAD MEDIA ================= */
    const uploadFd = new FormData();
    uploadFd.append('file_type', fileType);
    uploadFd.append('file', file);

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

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

    /* ================= CREATE SECTION ================= */
    const payload = {
        product_id: productId,
        section_title: section_title.value || null,
        section_key: section_key.value || null,
        file_type: fileType,
        preview_type: preview_type.value,
        file_path: uploadRes.data.file_path,
        thumbnail_path: uploadRes.data.thumbnail_path || null,
        priority: priority.value,
        alt_text: alt_text.value || null,
        caption: caption.value || null
    };

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

    if (res.status !== 'success') {
        alert(res.message || 'Failed to create section');
        return;
    }

    alert('Section added successfully');
    window.location.href =
        "<?= ADMIN_BASE_URL ?>retail-products/sections-list.php";
});
</script>

</body>
</html>
