<?php
require_once '../includes/auth.php';
require_once '../db.php';

require_once "../vendors/dompdf/autoload.inc.php";
use Dompdf\Dompdf;

$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to'] ?? date('Y-m-d');
$vendor_id = $_GET['vendor_id'] ?? '';
$status    = $_GET['status']    ?? 'final';
$itemWise = isset($_GET['itemwise']) ? 1 : 0;
$search = trim($_GET['search'] ?? '');

$where = " WHERE po.purchase_date BETWEEN ? AND ? AND po.company_id = ? ";
$params = [$from, $to, $cid];
$types = "ssi";

if ($status !== 'all') { $where .= " AND po.status = ? "; $params[] = $status; $types .= "s"; }

if (!empty($vendor_id)) {
    $where .= " AND po.vendor_id = ? ";
    $params[] = $vendor_id;
    $types .= "i";
}

if (!empty($search)) {
    $where .= " AND (po.po_no LIKE ? OR v.name LIKE ? OR po.supplier_invoice_no LIKE ?) ";
    $like = "%$search%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types .= "sss";
}

$html = "
<style>
body { font-family: DejaVu Sans, sans-serif; font-size: 11px; }
h2 { text-align:center; margin-bottom:5px; }
p { text-align:center; margin:0; font-size: 11px; }
table { width:100%; border-collapse: collapse; margin-top:10px; }
th, td { border: 1px solid #000; padding: 5px; font-size: 10px; }
th { background: #f2f2f2; }
</style>

<h2>Purchase Report</h2>
<p>From: $from | To: $to</p>
";

if ($itemWise) {

    $html .= "<table>
        <thead>
            <tr>
                <th>PO No</th>
                <th>Supplier Invoice</th>
                <th>Date</th>
                <th>Vendor</th>
                <th>Status</th>
                <th>Product</th>
                <th>Brand</th>
                <th>HSN</th>
                <th>Unit</th>
                <th>Batch</th>
                <th>MRP</th>
                <th>Purchase</th>
                <th>Selling</th>
                <th>Qty</th>
                <th>Avail</th>
                <th>GST%</th>
                <th>Expiry</th>
            </tr>
        </thead>
        <tbody>
    ";

    $sql = "
        SELECT 
            po.po_no,
            po.supplier_invoice_no,
            po.purchase_date,
            po.status,
            v.name AS vendor_name,
            pi.batch_no,
            pi.mrp,
            pi.purchase_price,
            pi.selling_price,
            pi.quantity,
            pi.available_qty,
            pi.gst_percent,
            pi.expiry_date,
            p.name AS product_name,
            p.brand,
            p.hsn_code,
            p.unit
        FROM purchase_orders po
        JOIN vendors v ON v.id = po.vendor_id
        JOIN purchase_items pi ON pi.purchase_order_id = po.id
        JOIN products p ON p.id = pi.product_id
        $where
        ORDER BY po.id DESC
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {

        $html .= "<tr>
            <td>{$row['po_no']}</td>
            <td>".($row['supplier_invoice_no'] ?? '-')."</td>
            <td>{$row['purchase_date']}</td>
            <td>{$row['vendor_name']}</td>
            <td>{$row['status']}</td>
            <td>{$row['product_name']}</td>
            <td>{$row['brand']}</td>
            <td>{$row['hsn_code']}</td>
            <td>{$row['unit']}</td>
            <td>{$row['batch_no']}</td>
            <td>".number_format($row['mrp'],2)."</td>
            <td>".number_format($row['purchase_price'],2)."</td>
            <td>".number_format($row['selling_price'],2)."</td>
            <td>{$row['quantity']}</td>
            <td>{$row['available_qty']}</td>
            <td>{$row['gst_percent']}</td>
            <td>".($row['expiry_date'] ?? '-')."</td>
        </tr>";
    }

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

} else {

    $html .= "<table>
        <thead>
            <tr>
                <th>PO No</th>
                <th>Supplier Invoice</th>
                <th>Date</th>
                <th>Vendor</th>
                <th>Status</th>
                <th>Total</th>
                <th>GST</th>
                <th>Net</th>
            </tr>
        </thead>
        <tbody>
    ";

    $sql = "
        SELECT po.*, v.name AS vendor_name
        FROM purchase_orders po
        JOIN vendors v ON v.id = po.vendor_id
        $where
        ORDER BY po.id DESC
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {

        $html .= "<tr>
            <td>{$row['po_no']}</td>
            <td>".($row['supplier_invoice_no'] ?? '-')."</td>
            <td>{$row['purchase_date']}</td>
            <td>{$row['vendor_name']}</td>
            <td>{$row['status']}</td>
            <td>".number_format($row['total_amount'],2)."</td>
            <td>".number_format($row['gst_amount'],2)."</td>
            <td>".number_format($row['net_amount'],2)."</td>
        </tr>";
    }

    $html .= "</tbody></table>";
}

/* Generate PDF */
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper("A4", "landscape"); // landscape because many columns
$dompdf->render();

$pdfFileName = "purchase_report_" . date("YmdHis") . ".pdf";

header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=$pdfFileName");
echo $dompdf->output();
exit;
