<?php
/**
 * BUQUE.PHP - VERSIÓN DE ALTA COMPATIBILIDAD Y RENDIMIENTO
 */

// 1. CONFIGURACIÓN
$cacheDir = __DIR__ . '/../cache';
if (!is_dir($cacheDir)) @mkdir($cacheDir, 0755, true);

// 2. CARGAR CONFIGURACIÓN
require_once '../config.php';
header('Content-Type: application/json; charset=utf-8');

// 3. RECEPCIÓN DE DATOS
$rawData = file_get_contents('php://input');
if (empty($rawData)) {
    exit;
}

// 4. DETECTAR FORMATO Y LIMPIAR
$isJson = (substr(trim($rawData), 0, 1) === '{');
$consolidatedTemps = [];
$buqueId = 'BOUCIÑA-01'; // Default

if ($isJson) {
    $data = json_decode($rawData, true);
    if (!$data) {
        exit;
    }
    if (!isset($data['apiKey']) || $data['apiKey'] !== API_KEY) {
        exit;
    }
    $buqueId = $data['buqueId'] ?? $buqueId;
    $idZona = 15;
    $temperatura = $data['lastTemp'] ?? 0;
    $consolidatedTemps = $data['temps'] ?? [];
} else {
    $values = array_map('trim', explode(',', trim($rawData)));
    if (count($values) < 4) {
        exit;
    }
    $temperatura = $values[0];
    $idZona = (int) $values[1];
    $apiKey = $values[3] ?? '';
    $buqueIdFromPayload = $values[4] ?? null;
    
    if ($apiKey !== API_KEY) {
        exit;
    }
    
    if (!empty($buqueIdFromPayload)) {
        $buqueId = $buqueIdFromPayload;
    }
}

// LIMPIAR BUQUE ID (Asegurar UTF-8)
if (!mb_check_encoding($buqueId, 'UTF-8')) {
    $buqueId = mb_convert_encoding($buqueId, 'UTF-8', 'ISO-8859-1');
}

// 5. MANEJO DE CACHÉ
// Sanitizar buqueId para el nombre del archivo (evitar problemas de Ñ o caracteres especiales)
$safeBuqueId = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $buqueId);
$cacheFile = $cacheDir . "/ship_$safeBuqueId.json"; 
$now = time();
$syncInterval = 120; // 2 minutos

$cacheData = [];
if (file_exists($cacheFile)) {
    $cacheData = json_decode(file_get_contents($cacheFile), true);
}

if (!is_array($cacheData)) {
    $cacheData = [
        'temps' => array_fill(1, 16, null),
        'timestamps' => array_fill(1, 16, 0),
        'last_db_sync' => 0,
        'buqueId' => $buqueId
    ];
}

// ACTUALIZAR CACHÉ
if (!empty($consolidatedTemps)) {
    foreach ($consolidatedTemps as $idx => $val) {
        $idx = (int)$idx;
        if ($idx >= 1 && $idx <= 16) {
            $cacheData['temps'][$idx] = $val;
            $cacheData['timestamps'][$idx] = $now;
        }
    }
} else {
    if ($idZona >= 1 && $idZona <= 16) {
        $cacheData['temps'][$idZona] = $temperatura;
        $cacheData['timestamps'][$idZona] = $now;
    }
}

$cacheData['last_contact'] = date('Y-m-d H:i:s');
$cacheData['ip'] = $_SERVER['REMOTE_ADDR'] ?? '---';

// 6. SINCRONIZACIÓN CON BASE DE DATOS
$lastSync = (int)($cacheData['last_db_sync'] ?? 0);
$shouldSyncDB = ($now - $lastSync >= $syncInterval) || ($idZona === 999);

if ($shouldSyncDB) {
    try {
        $pdo = getDBConnection();
        if ($pdo) {
            $payload = [
                'unica' => true,
                'fecha' => $cacheData['last_contact'],
                'ip' => $cacheData['ip'],
                'sensor_timestamps' => $cacheData['timestamps']
            ];
            // Aplanar temperaturas para que el Dashboard las encuentre
            for ($i = 1; $i <= 16; $i++) {
                $payload["temp$i"] = $cacheData['temps'][$i];
            }

            $pdo->prepare("UPDATE ships SET last_contact = NOW(), last_payload = :p WHERE ship_id = :b")
                ->execute([':p' => json_encode($payload, JSON_UNESCAPED_UNICODE), ':b' => $buqueId]);

            if ($idZona !== 999) {
                $cols = []; $vals = []; $params = [];
                $timeout = 600; // 10 minutos (120s sync * 5 approx)
                
                for ($i = 1; $i <= 16; $i++) {
                    $cols[] = "temp$i"; $vals[] = ":t$i";
                    
                    $val = $cacheData['temps'][$i];
                    $ts = (int)($cacheData['timestamps'][$i] ?? 0);
                    
                    // Si el sensor no ha reportado en 10 minutos, lo marcamos como NULL
                    if ($ts > 0 && ($now - $ts) > $timeout) {
                        $val = null;
                        $cacheData['temps'][$i] = null; // También lo limpiamos de la caché
                    }
                    
                    $params[":t$i"] = ($val === null || $val === '') ? null : (float)$val;
                }
                $sql = "INSERT INTO mediciones (buque_id, " . implode(', ', $cols) . ", fecha, ip) VALUES (:b, " . implode(', ', $vals) . ", :f, :ip)";
                $params[':b'] = $buqueId;
                $params[':f'] = $cacheData['last_contact'];
                $params[':ip'] = $cacheData['ip'];
                $pdo->prepare($sql)->execute($params);
                $cacheData['last_db_sync'] = $now;
            }
        }
    } catch (Exception $e) {
        $logFile = __DIR__ . '/../logs/debug_buque.log';
        if (!is_dir(__DIR__ . '/../logs')) @mkdir(__DIR__ . '/../logs', 0755, true);
        @file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] ERROR DB: " . $e->getMessage() . " - SQL: " . ($sql ?? 'N/A') . "\n", FILE_APPEND);
    }
}

// GUARDAR CACHÉ SIEMPRE
file_put_contents($cacheFile, json_encode($cacheData, JSON_UNESCAPED_UNICODE));

echo json_encode(["success" => true, "message" => "OK"]);
exit;