<?php
declare(strict_types=1);

/**
 * ==============================
 * AUTH & BOOTSTRAP
 * ==============================
 */
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';
require_once __DIR__ . '/../../security/auth_guard_web.php';

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

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

$sectionId = (int)$data['section_id'];

$sectionTitle   = $data['section_title']   ?? null;
$previewType    = $data['preview_type']    ?? 'Both';
$filePath       = $data['file_path']       ?? null;
$thumbnailPath  = $data['thumbnail_path']  ?? null;
$altText        = $data['alt_text']        ?? null;
$caption        = $data['caption']         ?? null;
$priority       = isset($data['priority']) ? (int)$data['priority'] : 0;

$allowedPreviewType = ['Desktop', 'Mobile', 'Both'];

if (!in_array($previewType, $allowedPreviewType, true)) {
    Response::error('Invalid preview type', 422);
}

if ($filePath && !preg_match('#^[a-zA-Z0-9/_\-\.]+$#', $filePath)) {
    Response::error('Invalid file path format', 422);
}

if ($thumbnailPath && !preg_match('#^[a-zA-Z0-9/_\-\.]+$#', $thumbnailPath)) {
    Response::error('Invalid thumbnail path format', 422);
}

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

if (!$stmt->fetch()) {
    Response::error('Invalid section', 404);
}

/**
 * ==============================
 * UPDATE SECTION
 * ==============================
 */
try {

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

    $stmt->execute([
        'section_title'  => $sectionTitle,
        'preview_type'   => $previewType,
        'file_path'      => $filePath,
        'thumbnail_path' => $thumbnailPath,
        'alt_text'       => $altText,
        'caption'        => $caption,
        'priority'       => $priority,
        'updated_by'     => $_SESSION['employee_id'],
        'id'             => $sectionId
    ]);

} catch (Throwable $e) {
    Response::error('Failed to update section', 500);
}

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