<?php
require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
require_once dirname(__DIR__) . '/_device_access.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);
} 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) {
    echo json_encode([
        "status" => "nao_cadastrado",
        "mac" => $mac_db
    ]);
    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;
}

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

if ($dns === "" || $username === "" || $password === "") {
    echo json_encode([
        "status" => "erro",
        "mac" => $mac_db
    ]);
    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,
    "device_type" => $deviceType,
    "hash" => $hash
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
