<?php

declare(strict_types=1);

function da_column_exists(PDO $db, string $table, string $column): bool {
    try {
        $st = $db->query("PRAGMA table_info($table)");
        while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
            if (($row['name'] ?? '') === $column) return true;
        }
    } catch (Throwable $e) {
    }
    return false;
}

function da_normalize_mac(?string $mac): string {
    $clean = strtoupper(substr(preg_replace('/[^A-Fa-f0-9]/', '', trim((string)$mac)), 0, 12));
    if (strlen($clean) !== 12) return '';
    return implode(':', str_split($clean, 2));
}

function da_normalize_device_type(?string $value): string {
    $raw = strtolower(trim((string)$value));
    if (in_array($raw, ['mobile', 'phone', 'celular', 'smartphone', 'android_mobile'], true)) return 'mobile';
    return 'tv';
}

function da_user_key(?string $username, ?string $password): string {
    $u = trim((string)$username);
    $p = trim((string)$password);
    if ($u === '' && $p === '') return '';
    return sha1($u . '|' . $p);
}

function da_table_exists(PDO $db, string $table): bool {
    try {
        $st = $db->prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=? LIMIT 1");
        $st->execute([$table]);
        return (bool)$st->fetch(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        return false;
    }
}

function da_ensure_schema(PDO $db): void {
    try {
        if (!da_table_exists($db, 'app_config')) {
            $db->exec("CREATE TABLE IF NOT EXISTS app_config (
                id INTEGER PRIMARY KEY,
                home_theme TEXT DEFAULT 'classic',
                purchase_key TEXT DEFAULT '',
                updated_at DATETIME,
                active_login_mode TEXT DEFAULT 'normal',
                qrcode_app_enabled INTEGER DEFAULT 1,
                renew_button_enabled INTEGER DEFAULT 1,
                test_button_enabled INTEGER DEFAULT 1,
                vencimento_modal_enabled INTEGER DEFAULT 1,
                qrcode_whatsapp TEXT DEFAULT '',
                qrcode_url TEXT DEFAULT ''
            )");
            $db->exec("INSERT OR IGNORE INTO app_config (id, home_theme, updated_at) VALUES (1, 'classic', datetime('now'))");
        }

        $appColumns = [
            'home_theme' => "TEXT DEFAULT 'classic'",
            'purchase_key' => "TEXT DEFAULT ''",
            'updated_at' => "DATETIME",
            'active_login_mode' => "TEXT DEFAULT 'normal'",
            'qrcode_app_enabled' => "INTEGER DEFAULT 1",
            'renew_button_enabled' => "INTEGER DEFAULT 1",
            'test_button_enabled' => "INTEGER DEFAULT 1",
            'vencimento_modal_enabled' => "INTEGER DEFAULT 1",
            'qrcode_whatsapp' => "TEXT DEFAULT ''",
            'qrcode_url' => "TEXT DEFAULT ''",
            'emuladores_enabled' => "INTEGER DEFAULT 1",
            'emuladores_block_message' => "TEXT DEFAULT 'Área de emuladores bloqueada pelo painel.'"
        ];
        foreach ($appColumns as $col => $def) {
            if (!da_column_exists($db, 'app_config', $col)) {
                $db->exec("ALTER TABLE app_config ADD COLUMN {$col} {$def}");
            }
        }
        $db->exec("INSERT OR IGNORE INTO app_config (id, home_theme, updated_at, qrcode_app_enabled, test_button_enabled) VALUES (1, 'classic', datetime('now'), 1, 1)");

        if (!da_table_exists($db, 'config_test')) {
            $db->exec("CREATE TABLE IF NOT EXISTS config_test (
                id INTEGER PRIMARY KEY,
                enabled INTEGER DEFAULT 1,
                api_url TEXT DEFAULT '',
                dns_nome TEXT DEFAULT '',
                provider TEXT DEFAULT 'sigma',
                api_token TEXT DEFAULT '',
                api_secret TEXT DEFAULT '',
                api_bouquet TEXT DEFAULT '',
                fastplay_adultos INTEGER DEFAULT 0,
                auto_mac_enabled INTEGER DEFAULT 0
            )");
            $db->exec("INSERT OR IGNORE INTO config_test (id, enabled, provider, auto_mac_enabled) VALUES (1, 1, 'sigma', 0)");
        }
        $testColumns = [
            'enabled' => "INTEGER DEFAULT 1",
            'api_url' => "TEXT DEFAULT ''",
            'dns_nome' => "TEXT DEFAULT ''",
            'provider' => "TEXT DEFAULT 'sigma'",
            'api_token' => "TEXT DEFAULT ''",
            'api_secret' => "TEXT DEFAULT ''",
            'api_bouquet' => "TEXT DEFAULT ''",
            'fastplay_adultos' => "INTEGER DEFAULT 0",
            'auto_mac_enabled' => "INTEGER DEFAULT 0"
        ];
        foreach ($testColumns as $col => $def) {
            if (!da_column_exists($db, 'config_test', $col)) {
                $db->exec("ALTER TABLE config_test ADD COLUMN {$col} {$def}");
            }
        }
        $db->exec("INSERT OR IGNORE INTO config_test (id, enabled, provider, auto_mac_enabled) VALUES (1, 1, 'sigma', 0)");
    } catch (Throwable $e) {
    }
}


function da_get_profile_by_key(PDO $db, string $userKey): array {
    if ($userKey === '') return da_default_profile();
    $st = $db->prepare('SELECT * FROM user_access_profiles WHERE user_key = ? LIMIT 1');
    $st->execute([$userKey]);
    $row = $st->fetch(PDO::FETCH_ASSOC) ?: [];
    return da_profile_from_row($row);
}

function da_default_profile(): array {
    return [
        'allow_tv' => true,
        'allow_mobile' => true,
        'allow_movies' => true,
        'allow_series' => true,
        'allow_live' => true,
        'allow_tab_movies' => true,
        'allow_tab_series' => true,
        'allow_tab_kids' => true,
        'allow_tab_anime' => true,
        'updated_at' => 0,
    ];
}

function da_profile_from_row(array $row): array {
    return [
        'allow_tv' => ((int)($row['allow_tv'] ?? 1) === 1),
        'allow_mobile' => ((int)($row['allow_mobile'] ?? 1) === 1),
        'allow_movies' => ((int)($row['allow_movies'] ?? 1) === 1),
        'allow_series' => ((int)($row['allow_series'] ?? 1) === 1),
        'allow_live' => ((int)($row['allow_live'] ?? 1) === 1),
        'allow_tab_movies' => ((int)($row['allow_tab_movies'] ?? ($row['allow_movies'] ?? 1)) === 1),
        'allow_tab_series' => ((int)($row['allow_tab_series'] ?? ($row['allow_series'] ?? 1)) === 1),
        'allow_tab_kids' => ((int)($row['allow_tab_kids'] ?? 1) === 1),
        'allow_tab_anime' => ((int)($row['allow_tab_anime'] ?? 1) === 1),
        'updated_at' => (int)($row['updated_at'] ?? 0),
    ];
}

function da_upsert_profile(PDO $db, string $userKey, string $username, string $password, array $profile): bool {
    if ($userKey === '') return false;
    $updatedAt = (int)($profile['updated_at'] ?? time());
    $st = $db->prepare("INSERT INTO user_access_profiles
        (user_key, username, password, allow_tv, allow_mobile, allow_movies, allow_series, allow_live, allow_tab_movies, allow_tab_series, allow_tab_kids, allow_tab_anime, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(user_key) DO UPDATE SET
            username=excluded.username,
            password=excluded.password,
            allow_tv=excluded.allow_tv,
            allow_mobile=excluded.allow_mobile,
            allow_movies=excluded.allow_movies,
            allow_series=excluded.allow_series,
            allow_live=excluded.allow_live,
            allow_tab_movies=excluded.allow_tab_movies,
            allow_tab_series=excluded.allow_tab_series,
            allow_tab_kids=excluded.allow_tab_kids,
            allow_tab_anime=excluded.allow_tab_anime,
            updated_at=excluded.updated_at");
    return $st->execute([
        $userKey,
        $username,
        $password,
        !empty($profile['allow_tv']) ? 1 : 0,
        !empty($profile['allow_mobile']) ? 1 : 0,
        !empty($profile['allow_movies']) ? 1 : 0,
        !empty($profile['allow_series']) ? 1 : 0,
        !empty($profile['allow_live']) ? 1 : 0,
        !empty($profile['allow_tab_movies']) ? 1 : 0,
        !empty($profile['allow_tab_series']) ? 1 : 0,
        !empty($profile['allow_tab_kids']) ? 1 : 0,
        !empty($profile['allow_tab_anime']) ? 1 : 0,
        $updatedAt,
    ]);
}

function da_find_user_by_mac(PDO $db, string $mac): ?array {
    $macDb = da_normalize_mac($mac);
    if ($macDb === '') return null;
    $st = $db->prepare('SELECT * FROM usuarios WHERE mac = ? LIMIT 1');
    $st->execute([$macDb]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

function da_resolve_user_key_from_mac(PDO $db, string $mac): string {
    $row = da_find_user_by_mac($db, $mac);
    if (!$row) return '';
    return da_user_key($row['username'] ?? '', $row['password'] ?? '');
}

function da_update_last_device(PDO $db, string $mac, string $deviceType): void {
    $macDb = da_normalize_mac($mac);
    if ($macDb === '') return;
    $deviceType = da_normalize_device_type($deviceType);
    try {
        $st = $db->prepare("UPDATE usuarios SET device_type = ?, last_device_type = ? WHERE mac = ?");
        $st->execute([$deviceType, $deviceType, $macDb]);
    } catch (Throwable $e) {}
}

function da_can_device_login(PDO $db, array $userRow, string $deviceType): bool {
    $deviceType = da_normalize_device_type($deviceType);
    $profile = da_get_profile_by_key($db, da_user_key($userRow['username'] ?? '', $userRow['password'] ?? ''));
    return $deviceType === 'mobile' ? !empty($profile['allow_mobile']) : !empty($profile['allow_tv']);
}
