<?php
$config = require __DIR__ . '/../config.php';

function db(): PDO
{
    static $pdo = null;
    global $config;

    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $db = $config['db'];
    $dsn = 'mysql:host=' . $db['host'] . ';dbname=' . $db['name'] . ';charset=' . $db['charset'];
    $pdo = new PDO($dsn, $db['user'], $db['pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    return $pdo;
}

function json_response(array $data, int $status = 200): void
{
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function handle_cors_preflight(): void
{
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        json_response(['ok' => true]);
    }
}

function input_json(): array
{
    $raw = file_get_contents('php://input');
    $data = json_decode($raw ?: '', true);

    if (is_array($data)) {
        return $data;
    }

    return $_POST;
}

function normalize_mac(string $mac): string
{
    return strtoupper(trim($mac));
}

function get_or_create_device(string $mac): array
{
    global $config;
    $pdo = db();
    $mac = normalize_mac($mac);

    if ($mac === '') {
        json_response(['ok' => false, 'error' => 'MAC is required'], 422);
    }

    $stmt = $pdo->prepare('SELECT * FROM devices WHERE mac = ? LIMIT 1');
    $stmt->execute([$mac]);
    $device = $stmt->fetch();

    if ($device) {
        $pdo->prepare('UPDATE devices SET last_seen_at = NOW() WHERE id = ?')->execute([$device['id']]);
        return $device;
    }

    $trialDays = (int) $config['app']['trial_days'];
    $pdo->prepare('INSERT INTO devices (mac, trial_started_at, trial_ends_at, last_seen_at) VALUES (?, NOW(), DATE_ADD(NOW(), INTERVAL ? DAY), NOW())')
        ->execute([$mac, $trialDays]);

    $stmt = $pdo->prepare('SELECT * FROM devices WHERE id = ? LIMIT 1');
    $stmt->execute([$pdo->lastInsertId()]);
    return $stmt->fetch();
}

function device_access(array $device): array
{
    $now = new DateTimeImmutable('now');
    $trialEnds = new DateTimeImmutable($device['trial_ends_at']);
    $activeUntil = $device['active_until'] ? new DateTimeImmutable($device['active_until']) : null;

    if (($device['status'] ?? '') === 'disabled') {
        return ['allowed' => false, 'reason' => 'disabled'];
    }

    if ($activeUntil && $activeUntil >= $now) {
        return ['allowed' => true, 'reason' => 'paid'];
    }

    if ($trialEnds >= $now) {
        return ['allowed' => true, 'reason' => 'trial'];
    }

    return ['allowed' => false, 'reason' => 'expired'];
}

function get_device_playlist(int $deviceId): ?array
{
    $stmt = db()->prepare('SELECT * FROM playlists WHERE device_id = ? AND enabled = 1 ORDER BY id ASC LIMIT 1');
    $stmt->execute([$deviceId]);
    $playlist = $stmt->fetch();

    return $playlist ?: null;
}

function get_device_playlists(int $deviceId): array
{
    $stmt = db()->prepare('SELECT * FROM playlists WHERE device_id = ? ORDER BY enabled DESC, id ASC');
    $stmt->execute([$deviceId]);

    return $stmt->fetchAll();
}

function generated_playlist_url(?array $playlist): string
{
    if (!$playlist) {
        return '';
    }

    if ($playlist['playlist_type'] === 'm3u') {
        return (string) $playlist['playlist_url'];
    }

    $serverUrl = rtrim((string) $playlist['server_url'], '/');
    return $serverUrl . '/get.php?username=' . rawurlencode((string) $playlist['username']) .
        '&password=' . rawurlencode((string) $playlist['password']) .
        '&type=m3u_plus&output=' . rawurlencode((string) $playlist['output_format']);
}

function public_playlist_payload(?array $playlist): ?array
{
    if (!$playlist) {
        return null;
    }

    return [
        'id' => (string) $playlist['id'],
        'name' => $playlist['playlist_name'] ?? 'Main IPTV',
        'type' => $playlist['playlist_type'],
        'playlist_url' => $playlist['playlist_url'],
        'server_url' => $playlist['server_url'],
        'username' => $playlist['username'],
        'password' => $playlist['password'],
        'output' => $playlist['output_format'],
        'enabled' => (bool) ($playlist['enabled'] ?? true),
        'generated_url' => generated_playlist_url($playlist),
        'updated_at' => $playlist['updated_at'],
    ];
}

function public_playlists_payload(array $playlists): array
{
    return array_values(array_filter(array_map('public_playlist_payload', $playlists)));
}

function absolute_url(string $path): string
{
    global $config;
    return rtrim($config['app']['site_url'], '/') . '/' . ltrim($path, '/');
}
