<?php
header('Content-Type: application/json');
$db_file = __DIR__ . "/.db.db";

function normalize_mac_for_store(string $mac): string {
    $hex = preg_replace('/[^0-9A-Fa-f]/', '', $mac);
    $hex = strtoupper($hex);
    $pairs = array_filter(str_split($hex, 2), fn($p) => strlen($p) === 2);
    return implode(':', $pairs);
}

function seconds_to_readable(int $seconds): string {
    $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';
}

function mac_plain(string $mac): string {
    return preg_replace('/[^0-9A-Fa-f]/', '', strtoupper($mac));
}

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

try {
    // Leer JSON config
    $jsonFile = __DIR__ . "/config_test.json";
    if (!file_exists($jsonFile)) {
        echo json_encode(["success" => false, "message" => "❌ Archivo config_test.json no encontrado."]);
        exit;
    }
    $directo = json_decode(file_get_contents($jsonFile), true);
    if (!$directo) {
        echo json_encode(["success" => false, "message" => "❌ Error al leer config_test.json."]);
        exit;
    }

    $username = $directo['username'] ?? null;
    $password = $directo['password'] ?? null;
    $dns_url  = $directo['dns_url'] ?? null;
    $payUrl   = $directo['payUrl'] ?? 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" => "⚠️ Función de demo inactiva."]);
        exit;
    }
    if (empty($username) || empty($password) || empty($dns_url)) {
        echo json_encode(["success" => false, "message" => "❌ Configuración directa incompleta."]);
        exit;
    }

    $iptv_url = $dns_url . "/get.php?username=" . urlencode($username) . "&password=" . urlencode($password) . "&type=m3u_plus&output=ts";

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

    // Asegurar tabla
    $db->exec("
        CREATE TABLE IF NOT EXISTS playlist (
            id INTEGER PRIMARY KEY,
            dns_id INTEGER,
            mac_address TEXT,
            username TEXT,
            password TEXT,
            pin TEXT,
            device_key TEXT,
            link TEXT,
            demo_start INTEGER,
            demo_duration INTEGER,
            last_used INTEGER DEFAULT (strftime('%s','now')),
            is_demo INTEGER DEFAULT 1
        )
    ");

    // Buscar registro existente
    $mac_plain = mac_plain($device_id);
    $stmtCheck = $db->prepare("SELECT * FROM playlist WHERE REPLACE(UPPER(mac_address),':','') = :mac_plain ORDER BY id DESC LIMIT 1");
    $stmtCheck->execute([':mac_plain' => $mac_plain]);
    $row = $stmtCheck->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $current_password = strval($row['password'] ?? '');
        
        // ✅ VERIFICACIÓN 1: Si ya está bloqueado por el cron
        if (substr($current_password, -1) === '_') {
            echo json_encode([
                "success" => false,
                "message" => "🚫 Tu demo ha expirado. La cuenta ha sido bloqueada.",
                "username" => $row['username'],
                "password" => $current_password,
                "iptv_url" => $iptv_url,
                "payUrl" => $row['link']
            ]);
            exit;
        }
        
        // ✅ VERIFICACIÓN 2: Si ya usó un demo completo anteriormente
        if (isset($row['is_demo']) && intval($row['is_demo']) === 0) {
            echo json_encode([
                "success" => false,
                "message" => "⚠️ Esta MAC ya ha usado un demo anteriormente.",
                "username" => $row['username'],
                "password" => $current_password,
                "iptv_url" => $iptv_url,
                "payUrl" => $row['link']
            ]);
            exit;
        }

        // ✅ VERIFICACIÓN 3: Calcular tiempo de expiración CORRECTAMENTE
        $start_ts = intval($row['demo_start']);
        $duration_sec = intval($row['demo_duration']);
        $expiry_ts = $start_ts + $duration_sec;
        $now = time();
        
        if ($now < $expiry_ts) {
            // Demo aún activo
            $remaining = $expiry_ts - $now;
            $readable = seconds_to_readable($remaining);
            echo json_encode([
                "success" => false,
                "message" => "⚠️ Ya tienes un demo activo. Te quedan $readable.",
                "username" => $row['username'],
                "password" => $current_password,
                "iptv_url" => $iptv_url,
                "payUrl" => $row['link']
            ]);
            exit;
        } else {
            // Demo expirado - dejar que el cron lo maneje
            echo json_encode([
                "success" => false,
                "message" => "⏳ Tu demo ha expirado. El sistema lo bloqueará automáticamente en breve.",
                "username" => $row['username'],
                "password" => $current_password,
                "iptv_url" => $iptv_url,
                "payUrl" => $row['link']
            ]);
            exit;
        }
    }

    // No existe registro: crear demo nuevo
    $stmtDns = $db->prepare("SELECT id 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" => "❌ La URL DNS configurada en el JSON no existe en la base de datos."]);
        exit;
    }
    $dns_id = intval($dnsRow['id']);

    $mac_store = normalize_mac_for_store($device_id);
    $now = time();

    $stmtInsert = $db->prepare("
        INSERT INTO playlist (dns_id, mac_address, username, password, pin, device_key, link, demo_start, demo_duration, last_used, is_demo)
        VALUES (:dns_id, :mac_address, :username, :password, :pin, :device_key, :link, :demo_start, :demo_duration, :last_used, :is_demo)
    ");
    $stmtInsert->execute([
        ':dns_id' => $dns_id,
        ':mac_address' => $mac_store,
        ':username' => $username,
        ':password' => $password,
        ':pin' => '0000',
        ':device_key' => null,
        ':link' => $payUrl,
        ':demo_start' => $now,
        ':demo_duration' => $demo_duration,
        ':last_used' => $now,
        ':is_demo' => 1
    ]);

    echo json_encode([
        "success" => true,
        "message" => "✅ Demo generado con éxito",
        "username" => $username,
        "password" => $password,
        "iptv_url" => $iptv_url,
        "payUrl" => $payUrl
    ]);

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