<?php
require_once __DIR__ . '/../config/helpers.php';
cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') json_err('Method not allowed', 405);

require_auth();

$file     = $_FILES['file'] ?? null;
$context  = $_POST['context'] ?? 'general'; // e.g. 'avatar', 'team_logo'

if (!$file || $file['error'] !== UPLOAD_ERR_OK) json_err('No file uploaded');

$allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$mime    = mime_content_type($file['tmp_name']);
if (!in_array($mime, $allowed)) json_err('Only JPEG, PNG, GIF, and WebP images are allowed');

$maxBytes = 5 * 1024 * 1024; // 5 MB
if ($file['size'] > $maxBytes) json_err('File exceeds 5 MB limit');

$ext      = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uuid() . '.' . strtolower($ext);
$uploadDir= __DIR__ . '/../../uploads/' . $context . '/';

if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

$dest = $uploadDir . $filename;
if (!move_uploaded_file($file['tmp_name'], $dest)) json_err('Upload failed', 500);

// Build public URL — adjust the base URL to match your Hostinger domain.
$baseUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
$url     = $baseUrl . '/uploads/' . $context . '/' . $filename;

json_ok(['url' => $url]);
