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

// Fetch all damaged goods
$damaged = $conn->query("
    SELECT dg.*, p.name AS product_name, p.sku, d.name AS dept_name 
    FROM damaged_goods dg
    JOIN products p ON dg.product_id = p.id
    JOIN departments d ON dg.department_id = d.id
    ORDER BY dg.reported_at DESC
");

// Create new PDF
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Inventory System');
$pdf->SetTitle('Damaged Goods Report');
$pdf->SetMargins(10, 10, 10);
$pdf->AddPage();

$html = '<h3>Damaged Goods Report</h3>';
$html .= '<table border="1" cellpadding="4">
            <tr style="background-color:#f2f2f2;">
                <th>Product</th>
                <th>SKU</th>
                <th>Department</th>
                <th>Qty</th>
                <th>Reason</th>
                <th>Reported By</th>
                <th>Reported At</th>
            </tr>';

while($row = $damaged->fetch_assoc()){
    $html .= '<tr>
                <td>'.htmlspecialchars($row['product_name']).'</td>
                <td>'.$row['sku'].'</td>
                <td>'.htmlspecialchars($row['dept_name']).'</td>
                <td>'.$row['quantity'].'</td>
                <td>'.htmlspecialchars($row['reason']).'</td>
                <td>'.htmlspecialchars($row['reported_by']).'</td>
                <td>'.date('Y-m-d H:i', strtotime($row['reported_at'])).'</td>
              </tr>';
}
$html .= '</table>';

// Output PDF
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('damaged_goods_'.date('Y-m-d').'.pdf', 'D');
exit;
?>