<?php
declare(strict_types=1);

require_once __DIR__ . '/../_app_guard.php';
app_guard_validate();
require_once __DIR__ . '/../_auth_common.php';

header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

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

function out_json(array $payload, int $code = 200): void {
    http_response_code($code);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$macRaw = trim((string)($_POST['mac'] ?? $_POST['device_id'] ?? ''));
$mac = auth_normalize_mac($macRaw);
if ($mac === '' || strlen(preg_replace('/[^A-Fa-f0-9]/', '', $mac)) < 12) {
    out_json(['status' => 'error', 'message' => 'mac_invalid'], 400);
}

$username = trim((string)($_POST['username'] ?? ''));
$password = trim((string)($_POST['password'] ?? ''));
$deviceName = trim((string)($_POST['device_name'] ?? 'Android TV'));
$loginMethod = trim((string)($_POST['login_method'] ?? 'mac'));
$deviceType = da_normalize_device_type((string)($_POST['device_type'] ?? 'tv'));
$ip = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$now = time();

try {
    $db = new PDO('sqlite:' . __DIR__ . '/../db.db', 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;');
    auth_ensure_schema($db);
} catch (Throwable $e) {
    out_json(['status' => 'error', 'message' => 'db_error'], 500);
}

try {
    $check = $db->prepare('SELECT mac, status, username, password, dns FROM usuarios WHERE mac = ? LIMIT 1');
    $check->execute([$mac]);
    $existing = $check->fetch();

    if (!$existing) {
        $stmt = $db->prepare("
            INSERT INTO usuarios
                (mac, dns, username, password, vencimento, status, nome_cliente, whatsapp, teste, login_mode, device_type, last_device_type)
            VALUES
                (?, '', '', '', 0, 'inativo', ?, '', 0, 'mac', ?, ?)
        ");
        $stmt->execute([$mac, $deviceName, $deviceType, $deviceType]);
        $registered = true;
    } else {
        da_update_last_device($db, $mac, $deviceType);
        $registered = false;
    }

    $logFile = __DIR__ . '/devices.json';
    $devices = [];
    if (is_file($logFile)) {
        $decoded = json_decode((string)file_get_contents($logFile), true);
        $devices = is_array($decoded) ? $decoded : [];
    }
    $devices[] = [
        'mac' => $mac,
        'username' => $username,
        'device_id' => $mac,
        'device_name' => $deviceName,
        'device_type' => $deviceType,
        'login_method' => $loginMethod,
        'ip' => $ip,
        'date' => date('Y-m-d H:i:s', $now),
    ];
    @file_put_contents($logFile, json_encode($devices, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

    out_json([
        'status' => 'success',
        'registered' => $registered,
        'mac' => $mac,
        'message' => $registered ? 'MAC registrado para ativacao' : 'Device registrado'
    ]);
} catch (Throwable $e) {
    out_json(['status' => 'error', 'message' => 'register_error'], 500);
}
