<?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();
$action = $_POST['action'] ?? $_GET['action'] ?? 'list';

try {
    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        if (!media_delete($id, $tenantId)) {
            json_response(['ok' => false, 'error' => 'Not found'], 404);
        }
        json_response(['ok' => true]);
    }

    if ($action === 'tag') {
        $id = (int) ($_POST['id'] ?? 0);
        $tag = preg_replace('/[^a-z0-9_-]/i', '', (string) ($_POST['tag'] ?? 'general')) ?: 'general';
        $stmt = db()->prepare('UPDATE media_assets SET file_tag = ? WHERE id = ? AND tenant_id = ?');
        $stmt->execute([strtolower($tag), $id, $tenantId]);
        json_response(['ok' => true]);
    }

    if ($action === 'stock_search') {
        $q = (string) ($_GET['q'] ?? $_POST['q'] ?? '');
        $provider = (string) ($_GET['provider'] ?? $_POST['provider'] ?? 'pexels');
        json_response(['ok' => true] + stock_search($q, $provider));
    }

    if ($action === 'stock_save') {
        $url = (string) ($_POST['url'] ?? '');
        $tag = (string) ($_POST['tag'] ?? 'stock');
        if ($url === '') {
            json_response(['ok' => false, 'error' => 'Missing url'], 400);
        }
        $asset = stock_save_to_library($tenantId, $url, $tag);
        json_response(['ok' => true, 'asset' => $asset]);
    }

    $tag = $_GET['tag'] ?? null;
    if ($tag) {
        $stmt = db()->prepare('SELECT * FROM media_assets WHERE tenant_id = ? AND file_tag = ? ORDER BY id DESC');
        $stmt->execute([$tenantId, $tag]);
    } else {
        $stmt = db()->prepare('SELECT * FROM media_assets WHERE tenant_id = ? ORDER BY id DESC');
        $stmt->execute([$tenantId]);
    }
    $rows = $stmt->fetchAll();
    foreach ($rows as &$r) {
        $r['url'] = media_public_url($r['optimized_path'] ?: $r['file_path']);
    }
    json_response(['ok' => true, 'assets' => $rows]);
} catch (Throwable $e) {
    json_response(['ok' => false, 'error' => $e->getMessage()], 400);
}
