<?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);
}

Validator::required($_POST, ['id','title']);

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

/* ================= FETCH EXISTING ================= */
$stmt = $db->prepare("
    SELECT cover_image, banner_image_desktop, banner_image_mobile
    FROM hospitality_products
    WHERE id = :id
");
$stmt->execute(['id'=>$id]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);

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

/* ================= IMAGE VALIDATOR ================= */
function validateImage(array $file): void {
    if ($file['error'] !== UPLOAD_ERR_OK) {
        Response::error('Image upload failed');
    }
    if ($file['size'] > MAX_IMAGE_SIZE) {
        Response::error('Image too large');
    }
    $mime = mime_content_type($file['tmp_name']);
    if (!in_array($mime, ALLOWED_IMAGE_TYPES, true)) {
        Response::error('Invalid image type');
    }
}

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

/* ================= HANDLE IMAGES ================= */
$coverImage  = $existing['cover_image'];
$desktopImg  = $existing['banner_image_desktop'];
$mobileImg   = $existing['banner_image_mobile'];

if (!empty($_FILES['cover_image']['tmp_name'])) {
    validateImage($_FILES['cover_image']);
    $f = 'cover_' . uniqid() . '.webp';
    move_uploaded_file($_FILES['cover_image']['tmp_name'], $uploadDir.$f);
    $coverImage = BASE_URL . UPLOAD_BASE_URL . '/hospitality-products/'.$f;
}

if (!empty($_FILES['banner_desktop']['tmp_name'])) {
    validateImage($_FILES['banner_desktop']);
    $f = 'desktop_' . uniqid() . '.webp';
    move_uploaded_file($_FILES['banner_desktop']['tmp_name'], $uploadDir.$f);
    $desktopImg = BASE_URL . UPLOAD_BASE_URL . '/hospitality-products/'.$f;
}

if (!empty($_FILES['banner_mobile']['tmp_name'])) {
    validateImage($_FILES['banner_mobile']);
    $f = 'mobile_' . uniqid() . '.webp';
    move_uploaded_file($_FILES['banner_mobile']['tmp_name'], $uploadDir.$f);
    $mobileImg = BASE_URL . UPLOAD_BASE_URL . '/hospitality-products/'.$f;
}

/* ================= UPDATE ================= */
$stmt = $db->prepare("
    UPDATE hospitality_products SET
        title              = :title,
        short_description  = :short_description,
        description        = :description,
        product_type       = :product_type,
        usage_category     = :usage_category,

        meta_title         = :meta_title,
        meta_description   = :meta_description,
        canonical_url      = :canonical_url,
        schema_json        = :schema_json,

        cover_image        = :cover_image,
        banner_image_desktop = :desktop_image,
        banner_image_mobile  = :mobile_image,

        status             = :status,
        approval_status    = :approval_status,
        priority           = :priority,
        updated_by         = :updated_by,
        updated_at         = NOW()
    WHERE id = :id
");

$stmt->execute([
    'id'               => $id,
    'title'            => trim($_POST['title']),
    'short_description'=> $_POST['short_description'] ?? null,
    'description'      => $_POST['description'] ?? null,
    'product_type'     => $_POST['product_type'] ?? 'Hotel',
    'usage_category'   => $_POST['usage_category'] ?? null,

    'meta_title'       => $_POST['meta_title'] ?? null,
    'meta_description' => $_POST['meta_description'] ?? null,
    'canonical_url'    => $_POST['canonical_url'] ?? null,
    'schema_json'      => $_POST['schema_json'] ?? null,

    'cover_image'      => $coverImage,
    'desktop_image'    => $desktopImg,
    'mobile_image'     => $mobileImg,

    'status'           => $_POST['status'] ?? 'Draft',
    'approval_status'  => $_POST['approval_status'] ?? 'Pending',
    'priority'         => (int)($_POST['priority'] ?? 0),
    'updated_by'       => $_SESSION['employee_id']
]);

Response::success('Hospitality product updated successfully');
