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

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

$db = Database::getInstance();
$stmt = $db->prepare("
    SELECT *
    FROM offers
    WHERE id = :id AND deleted_at IS NULL
");
$stmt->execute(['id' => $id]);
$offer = $stmt->fetch();

if (!$offer) {
    header('Location: index.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Edit Offer']); ?>
<?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 Offer'
]); ?>

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

<input type="hidden" name="id" value="<?= (int) $offer['id'] ?>">

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

<div class="row g-3">

<div class="col-md-6">
    <label class="form-label">Title *</label>
    <input type="text" name="title" class="form-control"
           value="<?= htmlspecialchars($offer['title']) ?>" required>
</div>

<div class="col-md-6">
    <label class="form-label">Offer Price *</label>
    <input type="number" step="0.01" name="offer_price"
           value="<?= $offer['offer_price'] ?>" class="form-control" required>
</div>

<div class="col-md-12">
    <label class="form-label">Short Description *</label>
    <input type="text" name="short_description" class="form-control"
           value="<?= htmlspecialchars($offer['short_description']) ?>" required>
</div>

<div class="col-md-12">
    <label class="form-label">Description *</label>
    <textarea name="description" class="form-control"
              rows="4" required><?= htmlspecialchars($offer['description']) ?></textarea>
</div>

<div class="col-md-6">
    <label class="form-label">Start Date *</label>
    <input type="datetime-local" name="start_date"
           value="<?= date('Y-m-d\TH:i', strtotime($offer['start_date'])) ?>"
           class="form-control" required>
</div>

<div class="col-md-6">
    <label class="form-label">End Date *</label>
    <input type="datetime-local" name="end_date"
           value="<?= date('Y-m-d\TH:i', strtotime($offer['end_date'])) ?>"
           class="form-control" required>
</div>

<div class="col-md-12">
    <label class="form-label">Redirect URL *</label>
    <input type="text" name="redirect_url"
           value="<?= htmlspecialchars($offer['redirect_url']) ?>"
           class="form-control" required>
</div>

<div class="col-md-6">
    <label class="form-label">Desktop Image</label><br>
    <img src="<?= $offer['desktop_image'] ?>" width="120" class="rounded mb-2"><br>
    <input type="file" name="desktop_image" class="form-control" accept="image/*">
    <small class="text-muted">Leave empty to keep existing</small>
</div>

<div class="col-md-6">
    <label class="form-label">Mobile Image</label><br>
    <img src="<?= $offer['mobile_image'] ?>" width="80" class="rounded mb-2"><br>
    <input type="file" name="mobile_image" class="form-control" accept="image/*">
    <small class="text-muted">Leave empty to keep existing</small>
</div>

<div class="col-md-4">
    <label class="form-label">Status *</label>
    <select name="status" class="form-select" required>
        <option value="active"   <?= $offer['status'] === 'active' ? 'selected' : '' ?>>Active</option>
        <option value="inactive" <?= $offer['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
    </select>
</div>

</div>

</div>

<div class="card-footer text-end">
    <a href="<?= ADMIN_BASE_URL ?>offers/list.php"
       class="btn btn-light me-2">Cancel</a>
    <button type="submit" class="btn btn-warning">
        <i class="bi bi-pencil-square me-1"></i> Update Offer
    </button>
</div>
</div>

</form>

</div>
</main>

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

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

<script>
const API_UPDATE = "<?= ADMIN_BASE_URL ?>api/offers/update.php";

document.getElementById('offerForm').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') {
            window.location.href = "<?= ADMIN_BASE_URL ?>offers/list.php";
        } else {
            alert(res.message || 'Failed to update offer');
        }
    })
    .catch(() => alert('Something went wrong'));
});
</script>

</body>
</html>
