<?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');
$status = $_GET['status'] ?? 'final';
$search = trim($_GET['search'] ?? '');

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

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

if (!empty($search)) {
    $where .= " AND (si.invoice_no LIKE ? OR c.name LIKE ? OR c.phone LIKE ?) ";
    $like = "%$search%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types .= "sss";
}

$sql = "
    SELECT 
        si.invoice_date,
        si.invoice_no,
        c.name AS customer_name,
        c.phone AS customer_phone,
        si.gross_total,
        si.total_taxable,
        si.total_gst,
        si.net_total,
        si.received_amount,
        si.balance_amount,
        si.status
    FROM sales_invoices si
    JOIN clients c ON c.id = si.client_id
    $where
    ORDER BY si.invoice_date DESC, si.id DESC
";

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

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

<h2>Sales Report</h2>
<p><b>From:</b> $from &nbsp;&nbsp; <b>To:</b> $to &nbsp;&nbsp; <b>Status:</b> $status</p>

<table>
<tr>
    <th>Date</th>
    <th>Invoice No</th>
    <th>Customer</th>
    <th>Phone</th>
    <th>Gross</th>
    <th>Taxable</th>
    <th>GST</th>
    <th>Net</th>
    <th>Received</th>
    <th>Balance</th>
    <th>Status</th>
</tr>
";

while ($row = $result->fetch_assoc()) {
    $html .= "<tr>
        <td>{$row['invoice_date']}</td>
        <td>{$row['invoice_no']}</td>
        <td>{$row['customer_name']}</td>
        <td>{$row['customer_phone']}</td>
        <td class='r'>".number_format($row['gross_total'],2)."</td>
        <td class='r'>".number_format($row['total_taxable'],2)."</td>
        <td class='r'>".number_format($row['total_gst'],2)."</td>
        <td class='r'><b>".number_format($row['net_total'],2)."</b></td>
        <td class='r'>".number_format($row['received_amount'],2)."</td>
        <td class='r'>".number_format($row['balance_amount'],2)."</td>
        <td>".strtoupper($row['status'])."</td>
    </tr>";
}

$html .= "</table>";

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();

$pdfName = "sales_report_{$from}_to_{$to}.pdf";
$dompdf->stream($pdfName, ["Attachment" => true]);
exit;
