<?php
require_once('tcpdf-main/tcpdf.php');
include 'db.php';

// Get filters
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$department = $_GET['department'] ?? '';
$product = $_GET['product'] ?? '';

// Build WHERE
$where = "WHERE 1=1";
if($date_from != '') $where .= " AND DATE(pd.dispatched_at) >= '$date_from'";
if($date_to != '') $where .= " AND DATE(pd.dispatched_at) <= '$date_to'";
if($department != '') $where .= " AND pd.department_id = '$department'";
if($product != '') $where .= " AND pp.product_name LIKE '%$product%'";

// Fetch data
$sql = "
SELECT pd.*, pp.product_name, pp.batch_number, d.name AS department
FROM perishable_dispatch pd
LEFT JOIN perishable_products pp ON pd.perishable_id = pp.id
LEFT JOIN departments d ON pd.department_id = d.id
$where
ORDER BY pd.dispatched_at DESC
";
$data = $conn->query($sql);

// Create PDF
$pdf = new TCPDF('L', PDF_UNIT, 'A4', true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Inventory System');
$pdf->SetTitle('Dispatch Report');
$pdf->SetMargins(10,20,10);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(10);
$pdf->SetAutoPageBreak(TRUE,15);
$pdf->SetFont('dejavusans','',10);
$pdf->AddPage();

$html = '<h3>Perishable Dispatch Report</h3><br>';
$html .= '<table border="1" cellpadding="4">
<thead>
<tr bgcolor="#f2f2f2">
<th>Date</th>
<th>Product</th>
<th>Batch</th>
<th>Department</th>
<th>Quantity</th>
<th>Collected By</th>
<th>Issued By</th>
</tr>
</thead><tbody>';

while($row = $data->fetch_assoc()){
    $html .= '<tr>
    <td>'.date('Y-m-d', strtotime($row['dispatched_at'])).'</td>
    <td>'.htmlspecialchars($row['product_name']).'</td>
    <td>'.$row['batch_number'].'</td>
    <td>'.$row['department'].'</td>
    <td>'.$row['quantity'].'</td>
    <td>'.$row['collected_by'].'</td>
    <td>'.$row['dispatched_by'].'</td>
    </tr>';
}

$html .= '</tbody></table>';

// Output PDF
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('dispatch_report.pdf','I');
?>