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

// Verificar que es una sesión de demo
session_start();
if (!isset($_SESSION['demo_user']) || $_SESSION['demo_user'] !== true) {
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

require_once '../config.php';
$pdo = getDBConnection();

if (!$pdo) {
    echo json_encode(['success' => false, 'message' => 'Error de conexión a BD']);
    exit;
}

// Solo GET permitido (lectura de BUQUE-01)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $buqueId = 'BUQUE-01'; // Siempre cargar desde BUQUE-01 en demo

    try {
        $stmt = $pdo->prepare("SELECT * FROM sensor_positions WHERE buque_id = :buque ORDER BY sensor_id ASC");
        $stmt->execute([':buque' => $buqueId]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $sensors = [];
        foreach ($rows as $row) {
            $sensors[] = [
                'id' => (int) $row['sensor_id'],
                'label' => $row['label'],
                'x' => $row['x'],
                'yTop' => $row['y_top'],
                'ySide' => $row['y_side']
            ];
        }

        echo json_encode([
            'success' => true,
            'message' => 'Datos obtenidos de BUQUE-01',
            'data' => [
                'sensors' => $sensors,
                'buque_id' => $buqueId
            ]
        ], JSON_UNESCAPED_UNICODE);

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error leyendo de BD: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
}
exit;

