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

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

require_once '../services/pdo_connection.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; }

  $db = (new Database())->getConnection();

  $sql = "SELECT id_detalle, id_producto, titulo_producto, cantidad, precio_unitario, total_linea
          FROM detalle_pedido
          WHERE id_pedido = :id
          ORDER BY id_detalle ASC";
  $st = $db->prepare($sql);
  $st->bindValue(':id', $id, PDO::PARAM_INT);
  $st->execute();
  $rows = $st->fetchAll(PDO::FETCH_ASSOC);

  $total = 0;
  foreach ($rows as $r) $total += (float)$r['total_linea'];

  echo json_encode(['success'=>true, 'data'=>$rows, 'total'=>$total], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
  echo json_encode(['success'=>false,'message'=>'Error del servidor']); 
}
