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

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

try {
    $pdo = getDBConnection();
    $method = $_SERVER['REQUEST_METHOD'];

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

        // Allow read for everyone logged in (to display alerts correctly)
        // But we might want to check if they have access to THIS ship
        if (!hasShipAccess($shipId)) {
            echo json_encode(['success' => false, 'message' => 'No autorizado']);
            exit;
        }

        $stmt = $pdo->prepare("SELECT max_temp, min_temp FROM ships WHERE ship_id = :ship");
        $stmt->execute([':ship' => $shipId]);
        $res = $stmt->fetch(PDO::FETCH_ASSOC);

        $maxTemp = $res ? (float) $res['max_temp'] : 25.0; // Default
        $minTemp = $res ? (float) $res['min_temp'] : 0.0;  // Default

        echo json_encode([
            'success' => true,
            'max_temp' => $maxTemp,
            'min_temp' => $minTemp
        ]);
    } elseif ($method === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        $shipId = $input['ship_id'] ?? '';
        $maxTemp = $input['max_temp'] ?? '';
        $minTemp = $input['min_temp'] ?? '';

        if (!$shipId)
            throw new Exception("Datos incompletos");

        // Only admins can write
        if (!hasShipAccess($shipId) || !canManageUsers()) {
            echo json_encode(['success' => false, 'message' => 'No autorizado']);
            exit;
        }

        // Prepare dynamic update
        $fields = [];
        $params = [':ship' => $shipId];

        if ($maxTemp !== '') {
            $fields[] = "max_temp = :max";
            $params[':max'] = $maxTemp;
        }
        if ($minTemp !== '') {
            $fields[] = "min_temp = :min";
            $params[':min'] = $minTemp;
        }

        if (empty($fields)) {
            echo json_encode(['success' => true]); // Nothing to update
            exit;
        }

        $sql = "UPDATE ships SET " . implode(', ', $fields) . " WHERE ship_id = :ship";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        echo json_encode(['success' => true]);
    }

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