<?php
require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
require_once dirname(__DIR__) . '/_auth_common.php';
require_once dirname(__DIR__) . '/_trial_service.php';

try {
    $db = new PDO('sqlite:' . dirname(__DIR__) . '/db.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Throwable $e) {
    auth_json_out(['status' => 'erro', 'message' => 'db_connection_error']);
}

auth_ensure_schema($db);

$action = strtolower(trim((string)($_REQUEST['action'] ?? '')));
$loginType = strtolower(trim((string)($_POST['login_type'] ?? $_GET['login_type'] ?? 'normal')));
$mac = auth_normalize_mac((string)($_POST['mac'] ?? $_GET['mac'] ?? ''));
$dnsSelected = auth_normalize_dns((string)($_POST['dns_selected'] ?? $_GET['dns_selected'] ?? ''));
$deviceType = da_normalize_device_type((string)($_POST['device_type'] ?? $_GET['device_type'] ?? 'tv'));
$activeMode = auth_get_active_login_mode($db);
$testCfg = auth_get_test_config($db);
$appFlags = auth_get_app_flags($db);
$dnsList = auth_get_dns_list($db);

if ($dnsSelected !== '' && !in_array($dnsSelected, $dnsList, true)) {
    array_unshift($dnsList, $dnsSelected);
}

if ($action === 'config') {
    $user = null;
    $macRegistered = false;
    $macPending = false;
    $macHasCredentials = false;
    $macMessage = 'MAC ainda não cadastrado no painel.';

    if ($mac !== '') {
        $stCfgMac = $db->prepare('SELECT * FROM usuarios WHERE mac = ? LIMIT 1');
        $stCfgMac->execute([$mac]);
        $user = $stCfgMac->fetch(PDO::FETCH_ASSOC) ?: null;
        if ($user) {
            $macRegistered = true;
            $macHasCredentials = auth_user_has_credentials($user);
            $macPending = !$macHasCredentials;
            if ($macHasCredentials) {
                $macMessage = 'MAC já cadastrado e pronto para uso.';
            } else {
                $macMessage = 'MAC cadastrado. Aguarde ativação.';
            }
            $user['device_type'] = da_normalize_device_type((string)($user['device_type'] ?? $user['last_device_type'] ?? 'tv'));
            $user['access_profile'] = da_get_profile_by_key($db, da_user_key($user['username'] ?? '', $user['password'] ?? ''));
        } else {
            $macMessage = 'MAC ainda não cadastrado no painel.';
        }
    }

    auth_json_out([
        'status' => 'ok',
        'active_login_mode' => $activeMode,
        'auto_mac_enabled' => (int)($testCfg['auto_mac_enabled'] ?? 0),
        'test_enabled' => (int)($testCfg['enabled'] ?? 0),
        'can_auto_trial' => ($activeMode === 'mac' && (int)($testCfg['auto_mac_enabled'] ?? 0) === 1 && (int)($testCfg['enabled'] ?? 0) === 1),
        'test_button_enabled' => (int)($appFlags['test_button_enabled'] ?? 1),
        'qrcode_app_enabled' => (int)($appFlags['qrcode_app_enabled'] ?? 1),
        'renew_button_enabled' => (int)($appFlags['renew_button_enabled'] ?? 1),
        'vencimento_modal_enabled' => (int)($appFlags['vencimento_modal_enabled'] ?? 1),
        'mac' => $mac,
        'mac_registered' => $macRegistered,
        'mac_pending' => $macPending,
        'mac_has_credentials' => $macHasCredentials,
        'mac_message' => $macMessage,
        'user' => $user,
    ]);
}

if (!in_array($loginType, ['normal', 'mac', 'activation_code'], true)) {
    $loginType = 'normal';
}

function auth_invalid_or_expired_out(array $validation): void {
    if (!empty($validation['expired'])) {
        auth_json_out(['status' => 'expired', 'logout' => false, 'message' => 'Conta vencida.']);
    }
    auth_json_out(['status' => 'invalid', 'logout' => false, 'message' => 'Usuário, senha ou DNS inválidos.']);
}

if ($loginType === 'normal') {
    $username = trim((string)($_POST['username'] ?? ''));
    $password = trim((string)($_POST['password'] ?? ''));
    if ($username === '' || $password === '' || $mac === '') {
        auth_json_out(['status' => 'invalid', 'logout' => false, 'message' => 'missing_credentials']);
    }
    if (empty($dnsList)) {
        auth_json_out(['status' => 'invalid', 'logout' => false, 'message' => 'dns_empty']);
    }

    $validated = auth_validate_dns_credentials($dnsList, $username, $password, $dnsSelected);
    if (empty($validated['ok'])) {
        auth_invalid_or_expired_out($validated);
    }

    $vencimento = (int)($validated['exp'] ?? 0);
    $dnsFinal = auth_normalize_dns((string)($validated['dns'] ?? ''));
    if ($dnsFinal === '') {
        auth_json_out(['status' => 'invalid', 'logout' => false, 'message' => 'dns_invalid']);
    }

    $check = $db->prepare('SELECT * FROM usuarios WHERE mac = ? LIMIT 1');
    $check->execute([$mac]);
    $existing = $check->fetch(PDO::FETCH_ASSOC);

    if ($existing && !da_can_device_login($db, $existing, $deviceType)) {
        auth_json_out(['status' => 'forbidden', 'logout' => false, 'message' => 'Este tipo de dispositivo está bloqueado.']);
    }

    $vencimentoSave = $vencimento > 0 ? (string)$vencimento : '';
    if ($existing) {
        $up = $db->prepare("UPDATE usuarios SET dns = ?, username = ?, password = ?, vencimento = ?, status = 'ativo', login_mode = COALESCE(NULLIF(login_mode,''), 'normal'), device_type = ?, last_device_type = ? WHERE mac = ?");
        $up->execute([$dnsFinal, $username, $password, $vencimentoSave, $deviceType, $deviceType, $mac]);
        $existing['dns'] = $dnsFinal;
        $existing['username'] = $username;
        $existing['password'] = $password;
        $existing['vencimento'] = $vencimentoSave;
        $existing['status'] = 'ativo';
        $existing['device_type'] = $deviceType;
        $existing['last_device_type'] = $deviceType;
        $userRow = $existing;
    } else {
        $newActivationCode = auth_generate_activation_code($db);
        $ins = $db->prepare("INSERT INTO usuarios (mac,dns,username,password,vencimento,status,login_mode,device_type,last_device_type,activation_code,nome_cliente,whatsapp,teste,usuario_id) VALUES (?,?,?,?,?,'ativo','normal',?,?,?,'','',0,0)");
        $ins->execute([$mac, $dnsFinal, $username, $password, $vencimentoSave, $deviceType, $deviceType, $newActivationCode]);
        $userRow = [
            'mac' => $mac,
            'dns' => $dnsFinal,
            'username' => $username,
            'password' => $password,
            'vencimento' => $vencimentoSave,
            'status' => 'ativo',
            'nome_cliente' => '',
            'whatsapp' => '',
            'login_mode' => 'normal',
            'activation_code' => $newActivationCode,
            'device_type' => $deviceType,
            'last_device_type' => $deviceType,
        ];
    }

    auth_json_out(auth_build_success_payload($db, $userRow, $dnsList, $dnsFinal, ['active_login_mode' => $activeMode]));
}

if ($mac === '') {
    auth_json_out(['status' => 'invalid', 'logout' => false, 'message' => 'mac_required']);
}

if ($loginType === 'mac') {
    $st = $db->prepare('SELECT * FROM usuarios WHERE mac = ? LIMIT 1');
    $st->execute([$mac]);
    $userRow = $st->fetch(PDO::FETCH_ASSOC) ?: null;

    if (!$userRow) {
        $autoMacEnabled = $activeMode === 'mac' && (int)($testCfg['auto_mac_enabled'] ?? 0) === 1 && (int)($testCfg['enabled'] ?? 0) === 1;
        if ($autoMacEnabled) {
            $trial = gerar_teste_service($db, $mac, $testCfg, [
                'nome' => 'Cliente MAC ' . strtoupper(substr(str_replace(':', '', $mac), -4)),
                'whatsapp' => '',
                'device_type' => $deviceType,
            ]);
            if (($trial['status'] ?? '') === 'success') {
                $st->execute([$mac]);
                $userRow = $st->fetch(PDO::FETCH_ASSOC) ?: null;
            } else {
                auth_ensure_pending_mac($db, $mac, $deviceType);
                auth_json_out([
                    'status' => 'waiting',
                    'logout' => false,
                    'mac_registered' => true,
                    'mac_pending' => true,
                    'mac_has_credentials' => false,
                    'can_auto_trial' => false,
                    'auto_trial_status' => (string)($trial['status'] ?? 'error'),
                    'message' => (string)($trial['message'] ?? 'Não foi possível gerar o teste automático agora.') . ' Aguardando liberação.',
                ]);
            }
        }
        if (!$userRow) {
            auth_ensure_pending_mac($db, $mac, $deviceType);
            auth_json_out(auth_waiting_payload('MAC cadastrado. Aguardando DNS, usuário e senha.'));
        }
    }

    if (!auth_user_has_credentials($userRow)) {
        $autoMacEnabled = $activeMode === 'mac' && (int)($testCfg['auto_mac_enabled'] ?? 0) === 1 && (int)($testCfg['enabled'] ?? 0) === 1;
        if ($autoMacEnabled) {
            $trial = gerar_teste_service($db, $mac, $testCfg, [
                'nome' => 'Cliente MAC ' . strtoupper(substr(str_replace(':', '', $mac), -4)),
                'whatsapp' => '',
                'device_type' => $deviceType,
            ]);
            if (($trial['status'] ?? '') === 'success') {
                $st->execute([$mac]);
                $userRow = $st->fetch(PDO::FETCH_ASSOC) ?: $userRow;
            }
        }
        if (!auth_user_has_credentials($userRow)) {
            da_update_last_device($db, $mac, $deviceType);
            auth_json_out(auth_waiting_payload($autoMacEnabled ? 'Gerando teste automático ou aguardando DNS, usuário e senha.' : 'Aguardando DNS, usuário e senha.'));
        }
    }

    if (!da_can_device_login($db, $userRow, $deviceType)) {
        auth_json_out(['status' => 'forbidden', 'logout' => false, 'message' => 'Este tipo de dispositivo está bloqueado.']);
    }

    $validated = auth_validate_xtream_credentials((string)$userRow['dns'], (string)$userRow['username'], (string)$userRow['password']);
    if (empty($validated['ok'])) {
        auth_invalid_or_expired_out($validated);
    }

    $userRow = auth_refresh_user_after_validation($db, $userRow, $validated, $deviceType);
    auth_json_out(auth_build_success_payload($db, $userRow, $dnsList, trim((string)($userRow['dns'] ?? '')), [
        'active_login_mode' => $activeMode,
        'mac_registered' => true,
    ]));
}

if ($loginType === 'activation_code') {
    $code = preg_replace('/\D/', '', (string)($_POST['activation_code'] ?? $_POST['codigo'] ?? ''));
    if (strlen($code) !== 4) {
        auth_json_out(['status' => 'invalid', 'logout' => false, 'message' => 'Código de ativação inválido.']);
    }
    $st = $db->prepare('SELECT * FROM usuarios WHERE activation_code = ? LIMIT 1');
    $st->execute([$code]);
    $userRow = $st->fetch(PDO::FETCH_ASSOC) ?: null;
    if (!$userRow) {
        auth_json_out(['status' => 'invalid', 'logout' => false, 'message' => 'Código de ativação inválido.']);
    }

    if (!auth_user_has_credentials($userRow)) {
        auth_json_out(auth_waiting_payload('Aguardando DNS, usuário e senha.'));
    }

    $userMac = auth_normalize_mac((string)($userRow['mac'] ?? ''));
    if ($userMac !== '' && $userMac !== $mac) {
        $checkCurrent = $db->prepare('SELECT mac FROM usuarios WHERE mac = ? LIMIT 1');
        $checkCurrent->execute([$mac]);
        if ($checkCurrent->fetch(PDO::FETCH_ASSOC)) {
            auth_json_out(['status' => 'forbidden', 'logout' => false, 'message' => 'Este aparelho já está vinculado a outro cadastro.']);
        }
        $upMac = $db->prepare('UPDATE usuarios SET mac = ?, activation_code_used_at = ?, device_type = ?, last_device_type = ? WHERE activation_code = ?');
        $upMac->execute([$mac, time(), $deviceType, $deviceType, $code]);
        $userRow['mac'] = $mac;
    } else {
        $upUsed = $db->prepare('UPDATE usuarios SET activation_code_used_at = ?, device_type = ?, last_device_type = ? WHERE activation_code = ?');
        $upUsed->execute([time(), $deviceType, $deviceType, $code]);
    }

    if (!da_can_device_login($db, $userRow, $deviceType)) {
        auth_json_out(['status' => 'forbidden', 'logout' => false, 'message' => 'Este tipo de dispositivo está bloqueado.']);
    }

    $validated = auth_validate_xtream_credentials((string)$userRow['dns'], (string)$userRow['username'], (string)$userRow['password']);
    if (empty($validated['ok'])) {
        auth_invalid_or_expired_out($validated);
    }

    if (trim((string)($userRow['login_mode'] ?? '')) !== 'activation_code') {
        $db->prepare("UPDATE usuarios SET login_mode = 'activation_code' WHERE activation_code = ?")->execute([$code]);
        $userRow['login_mode'] = 'activation_code';
    }
    $userRow = auth_refresh_user_after_validation($db, $userRow, $validated, $deviceType);

    auth_json_out(auth_build_success_payload($db, $userRow, $dnsList, trim((string)($userRow['dns'] ?? '')), [
        'active_login_mode' => $activeMode,
        'mac_registered' => true,
    ]));
}

auth_json_out(['status' => 'invalid', 'logout' => false, 'message' => 'login_type_not_supported']);
