<?php
declare(strict_types=1);

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

$db = Database::getInstance();

/* ================= LOAD HOSPITALITY PRODUCTS ================= */
$stmt = $db->prepare("
    SELECT id, title
    FROM hospitality_products
    ORDER BY title ASC
");
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', [
    'title' => 'Add Hospitality Section'
]); ?>

<link rel="stylesheet"
      href="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.snow.css">

<?php include '../partials/head-css.php'; ?>

<style>
.media-box {
    width: 100%;
    aspect-ratio: 4 / 3;
    background: #f8f9fa;
    border: 1px dashed #ced4da;
    border-radius: .5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #6c757d;
}
</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' => 'Hospitality',
    'title'     => 'Add Product Section'
]); ?>

<form id="sectionForm">

<div class="row g-4">

<!-- ================= LEFT: DETAILS ================= -->
<div class="col-lg-6">
<div class="card shadow-sm h-100">
<div class="card-header"><strong>Section Details</strong></div>
<div class="card-body">

<div class="mb-3">
<label class="form-label">
Hospitality Product <span class="text-danger">*</span>
</label>
<select id="hospitality_product_id" class="form-select" required>
<option value="">-- Select Product --</option>
<?php foreach ($products as $p): ?>
<option value="<?= (int)$p['id'] ?>">
    <?= htmlspecialchars($p['title']) ?>
</option>
<?php endforeach; ?>
</select>
</div>

<div class="mb-3">
<label class="form-label">Section Title</label>
<input id="section_title" class="form-control">
</div>

<div class="mb-3">
<label class="form-label">Section Key</label>
<input id="section_key"
       class="form-control"
       placeholder="hero, gallery, features">
</div>

<div class="mb-3">
<label class="form-label">Short Description</label>
<textarea id="short_description"
          class="form-control"
          rows="3"></textarea>
</div>

<div class="mb-3">
<label class="form-label">Full Description</label>
<div id="editor" style="height:220px"></div>
</div>

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

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

<div class="row g-3">

<div class="col-md-6">
<label class="form-label">File Type</label>
<select id="file_type" class="form-select">
<option value="Image">Image</option>
<option value="Video">Video</option>
</select>
</div>

<div class="col-md-6">
<label class="form-label">Preview Type</label>
<select id="preview_type" class="form-select">
<option value="Desktop">Desktop</option>
<option value="Mobile">Mobile</option>
<option value="Both" selected>Both</option>
</select>
</div>

<div class="col-12">
<label class="form-label">
Upload Media <span class="text-danger">*</span>
</label>
<input type="file" id="media_file" class="form-control" required>
</div>

<div class="col-md-6">
<label class="form-label">Priority</label>
<input type="number" id="priority"
       class="form-control" value="1">
</div>

<div class="col-md-6">
<label class="form-label">Status</label>
<select id="status" class="form-select">
<option value="Draft">Draft</option>
<option value="Active">Active</option>
</select>
</div>

</div>

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

<!-- ================= ACTIONS ================= -->
<div class="col-12">
<div class="card">
<div class="card-body text-end">
<a href="sections-list.php" class="btn btn-light">Cancel</a>
<button type="submit" class="btn btn-success">
    <i class="bi bi-plus-lg me-1"></i> Create Section
</button>
</div>
</div>
</div>

</div>
</form>

</div>
</main>

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

<?php include '../partials/vendor-scripts.php'; ?>
<script src="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.js"></script>

<script>
const API_UPLOAD =
    "<?= ADMIN_BASE_URL ?>api/hospitality-product-sections/upload-media.php";
const API_CREATE =
    "<?= ADMIN_BASE_URL ?>api/hospitality-product-sections/create.php";

let quill;

/* ================= INIT EDITOR ================= */
document.addEventListener('DOMContentLoaded', () => {
    quill = new Quill('#editor', { theme: 'snow' });
});

/* ================= SUBMIT ================= */
document.getElementById('sectionForm')
.addEventListener('submit', async function (e) {

    e.preventDefault();

    if (!hospitality_product_id.value) {
        alert('Please select a hospitality product');
        return;
    }

    if (!media_file.files.length) {
        alert('Please upload an image or video');
        return;
    }

    const submitBtn = this.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = 'Creating…';

    try {

        /* ---------- UPLOAD MEDIA ---------- */
        const fd = new FormData();
        fd.append('file_type', file_type.value);
        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') {
            throw new Error(uploadRes.message || 'Media upload failed');
        }

        /* ---------- CREATE SECTION ---------- */
        const payload = {
            hospitality_product_id: hospitality_product_id.value,
            section_title: section_title.value || null,
            section_key: section_key.value || null,
            short_description: short_description.value || null,
            description: quill.root.innerHTML || null,
            file_type: file_type.value,
            preview_type: preview_type.value,
            file_path: uploadRes.data.file_path,
            thumbnail_path: uploadRes.data.thumbnail_path || null,
            priority: priority.value || 0,
            status: status.value
        };

        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') {
            throw new Error(res.message || 'Create failed');
        }

        window.location.href = 'section-list.php';

    } catch (err) {
        alert(err.message);
        submitBtn.disabled = false;
        submitBtn.innerHTML = 'Create Section';
    }
});
</script>

</body>
</html>
