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

$method = $_SERVER['REQUEST_METHOD'];
$db     = db();

if ($method === 'GET') {
    $links      = $db->query('SELECT * FROM media_links ORDER BY sort_order')->fetchAll();
    $highlights = $db->query('SELECT * FROM highlights ORDER BY sort_order DESC')->fetchAll();
    json_ok(['links' => $links, 'highlights' => $highlights]);
}

if ($method === 'POST') {
    require_admin();
    $b    = body();
    $type = $b['type'] ?? '';

    if ($type === 'link') {
        $id = uuid();
        $db->prepare(
            'INSERT INTO media_links (id, platform, handle, url, display_name, sort_order)
             VALUES (?, ?, ?, ?, ?, ?)'
        )->execute([
            $id, $b['platform'] ?? '', $b['handle'] ?? '',
            $b['url'] ?? '', $b['display_name'] ?? '', (int)($b['sort_order'] ?? 0),
        ]);
        json_ok(['id' => $id], 201);
    }

    if ($type === 'highlight') {
        $id = uuid();
        $db->prepare(
            'INSERT INTO highlights (id, title, description, youtube_url, thumbnail_url, published_at, sort_order)
             VALUES (?, ?, ?, ?, ?, ?, ?)'
        )->execute([
            $id, $b['title'] ?? '', $b['description'] ?? '',
            $b['youtube_url'] ?? '', $b['thumbnail_url'] ?? null,
            $b['published_at'] ?? null, (int)($b['sort_order'] ?? 0),
        ]);
        json_ok(['id' => $id], 201);
    }

    json_err('type must be link or highlight');
}

json_err('Method not allowed', 405);
