<?php
ob_start();
require_once '../auth.php';
require_once '../config.php';

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

try {
    $pdo = getDBConnection();
    if (!$pdo) {
        throw new Exception('Error de conexión a BD');
    }

    $method = $_SERVER['REQUEST_METHOD'];

    if ($method === 'GET') {
        $shipId = $_GET['ship_id'] ?? '';
        if (!$shipId) {
            throw new Exception("Falta ID de buque");
        }

        if (!hasShipAccess($shipId)) {
            echo json_encode(['success' => false, 'message' => 'No autorizado']);
            exit;
        }

        // Obtener configuraciones de temperatura por sensor
        $stmt = $pdo->prepare("
            SELECT sensor_id, sensor_label, max_temp, min_temp 
            FROM sensor_temperature_config 
            WHERE buque_id = :ship_id
            ORDER BY sensor_id
        ");
        $stmt->execute([':ship_id' => $shipId]);
        $configs = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Si no hay configuraciones, obtener labels de sensor_positions
        if (empty($configs)) {
            $stmt = $pdo->prepare("
                SELECT DISTINCT sensor_id, label 
                FROM sensor_positions 
                WHERE buque_id = :ship_id
                ORDER BY sensor_id
            ");
            $stmt->execute([':ship_id' => $shipId]);
            $sensors = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Crear configuraciones por defecto
            foreach ($sensors as $sensor) {
                $configs[] = [
                    'sensor_id' => $sensor['sensor_id'],
                    'sensor_label' => $sensor['label'],
                    'max_temp' => 27.00,
                    'min_temp' => -40.00
                ];
            }
        }

        echo json_encode([
            'success' => true,
            'configs' => $configs
        ]);

    } elseif ($method === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        $shipId = $input['ship_id'] ?? '';
        $configs = $input['configs'] ?? [];

        if (!$shipId || !is_array($configs)) {
            throw new Exception("Datos incompletos");
        }

        // Solo sub-adm y admin pueden escribir
        if (!hasShipAccess($shipId) || !canManageUsers()) {
            echo json_encode(['success' => false, 'message' => 'No autorizado']);
            exit;
        }

        $pdo->beginTransaction();

        try {
            foreach ($configs as $config) {
                $sensorId = $config['sensor_id'] ?? null;
                $sensorLabel = $config['sensor_label'] ?? '';
                $maxTemp = $config['max_temp'] ?? 27.00;
                $minTemp = $config['min_temp'] ?? -40.00;

                if ($sensorId === null) continue;

                $stmt = $pdo->prepare("
                    INSERT INTO sensor_temperature_config (buque_id, sensor_id, sensor_label, max_temp, min_temp)
                    VALUES (:buque_id, :sensor_id, :sensor_label, :max_temp, :min_temp)
                    ON DUPLICATE KEY UPDATE
                    sensor_label = VALUES(sensor_label),
                    max_temp = VALUES(max_temp),
                    min_temp = VALUES(min_temp)
                ");
                $stmt->execute([
                    ':buque_id' => $shipId,
                    ':sensor_id' => $sensorId,
                    ':sensor_label' => $sensorLabel,
                    ':max_temp' => $maxTemp,
                    ':min_temp' => $minTemp
                ]);
            }

            $pdo->commit();
            echo json_encode(['success' => true]);

        } catch (Exception $e) {
            $pdo->rollBack();
            throw $e;
        }
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit;
?>

