<?php
require_once '../includes/config.php';
require_once '../includes/fpdf/fpdf.php';
if (!isLoggedIn() || !isAdmin()) redirect('login.php');
$reserva_id = (int)($_GET['reserva_id'] ?? 0);
if (!$reserva_id) redirect('reservas.php');
$db = getDBConnection();
$stmt = $db->prepare("
    SELECT r.*, u.nombre_completo, u.cedula_pasaporte, t.nombre as tarifa_nombre
    FROM reservas r
    JOIN usuarios u ON r.usuario_id = u.id
    JOIN tarifas t ON r.tarifa_id = t.id
    WHERE r.id = ?
");
$stmt->execute([$reserva_id]);
$reserva = $stmt->fetch();
if (!$reserva) redirect('reservas.php');
$stmt = $db->prepare("
    SELECT c.*, p.nombre as producto_nombre
    FROM consumos c
    JOIN productos p ON c.producto_id = p.id
    WHERE c.reserva_id = ?
    ORDER BY c.fecha_consumo
");
$stmt->execute([$reserva_id]);
$consumos = $stmt->fetchAll();
$total_consumos = array_sum(array_column($consumos, 'subtotal'));
$total_general = $reserva['costo_hospedaje'] + $total_consumos;
class PDF extends FPDF {
    function Header() {
        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 10, 'DETALLE DE GASTOS', 0, 1, 'C');
        $this->Ln(5);
    }
}
$pdf = new PDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, 'Reserva #' . str_pad($reserva['id'], 6, '0', STR_PAD_LEFT), 0, 1);
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(0, 6, 'Huesped: ' . utf8_decode($reserva['nombre_completo']), 0, 1);
$pdf->Cell(0, 6, 'CI/Pasaporte: ' . $reserva['cedula_pasaporte'], 0, 1);
$pdf->Cell(0, 6, 'Entrada: ' . date('d/m/Y', strtotime($reserva['fecha_entrada'])), 0, 1);
$pdf->Cell(0, 6, 'Salida: ' . date('d/m/Y', strtotime($reserva['fecha_salida'])), 0, 1);
$pdf->Ln(5);
$pdf->SetFont('Arial', 'B', 11);
$pdf->Cell(0, 8, 'COSTO DE HOSPEDAJE', 0, 1);
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(100, 6, utf8_decode($reserva['tarifa_nombre']), 0, 0);
$pdf->Cell(0, 6, 'Gs. ' . number_format($reserva['costo_hospedaje'], 0, ',', '.'), 0, 1, 'R');
$pdf->Ln(5);
if (!empty($consumos)) {
    $pdf->SetFont('Arial', 'B', 11);
    $pdf->Cell(0, 8, 'CONSUMOS', 0, 1);
    $pdf->SetFont('Arial', '', 9);
    foreach ($consumos as $c) {
        $pdf->Cell(80, 5, utf8_decode($c['producto_nombre']), 0, 0);
        $pdf->Cell(20, 5, 'x' . $c['cantidad'], 0, 0, 'C');
        $pdf->Cell(0, 5, 'Gs. ' . number_format($c['subtotal'], 0, ',', '.'), 0, 1, 'R');
    }
    $pdf->Ln(3);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(100, 6, 'TOTAL CONSUMOS:', 0, 0);
    $pdf->Cell(0, 6, 'Gs. ' . number_format($total_consumos, 0, ',', '.'), 0, 1, 'R');
}
$pdf->Ln(5);
$pdf->SetFont('Arial', 'B', 14);
$pdf->SetFillColor(45, 80, 22);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 10, 'TOTAL GENERAL: Gs. ' . number_format($total_general, 0, ',', '.'), 1, 1, 'C', true);
$pdf->Output('D', 'Detalle_Gastos_' . $reserva_id . '.pdf');
