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

if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

require_once __DIR__ . '/../models/model_pedido.php';
require_once __DIR__ . '/../models/model_detalle_pedido.php';

try {
    $id = isset($_GET['id_pedido']) ? (int)$_GET['id_pedido'] : 0;
    if ($id <= 0) {
        echo json_encode(['success' => false, 'message' => 'ID inválido']);
        exit;
    }

    $pedidoModel = new Pedido();
    $detalleModel = new DetallePedido();

    $pedido = $pedidoModel->getPedidoById($id);
    if (!$pedido) {
        echo json_encode(['success' => false, 'message' => 'Pedido no encontrado']);
        exit;
    }

    $lineas = $detalleModel->getDetallesByPedidoId($id);
    $totalLineas = 0.0;
    foreach ($lineas as $r) {
        $totalLineas += (float)$r['total_linea'];
    }

    echo json_encode([
        'success' => true,
        'pedido' => $pedido,
        'lineas' => $lineas,
        'total_lineas' => $totalLineas,
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error del servidor']);
}
