<?php
require(__DIR__ . '/fpdf/fpdf.php');

$conn = new mysqli("localhost", "root", "Arbolito123.", "conticket");

if ($conn->connect_error) {
    die("Conexión fallida: " . $conn->connect_error);
}

$sqlTotalesArtistas = "
    SELECT a.artista, COUNT(v.id) as total_boletos, SUM(v.precio) as total_precio 
    FROM ventas v
    JOIN asientos a ON v.asiento_id = a.id
    GROUP BY a.artista
";
$resultTotalesArtistas = $conn->query($sqlTotalesArtistas);

$sqlTotalGeneral = "
    SELECT COUNT(v.id) as total_boletos, SUM(v.precio) as total_precio 
    FROM ventas v
";
$resultTotalGeneral = $conn->query($sqlTotalGeneral);
$totalGeneral = $resultTotalGeneral->fetch_assoc();

$sqlVentas = "
    SELECT a.artista, v.fecha_venta, a.asiento, v.precio
    FROM ventas v
    JOIN asientos a ON v.asiento_id = a.id
";
$resultVentas = $conn->query($sqlVentas);

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(190, 10, 'Reporte de Ventas', 0, 1, 'C');
$pdf->Ln(5);

$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(190, 8, "Total de boletos vendidos: " . $totalGeneral["total_boletos"], 0, 1, 'L');
$pdf->Cell(190, 8, "Monto total: $" . number_format($totalGeneral["total_precio"], 2), 0, 1, 'L');
$pdf->Ln(5);

$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(190, 8, "Total por Artista:", 0, 1, 'L');
$pdf->SetFont('Arial', '', 12);

while ($row = $resultTotalesArtistas->fetch_assoc()) {
    $pdf->Cell(190, 8, "- " . $row["artista"] . ": " . $row["total_boletos"] . " boletos | $" . number_format($row["total_precio"], 2), 0, 1, 'L');
}
$pdf->Ln(5);

$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(50, 8, 'Artista', 1, 0, 'C');
$pdf->Cell(40, 8, 'Fecha de Venta', 1, 0, 'C');
$pdf->Cell(30, 8, 'Asiento', 1, 0, 'C');
$pdf->Cell(30, 8, 'Precio', 1, 1, 'C');

$pdf->SetFont('Arial', '', 12);
while ($row = $resultVentas->fetch_assoc()) {
    $pdf->Cell(50, 8, $row["artista"], 1, 0, 'C');
    $pdf->Cell(40, 8, $row["fecha_venta"], 1, 0, 'C');
    $pdf->Cell(30, 8, $row["asiento"], 1, 0, 'C');
    $pdf->Cell(30, 8, "$" . number_format($row["precio"], 2), 1, 1, 'C');
}

$pdf->Output();

$conn->close();
?>