<?php
/**
 * Playlist API
 * Endpoint: /api/playlist.php
 * 
 * Zwraca zaszyfrowane playlisty i ustawienia dla urządzenia na podstawie MAC i CODE
 */

// Mierz czas odpowiedzi
$startTime = microtime(true);

// Załaduj konfigurację i klasy
require_once dirname(__DIR__) . '/panel/config/config.php';
require_once PANEL_PATH . '/classes/Database.php';
require_once PANEL_PATH . '/classes/Logger.php';
require_once PANEL_PATH . '/classes/Playlist.php';
require_once PANEL_PATH . '/classes/Device.php';
require_once PANEL_PATH . '/classes/Setting.php';

// Ustaw nagłówki
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('X-Content-Type-Options: nosniff');

// Pobierz parametry
$mac = isset($_GET['mac']) ? strtoupper(trim($_GET['mac'])) : null;
$code = isset($_GET['code']) ? trim($_GET['code']) : null;

// Logger
$logger = new Logger();

// Walidacja parametrów
if (empty($mac) || empty($code)) {
    $responseTime = (int)((microtime(true) - $startTime) * 1000);
    $logger->logApi(null, $mac, $code, '/api/playlist', 'GET', 400, 0, $responseTime);
    $logger->logToFile('api.log', "Invalid params - MAC: {$mac}, CODE: {$code}");
    
    outputEncrypted(['error' => 'Missing MAC or CODE parameter']);
    exit;
}

// Formatuj MAC (dodaj dwukropki jeśli brak)
$mac = formatMac($mac);

// Pobierz playlisty z bazy
$playlistModel = new Playlist();
$result = $playlistModel->getForApi($mac, $code);

if ($result === null) {
    // Urządzenie nie istnieje
    $responseTime = (int)((microtime(true) - $startTime) * 1000);
    $logger->logApi(null, $mac, $code, '/api/playlist', 'GET', 404, 0, $responseTime);
    $logger->logToFile('api.log', "Device not found - MAC: {$mac}, CODE: {$code}");
    
    outputEncrypted(['error' => 'Device not found', 'playlists' => []]);
    exit;
}

if ($result['blocked']) {
    // Urządzenie lub użytkownik zablokowany
    $responseTime = (int)((microtime(true) - $startTime) * 1000);
    $logger->logApi($result['device_id'] ?? null, $mac, $code, '/api/playlist', 'GET', 403, 0, $responseTime);
    $logger->logToFile('api.log', "Device blocked - MAC: {$mac}, CODE: {$code}");
    
    outputEncrypted(['error' => 'Device is blocked', 'playlists' => []]);
    exit;
}

// Pobierz ustawienia dla urządzenia
$settingModel = new Setting();
$settings = $settingModel->getForDevice($result['device_id']);

// Sukces - zwróć playlisty i ustawienia
$playlistsCount = count($result['playlists']);
$responseTime = (int)((microtime(true) - $startTime) * 1000);
$logger->logApi($result['device_id'], $mac, $code, '/api/playlist', 'GET', 200, $playlistsCount, $responseTime);
$logger->logToFile('api.log', "Success - MAC: {$mac}, CODE: {$code}, Playlists: {$playlistsCount}, Time: {$responseTime}ms");

outputEncrypted([
    'playlists' => $result['playlists'],
    'settings' => [
        'timestamp' => $settings['timestamp'],
        'values' => $settings['values']
    ]
]);

/**
 * Szyfruj i wyślij odpowiedź
 */
function outputEncrypted(array $data): void
{
    $key = API_ENCRYPTION_KEY;
    
    $json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    
    // XOR encryption
    $keyLen = strlen($key);
    $encrypted = '';
    for ($i = 0; $i < strlen($json); $i++) {
        $encrypted .= chr(ord($json[$i]) ^ ord($key[$i % $keyLen]));
    }
    
    // Base64 encode
    echo base64_encode($encrypted);
}

/**
 * Formatuj adres MAC
 */
function formatMac(string $mac): string
{
    // Usuń wszystkie separatory
    $mac = strtoupper(preg_replace('/[^A-F0-9]/', '', $mac));
    
    // Dodaj dwukropki jeśli mamy 12 znaków
    if (strlen($mac) === 12) {
        return implode(':', str_split($mac, 2));
    }
    
    return $mac;
}
