<?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 y POST permitidos
$buqueId = 'BUQUE-01'; // Siempre usar BUQUE-01 en demo

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    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()]);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (!isset($data['sensors']) || !is_array($data['sensors'])) {
        echo json_encode(['success' => false, 'message' => 'Datos inválidos']);
        exit;
    }

    $sensors = $data['sensors'];
    $count = 0;

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("
            INSERT INTO sensor_positions (sensor_id, buque_id, label, x, y_top, y_side)
            VALUES (:sensor_id, :buque_id, :label, :x, :y_top, :y_side)
            ON DUPLICATE KEY UPDATE
            label = VALUES(label),
            x = VALUES(x),
            y_top = VALUES(y_top),
            y_side = VALUES(y_side)
        ");

        foreach ($sensors as $s) {
            $stmt->execute([
                ':sensor_id' => $s['id'],
                ':buque_id' => $buqueId,
                ':label' => $s['label'] ?? "Sensor {$s['id']}",
                ':x' => $s['x'] ?? '50%',
                ':y_top' => $s['yTop'] ?? '0%',
                ':y_side' => $s['ySide'] ?? '0%'
            ]);
            $count++;
        }

        $pdo->commit();
        echo json_encode(['success' => true, 'message' => 'Configuración de Demo guardada', 'updated' => $count]);

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

