<?php
// CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Method not allowed"]);
    exit;
}

if (!isset($_FILES['file'])) {
    http_response_code(400);
    echo json_encode(["error" => "No file uploaded"]);
    exit;
}

$file = $_FILES['file'];
$uploadDir = __DIR__ . '/uploads/';

// Ensure directory exists
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Allowed images and videos
$allowedImageTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
$allowedVideoTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-matroska', 'video/avi', 'video/3gpp'];

$type = strtolower($file['type']);
$isImage = in_array($type, $allowedImageTypes);
$isVideo = in_array($type, $allowedVideoTypes) || str_starts_with($type, 'video/');

if (!$isImage && !$isVideo) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid file type. Only images and videos (MP4, WEBM, MOV) are allowed."]);
    exit;
}

// 20MB maximum limit for video reviews
$maxBytes = 20 * 1024 * 1024;
if ($file['size'] > $maxBytes) {
    http_response_code(400);
    echo json_encode(["error" => "File is too large. Maximum allowed size is 20MB."]);
    exit;
}

// Generate unique filename
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
if (!$ext) {
    $ext = $isVideo ? 'webm' : 'jpg';
}
$prefix = $isVideo ? 'vid_' : 'img_';
$filename = uniqid($prefix) . '_' . time() . '.' . $ext;
$targetPath = $uploadDir . $filename;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    $url = '/api/uploads/' . $filename;
    echo json_encode(["success" => true, "url" => $url, "filename" => $filename]);
} else {
    http_response_code(500);
    echo json_encode(["error" => "Failed to save uploaded file on server."]);
}
?>
