<?php
declare(strict_types=1);

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

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

if (empty($_FILES['file']['tmp_name'])) {
    Response::error('File is required', 422);
}

$fileType = $_POST['file_type'] ?? 'Image';

/* ================= VALIDATE ================= */
$mime = mime_content_type($_FILES['file']['tmp_name']);

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

if ($fileType === 'Video' && !in_array($mime, ALLOWED_VIDEO_TYPES, true)) {
    Response::error('Invalid video type', 422);
}

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

/* ================= SAVE FILE ================= */
$ext  = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$name = uniqid('section_', true) . '.' . $ext;

if (!move_uploaded_file($_FILES['file']['tmp_name'], $baseDir . $name)) {
    Response::error('Failed to save file', 500);
}

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

/* ================= RESPONSE ================= */
Response::success('Upload successful', [
    'file_path' => $filePath,
    'thumbnail_path' => null
]);
