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

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

$db = Database::getInstance();

/* ================= LOAD SECTION ================= */
$stmt = $db->prepare("
    SELECT s.*, p.title AS product_title
    FROM hospitality_product_sections s
    JOIN hospitality_products p ON p.id = s.hospitality_product_id
    WHERE s.id = :id
");
$stmt->execute(['id' => $id]);
$section = $stmt->fetch(PDO::FETCH_ASSOC);

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

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

<style>
.media-box{
    width:100%;
    aspect-ratio:4/3;
    border:1px solid #dee2e6;
    border-radius:.5rem;
    background:#f8f9fa;
    overflow:hidden;
}
.media-box img,
.media-box 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' => 'Hospitality',
    'title'     => 'Edit Section'
]); ?>

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

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

<div class="row g-4">

<!-- ================= MEDIA ================= -->
<div class="col-lg-4">
<div class="card shadow-sm">
<div class="card-header"><strong>Media</strong></div>
<div class="card-body">

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

<label class="form-label">Replace Media (optional)</label>
<input type="file" name="media_file" class="form-control">

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

<!-- ================= DETAILS ================= -->
<div class="col-lg-8">
<div class="card shadow-sm">
<div class="card-header"><strong>Section Details</strong></div>
<div class="card-body row g-3">

<div class="col-md-4">
<label class="form-label">Product</label>
<input class="form-control bg-light"
       value="<?= htmlspecialchars($section['product_title']) ?>" readonly>
</div>

<div class="col-md-4">
<label class="form-label">Section Key</label>
<input name="section_key" class="form-control"
       value="<?= htmlspecialchars($section['section_key']) ?>">
</div>

<div class="col-md-4">
<label class="form-label">Priority</label>
<input type="number" name="priority" class="form-control"
       value="<?= (int)$section['priority'] ?>">
</div>

<div class="col-md-6">
<label class="form-label">Section Title</label>
<input name="section_title" class="form-control"
       value="<?= htmlspecialchars($section['section_title']) ?>">
</div>

<div class="col-md-3">
<label class="form-label">Status</label>
<select name="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>

<div class="col-md-3">
<label class="form-label">Approval</label>
<select name="approval_status" class="form-select">
<option value="Pending" <?= $section['approval_status']==='Pending'?'selected':'' ?>>Pending</option>
<option value="Approved" <?= $section['approval_status']==='Approved'?'selected':'' ?>>Approved</option>
<option value="Rejected" <?= $section['approval_status']==='Rejected'?'selected':'' ?>>Rejected</option>
</select>
</div>

<div class="col-12">
<label class="form-label">Short Description</label>

<input type="hidden" name="short_description" id="short_description">
<input type="text" name="short_description" id="short_description" class="form-control" value="<?= htmlspecialchars($section['short_description']) ?>">
</div>

<div class="col-12">
<label class="form-label">Description</label>
<div id="editor" style="height:280px"></div>
<input type="hidden" name="description" id="description">
</div>

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

<!-- ================= ACTIONS ================= -->
<div class="col-12">
<div class="card">
<div class="card-body d-flex justify-content-between">
<a href="section-list.php" class="btn btn-light">Cancel</a>
<button type="submit" class="btn btn-warning">
    <i class="bi bi-save me-1"></i> Save Changes
</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>

<!-- ================= SUCCESS MODAL ================= -->
<div class="modal fade" id="successModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-success text-white">
<h6 class="modal-title">Success</h6>
</div>
<div class="modal-body text-center">
<i class="bi bi-check-circle fs-1 text-success"></i>
<p class="mt-3 mb-0">Section updated successfully.</p>
</div>
<div class="modal-footer justify-content-center">
<button class="btn btn-success" id="goListBtn">
Go to Sections List
</button>
</div>
</div>
</div>
</div>

<script>
const quill = new Quill('#editor', { theme: 'snow' });
quill.clipboard.dangerouslyPasteHTML(
    <?= json_encode($section['description'] ?? '') ?>
);

const successModal = new bootstrap.Modal(
    document.getElementById('successModal')
);

document.getElementById('editSectionForm')
.addEventListener('submit', async e => {
    e.preventDefault();

    document.getElementById('description').value =
        quill.root.innerHTML.trim();

    const fd = new FormData(e.target);

    const res = await fetch(
        "<?= ADMIN_BASE_URL ?>api/hospitality-product-sections/update.php",
        {
            method: 'POST',
            credentials: 'include',
            body: fd
        }
    ).then(r => r.json());

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

    successModal.show();
});

document.getElementById('goListBtn')
.addEventListener('click', () => {
    window.location.href =
        "<?= ADMIN_BASE_URL ?>hospitality-products/section-list.php";
});
</script>

</body>
</html>
