<?php
declare(strict_types=1);

require_once __DIR__.'/../../security/auth_guard.php';
require_once __DIR__.'/../../config/constants.php';
require_once __DIR__.'/../../config/database.php';
require_once __DIR__.'/../../core/Response.php';
require_once __DIR__.'/../../core/Validator.php';

$db = Database::getInstance();

/* ================= METHOD ================= */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Invalid request method', 405);
}

/* ================= REQUIRED ================= */
Validator::required($_POST, ['id']);

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

/* ================= FETCH EXISTING ================= */
$stmt = $db->prepare("
    SELECT file_path, thumbnail_path, file_type
    FROM hospitality_product_sections
    WHERE id = :id
");
$stmt->execute(['id' => $id]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$existing) {
    Response::error('Section not found', 404);
}

/* ================= MEDIA VALIDATION ================= */
function validateFile(array $file, string $type): void
{
    if ($file['error'] !== UPLOAD_ERR_OK) {
        Response::error('Media upload failed');
    }

    if ($file['size'] > MAX_IMAGE_SIZE * 5) {
        Response::error('File too large');
    }

    $mime = mime_content_type($file['tmp_name']);

    if ($type === 'Image' && !in_array($mime, ALLOWED_IMAGE_TYPES, true)) {
        Response::error('Invalid image type');
    }

    if ($type === 'Video' && !str_starts_with($mime, 'video/')) {
        Response::error('Invalid video type');
    }
}

/* ================= UPLOAD DIR ================= */
$uploadDir = BASE_PATH . '/uploads/hospitality/sections/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0775, true);
}

/* ================= HANDLE MEDIA ================= */
$filePath  = $existing['file_path'];
$thumbPath = $existing['thumbnail_path'];

if (!empty($_FILES['media_file']['tmp_name'])) {

    validateFile($_FILES['media_file'], $existing['file_type']);

    $ext = pathinfo($_FILES['media_file']['name'], PATHINFO_EXTENSION);
    $name = uniqid('section_', true) . '.' . $ext;

    move_uploaded_file(
        $_FILES['media_file']['tmp_name'],
        $uploadDir . $name
    );

    $filePath = BASE_URL . UPLOAD_BASE_URL . '/hospitality/sections/' . $name;

    /* Optional thumbnail logic for video */
    if ($existing['file_type'] === 'Video') {
        $thumbPath = null; // keep existing or regenerate if needed
    }
}

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

$stmt->execute([
    'id'                => $id,
    'section_title'     => $_POST['section_title'] ?? null,
    'short_description' => $_POST['short_description'] ?? null,
    'description'       => $_POST['description'] ?? null,
    'preview_type'      => $_POST['preview_type'] ?? 'Both',
    'file_path'         => $filePath,
    'thumbnail_path'    => $thumbPath,
    'alt_text'          => $_POST['alt_text'] ?? null,
    'caption'           => $_POST['caption'] ?? null,
    'priority'          => (int) ($_POST['priority'] ?? 0),
    'status'            => $_POST['status'] ?? 'Draft',
    'approval_status'   => $_POST['approval_status'] ?? 'Pending',
    'updated_by'        => $_SESSION['employee_id']
]);

Response::success('Section updated successfully');
