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

// Crear archivo de log
$logFile = __DIR__ . '/debug_log.txt';

function writeLog($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message" . PHP_EOL, FILE_APPEND);
}

writeLog("=== NUEVA PETICIÓN ===");
writeLog("POST data: " . print_r($_POST, true));
writeLog("GET data: " . print_r($_GET, true));
writeLog("SERVER: " . $_SERVER['REMOTE_ADDR'] . " - " . $_SERVER['HTTP_USER_AGENT']);

$dbFile = __DIR__ . '/.db.db';

if (!file_exists($dbFile)) {
    writeLog("ERROR: Base de datos no encontrada en " . $dbFile);
    echo json_encode(["ok" => false, "reason" => "db_not_found"]);
    exit;
}

$code = isset($_POST['code']) ? trim($_POST['code']) : '';
$device_id = isset($_POST['device_id']) ? trim($_POST['device_id']) : '';

writeLog("Code recibido: '" . $code . "'");
writeLog("Device ID recibido: '" . $device_id . "'");

if ($code === '') {
    writeLog("ERROR: Código vacío");
    echo json_encode(["ok" => false, "reason" => "missing_code"]);
    exit;
}

if ($device_id === '') {
    $device_id = hash('sha256', $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']);
    writeLog("Device ID generado automáticamente: '" . $device_id . "'");
} else {
    writeLog("Device ID enviado por la app: '" . $device_id . "'");
}

try {
    $pdo = new PDO('sqlite:' . $dbFile);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    writeLog("Base de datos conectada correctamente");

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS code_connections (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            code TEXT NOT NULL,
            device_id TEXT NOT NULL,
            ip_address TEXT,
            connected_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            last_activity DATETIME DEFAULT CURRENT_TIMESTAMP,
            is_active INTEGER DEFAULT 1,
            UNIQUE(code, device_id)
        )
    ");

    $stmt = $pdo->prepare("SELECT code, expires_at FROM codes WHERE code = :code LIMIT 1");
    $stmt->execute([':code' => $code]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        writeLog("ERROR: Código '$code' no encontrado en la base de datos");
        echo json_encode(["ok" => false, "reason" => "not_found"]);
        exit;
    }

    writeLog("Código encontrado: " . $row['code'] . " - Expira: " . $row['expires_at']);

    $expiresAt = trim((string)$row['expires_at']);

    // ============================================================
    // PASO 1: VERIFICAR EXPIRACIÓN PRIMERO
    // ============================================================
    $now = new DateTime('now');
    $exp = null;

    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $expiresAt)) {
        $exp = DateTime::createFromFormat('Y-m-d H:i:s', $expiresAt . ' 23:59:59');
        writeLog("Formato fecha YYYY-MM-DD, ajustado a 23:59:59");
    } else {
        try {
            $exp = new DateTime($expiresAt);
            writeLog("Formato fecha completo: " . $expiresAt);
        } catch (Throwable $e) {
            $exp = null;
            writeLog("ERROR al parsear fecha: " . $e->getMessage());
        }
    }

    if (!$exp) {
        writeLog("ERROR: Fecha de expiración inválida");
        echo json_encode(["ok" => false, "reason" => "invalid_exp_date"], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $secondsLeft = $exp->getTimestamp() - $now->getTimestamp();
    $daysLeft    = (int)floor($secondsLeft / 86400);
    $hoursLeft   = (int)floor($secondsLeft / 3600);

    writeLog("Tiempo restante: {$daysLeft} días, {$hoursLeft} horas, {$secondsLeft} segundos");
    writeLog("Now: " . $now->format('Y-m-d H:i:s'));
    writeLog("Exp: " . $exp->format('Y-m-d H:i:s'));

    // SI EXPIRÓ → RESPONDER "expired"
    if ($secondsLeft < 0) {
        writeLog("CÓDIGO EXPIRADO");
        $pdo->prepare("UPDATE code_connections SET is_active = 0 WHERE code = :code")
            ->execute([':code' => $code]);
            
        echo json_encode([
            "ok" => false,
            "reason" => "expired",
            "expires_at" => $expiresAt,
            "days_left" => $daysLeft,
            "hours_left" => $hoursLeft,
            "seconds_left" => $secondsLeft,
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // ============================================================
    // PASO 2: SOLO SI NO EXPIRÓ, VERIFICAR DISPOSITIVOS
    // ============================================================
    
    $stmtCount = $pdo->prepare("
        SELECT COUNT(DISTINCT device_id) as total 
        FROM code_connections 
        WHERE code = :code AND is_active = 1
    ");
    $stmtCount->execute([':code' => $code]);
    $activeDevices = $stmtCount->fetch(PDO::FETCH_ASSOC)['total'];
    
    $MAX_DEVICES = 5;
    writeLog("Dispositivos activos para código '$code': {$activeDevices}/{$MAX_DEVICES}");
    
    $stmtCheck = $pdo->prepare("
        SELECT id, is_active FROM code_connections 
        WHERE code = :code AND device_id = :device_id
    ");
    $stmtCheck->execute([':code' => $code, ':device_id' => $device_id]);
    $existingConnection = $stmtCheck->fetch(PDO::FETCH_ASSOC);
    
    if ($existingConnection && $existingConnection['is_active'] == 1) {
        writeLog("Dispositivo ya conectado (ID: {$existingConnection['id']}) - Actualizando actividad");
        $stmtUpdate = $pdo->prepare("
            UPDATE code_connections 
            SET last_activity = CURRENT_TIMESTAMP, ip_address = :ip 
            WHERE id = :id
        ");
        $stmtUpdate->execute([
            ':ip' => $_SERVER['REMOTE_ADDR'],
            ':id' => $existingConnection['id']
        ]);
    } 
    elseif (!$existingConnection) {
        if ($activeDevices >= $MAX_DEVICES) {
            writeLog("LÍMITE ALCANZADO: {$activeDevices}/{$MAX_DEVICES} - Rechazando nueva conexión");
            echo json_encode([
                "ok" => false, 
                "reason" => "max_devices_reached",
                "max_devices" => $MAX_DEVICES,
                "active_devices" => $activeDevices
            ]);
            exit;
        }
        
        writeLog("Nuevo dispositivo conectándose - Registrando conexión");
        $stmtInsert = $pdo->prepare("
            INSERT INTO code_connections (code, device_id, ip_address, connected_at, last_activity)
            VALUES (:code, :device_id, :ip, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
        ");
        $stmtInsert->execute([
            ':code' => $code,
            ':device_id' => $device_id,
            ':ip' => $_SERVER['REMOTE_ADDR']
        ]);
        writeLog("Nueva conexión registrada correctamente");
    }
    else {
        writeLog("Dispositivo estaba inactivo - Reactivando");
        $stmtReactivate = $pdo->prepare("
            UPDATE code_connections 
            SET is_active = 1, last_activity = CURRENT_TIMESTAMP, ip_address = :ip 
            WHERE id = :id
        ");
        $stmtReactivate->execute([
            ':ip' => $_SERVER['REMOTE_ADDR'],
            ':id' => $existingConnection['id']
        ]);
    }

    $stmtStats = $pdo->prepare("
        SELECT COUNT(DISTINCT device_id) as total_devices 
        FROM code_connections 
        WHERE code = :code AND is_active = 1
    ");
    $stmtStats->execute([':code' => $code]);
    $totalDevices = $stmtStats->fetch(PDO::FETCH_ASSOC)['total'];

    writeLog("RESPUESTA EXITOSA - Dispositivos activos: {$totalDevices}");
    writeLog("=== FIN PETICIÓN ===" . PHP_EOL);

    echo json_encode([
        "ok" => true,
        "expires_at" => $expiresAt,
        "days_left" => $daysLeft,
        "hours_left" => $hoursLeft,
        "seconds_left" => $secondsLeft,
        "max_devices" => $MAX_DEVICES,
        "active_devices" => (int)$totalDevices
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Throwable $e) {
    writeLog("EXCEPCIÓN: " . $e->getMessage());
    writeLog("=== FIN PETICIÓN (ERROR) ===" . PHP_EOL);
    echo json_encode(["ok" => false, "reason" => "server_error"]);
}
?>