<?php
ob_start();
// api/sensor_positions.php
/**
 * API para guardar y obtener posiciones de sensores (DB VERSION)
 * Sincroniza labels y posiciones con la tabla `sensor_positions` de MariaDB.
 */

require_once '../auth.php';
require_once '../config.php';

checkApiLogin();
$pdo = getDBConnection();

if (ob_get_level() > 0)
    ob_clean();
header('Content-Type: application/json; charset=utf-8');

if (!$pdo) {
    jsonResponse(false, 'Error de conexión a BD', null, 500);
}

// ---------------------------------------------------------
// POST: GUARDAR CONFIGURACIÓN
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (!isset($data['buque_id']) || !isset($data['sensors']) || !is_array($data['sensors'])) {
        jsonResponse(false, 'Datos inválidos', null, 400);
    }

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

    try {
        $pdo->beginTransaction();

        // Prepare statement for Upsert (Insert or Update)
        // Columns: sensor_id, buque_id, label, x, y_top, y_side
        $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();

        // Also update JSON file as backup/cache if needed (optional, but good for backward compat)
        // copyToJSON($buqueId, $sensors); 

        jsonResponse(true, 'Configuración guardada en Base de Datos', ['updated' => $count]);

    } catch (Exception $e) {
        $pdo->rollBack();
        jsonResponse(false, 'Error guardando en BD: ' . $e->getMessage(), null, 500);
    }
}

// ---------------------------------------------------------
// GET: LEER CONFIGURACIÓN
// ---------------------------------------------------------
elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $buqueId = isset($_GET['buque_id']) ? $_GET['buque_id'] : 'BUQUE-01';

    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']
            ];
        }

        jsonResponse(true, 'Datos obtenidos de BD', [
            'sensors' => $sensors,
            'buque_id' => $buqueId
        ]);

    } catch (Exception $e) {
        jsonResponse(false, 'Error leyendo de BD', null, 500);
    }
} else {
    jsonResponse(false, 'Método no permitido', null, 405);
}
