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

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$dbPath = dirname(__DIR__) . "/db.db";

try {
    $db = new PDO("sqlite:" . $dbPath, null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_TIMEOUT => 3,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
    $db->exec("PRAGMA journal_mode=WAL;");
    $db->exec("PRAGMA synchronous=NORMAL;");
    $db->exec("PRAGMA temp_store=MEMORY;");
    da_ensure_schema($db);
    auth_ensure_schema($db);
} catch (Exception $e) {
    echo json_encode(["status" => "erro"]);
    exit;
}

$mac = trim($_POST["mac"] ?? $_GET["mac"] ?? "");
$deviceType = da_normalize_device_type((string)($_POST["device_type"] ?? $_GET["device_type"] ?? "tv"));

if ($mac === "") {
    echo json_encode(["status" => "erro"]);
    exit;
}

$mac_clean = preg_replace("/[^A-Fa-f0-9]/", "", $mac);
$mac_clean = strtoupper(substr($mac_clean, 0, 12));
$mac_db = implode(":", str_split($mac_clean, 2));

if (strlen($mac_clean) < 12) {
    echo json_encode(["status" => "erro"]);
    exit;
}

$stmt = $db->prepare("SELECT mac, dns, username, password, vencimento, status, nome_cliente, whatsapp, device_type, last_device_type FROM usuarios WHERE mac = ? LIMIT 1");
$stmt->execute([$mac_db]);
$row = $stmt->fetch();

if (!$row) {
    $meta = [
        'nome_cliente' => (string)($_POST['nome_cliente'] ?? $_GET['nome_cliente'] ?? ''),
        'whatsapp' => (string)($_POST['whatsapp'] ?? $_GET['whatsapp'] ?? ''),
        'device_name' => (string)($_POST['device_name'] ?? $_GET['device_name'] ?? ''),
        'device_brand' => (string)($_POST['device_brand'] ?? $_GET['device_brand'] ?? ''),
        'device_model' => (string)($_POST['device_model'] ?? $_GET['device_model'] ?? ''),
        'android_version' => (string)($_POST['android_version'] ?? $_GET['android_version'] ?? ''),
        'app_version' => (string)($_POST['app_version'] ?? $_GET['app_version'] ?? ''),
        'android_id' => (string)($_POST['android_id'] ?? $_GET['android_id'] ?? ''),
    ];
    auth_upsert_pending_device($db, $mac_db, $deviceType, $meta, false, 'device_check_missing');
    echo json_encode([
        "status" => "waiting",
        "mac" => $mac_db,
        "mac_registered" => true,
        "mac_pending" => true,
        "mac_has_credentials" => false,
        "logout" => true,
        "force_login" => true,
        "message" => "Aguardando ativação do dispositivo."
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$dns = trim($row["dns"] ?? "");
$username = trim($row["username"] ?? "");
$password = trim($row["password"] ?? "");
$vencimento = (int)($row["vencimento"] ?? 0);

if ($dns === "" || $username === "" || $password === "") {
    $meta = [
        'device_name' => (string)($_POST['device_name'] ?? $_GET['device_name'] ?? ''),
        'device_brand' => (string)($_POST['device_brand'] ?? $_GET['device_brand'] ?? ''),
        'device_model' => (string)($_POST['device_model'] ?? $_GET['device_model'] ?? ''),
        'android_version' => (string)($_POST['android_version'] ?? $_GET['android_version'] ?? ''),
        'app_version' => (string)($_POST['app_version'] ?? $_GET['app_version'] ?? ''),
        'android_id' => (string)($_POST['android_id'] ?? $_GET['android_id'] ?? ''),
    ];
    auth_upsert_pending_device($db, $mac_db, $deviceType, $meta, true, 'credentials_removed');
    echo json_encode([
        "status" => "waiting",
        "mac" => $mac_db,
        "mac_registered" => true,
        "mac_pending" => true,
        "mac_has_credentials" => false,
        "logout" => true,
        "force_login" => true,
        "message" => "Credenciais removidas. Aguardando nova ativação."
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (!da_can_device_login($db, $row, $deviceType)) {
    echo json_encode([
        "status" => "bloqueado",
        "mac" => $mac_db,
        "message" => "device_type_blocked"
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
da_update_last_device($db, $mac_db, $deviceType);

if (strtolower(trim((string)($row["status"] ?? ""))) !== "ativo") {
    echo json_encode([
        "status" => "bloqueado",
        "mac" => $mac_db,
        "message" => "device_inactive"
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}


$hash = md5($mac_db . "|" . $dns . "|" . $username . "|" . $password . "|" . $vencimento);

echo json_encode([
    "status" => "ok",
    "mac" => $mac_db,
    "dns" => $dns,
    "username" => $username,
    "password" => $password,
    "vencimento" => $vencimento,
    "nome_cliente" => (string)($row["nome_cliente"] ?? ""),
    "whatsapp" => (string)($row["whatsapp"] ?? ""),
    "ativo" => true,
    "mac_pending" => false,
    "mac_has_credentials" => true,
    "force_login" => false,
    "device_type" => $deviceType,
    "hash" => $hash
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
