<?php
include 'includes/auth.php';
include 'db.php';
require_once('tcpdf-main/tcpdf.php'); // path to TCPDF

// ================= GET FILTERS =================
$from_date   = $_GET['from'] ?? '';
$to_date     = $_GET['to'] ?? '';
$type        = $_GET['type'] ?? '';
$min_amount  = $_GET['min_amount'] ?? '';
$max_amount  = $_GET['max_amount'] ?? '';

$where = [];
if($from_date) $where[] = "DATE(payment_date) >= '".$conn->real_escape_string($from_date)."'";
if($to_date)   $where[] = "DATE(payment_date) <= '".$conn->real_escape_string($to_date)."'";
if($type)      $where[] = "type = '".$conn->real_escape_string($type)."'";
if($min_amount !== '') $where[] = "amount >= ".floatval($min_amount);
if($max_amount !== '') $where[] = "amount <= ".floatval($max_amount);

$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ================= FETCH DATA =================
$audit = $conn->query("
    SELECT 
        DATE(payment_date) AS date, 
        SUM(amount) AS total_income,
        SUM(CASE WHEN type='Cash' THEN amount ELSE 0 END) AS cash_total,
        SUM(CASE WHEN type='Card' THEN amount ELSE 0 END) AS card_total
    FROM payments
    $where_sql
    GROUP BY DATE(payment_date)
    ORDER BY date DESC
");

// ================= CREATE PDF =================
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Front Office');
$pdf->SetTitle('Night Audit Report');
$pdf->SetMargins(15, 15, 15);
$pdf->AddPage();

// Title
$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0,10,'Night Audit Report',0,1,'C');
$pdf->Ln(5);

// Table header
$pdf->SetFont('helvetica','B',12);
$pdf->SetFillColor(50,50,50);
$pdf->SetTextColor(255,255,255);
$pdf->Cell(40,8,'Date',1,0,'C',1);
$pdf->Cell(50,8,'Total Income (MK)',1,0,'C',1);
$pdf->Cell(40,8,'Cash (MK)',1,0,'C',1);
$pdf->Cell(40,8,'Card (MK)',1,1,'C',1);

// Table body
$pdf->SetFont('helvetica','',11);
$pdf->SetTextColor(0,0,0);

$overall_total = 0;
$overall_cash  = 0;
$overall_card  = 0;

while($row = $audit->fetch_assoc()){
    $date  = $row['date'];
    $total = $row['total_income'];
    $cash  = $row['cash_total'];
    $card  = $row['card_total'];

    $overall_total += $total;
    $overall_cash  += $cash;
    $overall_card  += $card;

    $pdf->Cell(40,8,$date,1,0,'C');
    $pdf->Cell(50,8,number_format($total,2),1,0,'R');
    $pdf->Cell(40,8,number_format($cash,2),1,0,'R');
    $pdf->Cell(40,8,number_format($card,2),1,1,'R');
}

// Footer totals
$pdf->SetFont('helvetica','B',12);
$pdf->Cell(40,8,'Overall Totals',1,0,'C');
$pdf->Cell(50,8,number_format($overall_total,2),1,0,'R');
$pdf->Cell(40,8,number_format($overall_cash,2),1,0,'R');
$pdf->Cell(40,8,number_format($overall_card,2),1,1,'R');

// Output PDF
$pdf->Output('night_audit.pdf','I');
exit;