<?php
header('Content-Type: application/json; charset=utf-8');

/* =====================================================
   1. ARCHIVOS
===================================================== */
$db_file     = __DIR__ . "/.db.db";
$teste_file  = __DIR__ . "/teste.json";
$config_file = __DIR__ . "/config_demo.json";

/* =====================================================
   2. VALIDACIONES INICIALES
===================================================== */
if (!file_exists($db_file)) {
    echo json_encode(["success" => false, "message" => "Banco de datos no encontrado."]);
    exit;
}

if (!file_exists($config_file)) {
    echo json_encode(["success" => false, "message" => "Config demo no encontrada."]);
    exit;
}

$config = json_decode(file_get_contents($config_file), true);

if (!$config || ($config['status'] ?? '') !== 'Activo') {
    echo json_encode(["success" => false, "message" => "Demo desactivado."]);
    exit;
}

$username_demo   = $config['username'] ?? null;
$password_demo   = $config['password'] ?? null;
$dns_uid         = $config['dns_uid'] ?? null;
$demo_duration   = intval($config['demo_duration'] ?? 3600);

if (!$username_demo || !$password_demo || !$dns_uid) {
    echo json_encode(["success" => false, "message" => "Config demo incompleta."]);
    exit;
}

/* =====================================================
   3. CAPTURA DEVICE ID
===================================================== */
$id_recebido = $_REQUEST['device_id'] ?? file_get_contents('php://input') ?? null;

if (!$id_recebido) {
    echo json_encode(["success" => false, "message" => "Device ID no detectado."]);
    exit;
}

$id_limpo = trim($id_recebido);

function obterMacFinal($id) {
    if ($id === "76:6c:7a:1b:19:b8:40:89") {
        return "f9:ac:11:ed:1b:99";
    }
    $reversed = strrev($id);
    $hash = hash('sha256', $reversed);
    $hex = substr($hash, 0, 12);
    return strtolower(implode(":", str_split($hex, 2)));
}

$mac_final = obterMacFinal($id_limpo);

/* =====================================================
   4. CONTROL DE TEST (teste.json)
===================================================== */
if (!file_exists($teste_file)) {
    file_put_contents($teste_file, json_encode([], JSON_PRETTY_PRINT));
}

$teste_data = json_decode(file_get_contents($teste_file), true) ?? [];

// Verificar si ya usó el demo
if (isset($teste_data[$mac_final])) {
    $inicio_demo = strtotime($teste_data[$mac_final]['timestamp'] ?? $teste_data[$mac_final]['data']);
    $fin_demo = $inicio_demo + $demo_duration;
    $ahora = time();
    $restante = $fin_demo - $ahora;

    if ($restante > 0) {
        echo json_encode([
            "success" => false,
            "message" => "⚠️ Este dispositivo ya está usando el demo",
            "time_remaining" => $restante
        ]);
        exit;
    } else {
        // Aquí el cronjob o proceso externo debería agregar un caracter a la contraseña
        // para desactivar automáticamente el demo. Mientras tanto lo bloqueamos.
        echo json_encode([
            "success" => false,
            "message" => "⛔ Demo expirado, espere a que su cuenta sea actualizada"
        ]);
        exit;
    }
}

/* =====================================================
   5. CONEXIÓN BD
===================================================== */
try {

    $db = new PDO("sqlite:$db_file");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    /* --- BUSCAR DNS POR UID --- */
    $stmt = $db->prepare("SELECT id, url FROM dns WHERE uid = :uid LIMIT 1");
    $stmt->execute([':uid' => $dns_uid]);
    $dns = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$dns) {
        echo json_encode(["success" => false, "message" => "DNS no encontrado."]);
        exit;
    }

    $dns_id  = $dns['id'];
    $dns_url = $dns['url'];

    /* --- INSERTAR EN IBOF --- */
    $hoje = date('Y-m-d');

    $stmt = $db->prepare("
        INSERT INTO ibof 
        (plid, name, macad, uuid, username, password, cdate, udate, mark, protec)
        VALUES
        (:plid, :name, :mac, :uuid, :user, :pass, :c, :u, '0', '1')
    ");

    $stmt->execute([
        ':plid' => (string)$dns_id,
        ':name' => 'TEST DEMO',
        ':mac'  => $mac_final,
        ':uuid' => $dns_uid,
        ':user' => $username_demo,
        ':pass' => $password_demo,
        ':c'    => $hoje,
        ':u'    => $hoje
    ]);

    /* =====================================================
       6. REGISTRAR EN teste.json
    ===================================================== */
    $teste_data[$mac_final] = [
        "timestamp" => date('Y-m-d H:i:s'),
        "device_id" => $id_limpo,
        "username"  => $username_demo,
        "password"  => $password_demo
    ];

    file_put_contents(
        $teste_file,
        json_encode($teste_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
    );

    /* =====================================================
       7. RESPUESTA FINAL
    ===================================================== */
    echo json_encode([
        "success"        => true,
        "message"        => "✅ Demo liberado correctamente",
        "mac"            => $mac_final,
        "username"       => $username_demo,
        "password"       => $password_demo,
        "dns"            => $dns_url,
        "uid"            => $dns_uid,
        "demo_duration"  => $demo_duration
    ]);
    exit;

} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "Erro: " . $e->getMessage()]);
    exit;
}
