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

$response = ["status" => "error", "message" => ""];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response["message"] = "Only POST requests are allowed.";
    echo json_encode($response);
    exit;
}

// Ensure a file is uploaded
if (!isset($_FILES['file'])) {
    $response["message"] = "No file uploaded.";
    echo json_encode($response);
    exit;
}

$file = $_FILES['file'];
$filename = basename($file['name']);
$filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$filesize = $file['size'];
$tempPath = $file['tmp_name'];

// Allowed file types
$imageExtensions = ["jpg", "jpeg", "png", "gif", "webp"];
$videoExtensions = ["mp4", "avi", "mov", "mkv", "flv"];
$maxSize = 20 * 1024 * 1024; // 50MB max file size

// Determine storage path
if (in_array($filetype, $imageExtensions)) {
    $uploadFolder = "uploads/images/";
} elseif (in_array($filetype, $videoExtensions)) {
    $uploadFolder = "uploads/videos/";
} else {
    $response["message"] = "Invalid file type. Only images and videos are allowed.";
    echo json_encode($response);
    exit;
}

// Validate file size
if ($filesize > $maxSize) {
    $response["message"] = "File is too large. Max size is 20MB.";
    echo json_encode($response);
    exit;
}

// Validate MIME type for security
$mimeType = mime_content_type($tempPath);
$allowedMimeTypes = ["image/jpeg", "image/png", "image/gif", "image/webp", "video/mp4", "video/avi", "video/quicktime", "video/x-matroska", "video/x-flv"];

if (!in_array($mimeType, $allowedMimeTypes)) {
    $response["message"] = "Invalid file type detected.";
    echo json_encode($response);
    exit;
}

// Ensure the folder exists
if (!file_exists($uploadFolder)) {
    mkdir($uploadFolder, 0777, true);
}

// Generate a unique filename
$newFilename = uniqid() . "_" . time() . "." . $filetype;
$uploadPath = $uploadFolder . $newFilename;

// Move the file
if (move_uploaded_file($tempPath, $uploadPath)) {
    $baseURL = "https://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
    $response["status"] = "success";
    $response["message"] = "File uploaded successfully.";
    $response["file_url"] = $baseURL . $uploadPath;
} else {
    $response["message"] = "Failed to upload file.";
}

echo json_encode($response);
?>