<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

$mac = drak_normalize_mac((string)($_GET['mac'] ?? $_GET['code'] ?? ''));
if ($mac === '') {
    drak_json(['success' => false, 'message' => 'Invalid MAC address'], 400);
}

try {
    $pdo = drak_pdo();
    $payload = drak_auth_payload($pdo, $mac);
    $device = $payload['device'];
    $playlists = $payload['playlists'];

    if (!drak_device_active($device)) {
        drak_json([
            'success' => false,
            'message' => 'Device inactive',
            'mac' => $mac,
            'status' => $device['status'] ?? '',
            'expire_date' => $device['expires_at'] ?? '',
        ]);
    }

    if (count($playlists) === 0) {
        drak_json([
            'success' => false,
            'message' => 'No playlist found for this MAC',
            'mac' => $mac,
            'status' => $device['status'] ?? '',
            'expire_date' => $device['expires_at'] ?? '',
        ]);
    }

    $first = $playlists[0];
    drak_json([
        'success' => true,
        'mac' => $mac,
        'status' => $device['status'] ?? '',
        'playlist_name' => (string)$first['name'],
        'playlist_url' => (string)$first['playlist_url'],
        'epg_url' => (string)($first['epg_url'] ?? ''),
        'expire_date' => (string)($device['expires_at'] ?? ''),
        'playlists' => $playlists,
        'recent_added' => [],
    ]);
} catch (Throwable $error) {
    drak_json(['success' => false, 'message' => 'Database connection failed'], 500);
}
