<?php
require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
header("Content-Type: application/json; charset=utf-8");

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

try {
    $db = new PDO("sqlite:" . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    echo json_encode([
        "status" => "erro",
        "msg" => "db_error"
    ]);
    exit;
}

$mac = trim($_POST["mac"] ?? "");
$nome = trim($_POST["nome_cliente"] ?? "");
$wpp = trim($_POST["whatsapp"] ?? "");

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

$macClean = strtoupper(preg_replace('/[^A-F0-9]/i', '', $mac));

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

$macClean = substr($macClean, 0, 12);
$macDb = implode(":", str_split($macClean, 2));

try {
    $check = $db->prepare("SELECT id, username, nome_cliente, whatsapp FROM usuarios WHERE mac = ? LIMIT 1");
    $check->execute([$macDb]);
    $user = $check->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode([
            "status" => "erro",
            "msg" => "user_not_found",
            "mac" => $macDb
        ]);
        exit;
    }

    $st = $db->prepare("
        UPDATE usuarios
        SET nome_cliente = ?, whatsapp = ?
        WHERE mac = ?
    ");
    $st->execute([$nome, $wpp, $macDb]);

    $read = $db->prepare("
        SELECT username, nome_cliente, whatsapp, mac
        FROM usuarios
        WHERE mac = ?
        LIMIT 1
    ");
    $read->execute([$macDb]);
    $updated = $read->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        "status" => "ok",
        "msg" => "saved",
        "data" => [
            "username" => $updated["username"] ?? "",
            "nome_cliente" => $updated["nome_cliente"] ?? "",
            "whatsapp" => $updated["whatsapp"] ?? "",
            "mac" => $updated["mac"] ?? $macDb
        ]
    ]);
} catch (Exception $e) {
    echo json_encode([
        "status" => "erro",
        "msg" => "save_error"
    ]);
}