<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

$pdo = drak_pdo();
$body = drak_body();
$action = (string)($_GET['action'] ?? $body['action'] ?? 'authenticate');
$mac = drak_normalize_mac((string)($_GET['mac'] ?? $body['mac'] ?? ''));
$deviceId = trim((string)($_GET['device_id'] ?? $_GET['deviceId'] ?? $body['device_id'] ?? $body['deviceId'] ?? ''));

try {
    if ($mac === '') {
        drak_json(['ok' => false, 'error' => 'invalid_mac'], 400);
    }

    if ($action === 'authenticate' || $action === 'register') {
        drak_json(drak_auth_payload($pdo, $mac, $deviceId ?: null, (string)($body['user_agent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? '')));
    }

    if ($action === 'add_playlist') {
        $payload = drak_auth_payload($pdo, $mac, $deviceId ?: null, (string)($body['user_agent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? ''));
        $device = $payload['device'];
        if (!drak_device_active($device)) {
            drak_json(['ok' => false, 'error' => 'device_inactive']);
        }

        $name = trim((string)($body['name'] ?? ''));
        $url = trim((string)($body['playlist_url'] ?? $body['url'] ?? ''));
        $epg = trim((string)($body['epg_url'] ?? $body['epg'] ?? ''));
        $protected = !empty($body['is_protected']) ? 1 : 0;
        if ($name === '' || $url === '' || !preg_match('/^https?:\/\//i', $url)) {
            drak_json(['ok' => false, 'error' => 'invalid_url']);
        }

        $id = drak_uuid();
        $stmt = $pdo->prepare("
            INSERT INTO niceflix_playlists
                (id, device_id, name, playlist_url, epg_url, is_protected, source, created_at, updated_at)
            VALUES
                (:id, :device_id, :name, :playlist_url, NULLIF(:epg_url, ''), :is_protected, 'client', NOW(6), NOW(6))
        ");
        $stmt->execute([
            'id' => $id,
            'device_id' => $device['id'],
            'name' => $name,
            'playlist_url' => $url,
            'epg_url' => $epg,
            'is_protected' => $protected,
        ]);
        drak_json(['ok' => true, 'id' => $id]);
    }

    if ($action === 'delete_playlist') {
        $payload = drak_auth_payload($pdo, $mac, $deviceId ?: null);
        $playlistId = trim((string)($body['playlist_id'] ?? $body['id'] ?? ''));
        if ($playlistId === '') {
            drak_json(['ok' => false, 'error' => 'missing_playlist_id']);
        }
        $stmt = $pdo->prepare("
            DELETE FROM niceflix_playlists
            WHERE id = :playlist_id AND device_id = :device_id
        ");
        $stmt->execute([
            'playlist_id' => $playlistId,
            'device_id' => $payload['device']['id'],
        ]);
        drak_json(['ok' => true]);
    }

    drak_json(['ok' => false, 'error' => 'unknown_action'], 404);
} catch (Throwable $error) {
    drak_json(['ok' => false, 'error' => 'server_error'], 500);
}
