<?php
declare(strict_types=1);

/* ================= AUTH ================= */
require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';

$db = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

/* ================= VALIDATION ================= */
Validator::required($data, ['id', 'status']);

$id = (int) $data['id'];

/* ================= CHECK EXISTS ================= */
$stmt = $db->prepare("
    SELECT id FROM retail_product_sections WHERE id = :id
");
$stmt->execute(['id' => $id]);

if (!$stmt->fetch()) {
    Response::error('Section not found', 404);
}

/* ================= SANITIZE ================= */
$allowedStatus = ['Draft', 'Active', 'InActive'];
if (!in_array($data['status'], $allowedStatus, true)) {
    Response::error('Invalid status value', 422);
}

/* ================= UPDATE ================= */
$stmt = $db->prepare("
    UPDATE retail_product_sections SET
        section_title  = :section_title,
        file_path      = :file_path,
        thumbnail_path = :thumbnail_path,
        alt_text       = :alt_text,
        caption        = :caption,
        preview_type   = :preview_type,
        priority       = :priority,
        is_lazy_load   = :is_lazy_load,
        status         = :status,
        updated_by     = :updated_by,
        updated_at     = NOW()
    WHERE id = :id
");

$stmt->execute([
    'id'             => $id,
    'section_title'  => $data['section_title'] ?? null,
    'file_path'      => $data['file_path'] ?? null,
    'thumbnail_path' => $data['thumbnail_path'] ?? null,
    'alt_text'       => $data['alt_text'] ?? null,
    'caption'        => $data['caption'] ?? null,
    'preview_type'   => $data['preview_type'] ?? 'Both',
    'priority'       => isset($data['priority']) ? (int)$data['priority'] : 0,
    'is_lazy_load'   => isset($data['is_lazy_load']) ? (int)$data['is_lazy_load'] : 1,
    'status'         => $data['status'],              // ✅ FIXED
    'updated_by'     => (int) $_SESSION['employee_id']
]);

/* ================= RESPONSE ================= */
Response::success('Section updated successfully');
