<?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_ensure_schema(PDO $db): void {
    return;
}


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']);
}
