<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/media.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
if (empty($_SESSION['admin_logged_in'])) {
    json_response(['ok' => false, 'error' => 'Unauthorized'], 401);
}

$tenantId = current_tenant_id();

try {
    $tag = preg_replace('/[^a-z0-9_-]/i', '', (string) ($_POST['tag'] ?? 'general')) ?: 'general';
    $crop = null;
    if (isset($_POST['crop_w'], $_POST['crop_h'])) {
        $crop = [
            'x' => (float) ($_POST['crop_x'] ?? 0),
            'y' => (float) ($_POST['crop_y'] ?? 0),
            'width' => (float) $_POST['crop_w'],
            'height' => (float) $_POST['crop_h'],
        ];
    }
    if (empty($_FILES['file'])) {
        json_response(['ok' => false, 'error' => 'No file uploaded'], 400);
    }
    $asset = media_process_upload($_FILES['file'], $tenantId, strtolower($tag), $crop);
    json_response(['ok' => true, 'asset' => $asset]);
} catch (Throwable $e) {
    json_response(['ok' => false, 'error' => $e->getMessage()], 400);
}
