<?php
header('Content-Type: application/json');

// La ruta correcta de tu base de datos
$db_file = __DIR__ . "/.db.db";

// Función original de tu panel para encriptar la MAC correctamente
function obterMacFinal($id) {
    $reversed = strrev($id);
    $hash = hash('sha256', $reversed);
    $hex = substr($hash, 0, 12);
    return strtolower(implode(":", str_split($hex, 2)));
}

function seconds_to_readable(int $seconds) {
    $h = floor($seconds / 3600);
    $m = floor(($seconds % 3600) / 60);
    $s = $seconds % 60;
    $parts = [];
    if ($h > 0) $parts[] = "$h h";
    if ($m > 0) $parts[] = "$m m";
    if ($s > 0) $parts[] = "$s s";
    return implode(' ', $parts) ?: '0 s';
}

$device_id_raw = trim($_POST['device_id'] ?? '');
if (!$device_id_raw) {
    echo json_encode(["success" => false, "message" => "❌ Device ID not provided."]);
    exit;
}

// Convertir el device_id a la MAC encriptada que usa tu panel
$mac_final = obterMacFinal($device_id_raw);

try {
    $jsonFile = __DIR__ . "/config_test.json";
    if (!file_exists($jsonFile)) {
        echo json_encode(["success" => false, "message" => "❌ config_test.json file not found."]);
        exit;
    }
    $directo = json_decode(file_get_contents($jsonFile), true);

    $username = $directo['username'] ?? null;
    $password = $directo['password'] ?? null;
    $dns_url  = $directo['dns_url'] ?? null;
    $status   = $directo['status'] ?? 'Desactivado';
    $demo_duration = isset($directo['demo_duration']) ? intval($directo['demo_duration']) : 3600;

    if ($status !== 'Activo') {
        echo json_encode(["success" => false, "message" => "⚠️ Auto Demo function is disabled."]);
        exit;
    }

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

    // Actualizar la tabla IBOF para que soporte los demos (solo lo hace la primera vez)
    try {
        $db->exec("ALTER TABLE ibof ADD COLUMN demo_start INTEGER");
        $db->exec("ALTER TABLE ibof ADD COLUMN demo_duration INTEGER");
        $db->exec("ALTER TABLE ibof ADD COLUMN is_demo INTEGER DEFAULT 1");
    } catch (Exception $e) {
        // Si las columnas ya existen, ignora este paso
    }

    // Buscar la MAC en la tabla IBOF
    $stmtCheck = $db->prepare("SELECT * FROM ibof WHERE macad = :mac LIMIT 1");
    $stmtCheck->execute([':mac' => $mac_final]);
    $row = $stmtCheck->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $current_password = strval($row['password'] ?? '');
        
        if (substr($current_password, -1) === '_') {
            echo json_encode(["success" => false, "message" => "🚫 Your demo has expired."]);
            exit;
        }
        
        // Protección para las cuentas manuales o revendedores
        if (empty($row['demo_start'])) {
            echo json_encode(["success" => false, "message" => "⚠️ This MAC already has a paid account. No demo available."]);
            exit;
        }

        $start_ts = intval($row['demo_start']);
        $duration_sec = intval($row['demo_duration']);
        $now = time();
        
        if ($now < ($start_ts + $duration_sec)) {
            $remaining = ($start_ts + $duration_sec) - $now;
            echo json_encode(["success" => true, "message" => "✅ Resuming Demo. You have " . seconds_to_readable($remaining) . " left."]);
            exit;
        } else {
            echo json_encode(["success" => false, "message" => "⏳ Your demo has ended."]);
            exit;
        }
    }

    // Si no existe, crear el demo en IBOF
    $stmtDns = $db->prepare("SELECT id, uid FROM dns WHERE url = :url LIMIT 1");
    $stmtDns->execute([':url' => $dns_url]);
    $dnsRow = $stmtDns->fetch(PDO::FETCH_ASSOC);
    if (!$dnsRow) {
        echo json_encode(["success" => false, "message" => "❌ Internal DNS error."]);
        exit;
    }
    
    $dns_id = $dnsRow['id'];
    $uuid = $dnsRow['uid'] ?? '0';
    $hoje = date('Y-m-d');
    $now = time();

    $stmtInsert = $db->prepare("
        INSERT INTO ibof (plid, name, macad, uuid, username, password, cdate, udate, mark, protec, demo_start, demo_duration, is_demo)
        VALUES (:plid, :name, :mac, :uuid, :user, :pass, :c, :u, '0', '1', :ds, :dd, 1)
    ");
    $stmtInsert->execute([
        ':plid' => (string)$dns_id,
        ':name' => 'DEMO AUTO',
        ':mac'  => $mac_final,
        ':uuid' => $uuid,
        ':user' => $username,
        ':pass' => $password,
        ':c'    => $hoje,
        ':u'    => $hoje,
        ':ds'   => $now,
        ':dd'   => $demo_duration
    ]);

    echo json_encode(["success" => true, "message" => "✅ Demo generated! Please 'Reload' to load your playlist."]);

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