<?php
/**
 * SAC 2026 - KERNEL DIAGNOSTICS v1.0
 * Prueba de latencia y persistencia de datos.
 */
require_once 'config.php';

// Solo el programador puede ejecutar diagnósticos de Kernel
checkAccess(['programmer']);

$data = json_decode(file_get_contents("php://input"), true);
$action = $data['action'] ?? 'status';

try {
    if ($action === 'db_pulse') {
        $startTime = microtime(true);
        
        // 1. Prueba de Escritura
        $testId = "PULSE_" . time();
        $stmtW = $pdo->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?)");
        $stmtW->execute([$testId, 'OK']);
        
        // 2. Prueba de Lectura
        $stmtR = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ?");
        $stmtR->execute([$testId]);
        $val = $stmtR->fetchColumn();
        
        // 3. Limpieza
        $stmtD = $pdo->prepare("DELETE FROM system_settings WHERE setting_key = ?");
        $stmtD->execute([$testId]);
        
        $endTime = microtime(true);
        $latency = round(($endTime - $startTime) * 1000, 2);

        response([
            "status" => "success",
            "latency_ms" => $latency,
            "read_verify" => $val === 'OK',
            "server_time" => date('H:i:s'),
            "os" => PHP_OS,
            "php_version" => phpversion()
        ]);
    } else {
        response([
            "version" => "4.0.3",
            "environment" => "Ubuntu Server 24.04 LTS",
            "panel" => "aaPanel Pro",
            "architect" => "Andres Mathison",
            "company" => "TecnoMath.com"
        ]);
    }
} catch (Exception $e) {
    response(["error" => $e->getMessage()], 500);
}
?>