<?php
require 'dompdf/vendor/autoload.php';
include 'db.php';

use Dompdf\Dompdf;

$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to'] ?? date('Y-m-d');

$html = "
<h2 style='text-align:center;'>Restaurant Sales Report</h2>
<p><strong>Date Range:</strong> $from to $to</p>

<table border='1' width='100%' cellpadding='6' cellspacing='0'>
<tr>
<th>#</th>
<th>Order ID</th>
<th>Date</th>
<th>Total</th>
<th>Paid</th>
<th>Balance</th>
<th>Status</th>
</tr>
";

$i=1;

$orders = $conn->query("
SELECT *
FROM restaurant_orders
WHERE DATE(created_at) BETWEEN '$from' AND '$to'
ORDER BY created_at DESC
");

while($o=$orders->fetch_assoc()){

    $items = $conn->query("
    SELECT price,qty
    FROM restaurant_order_items
    WHERE order_id=".$o['id']
    );

    $total=0;

    while($it=$items->fetch_assoc()){
        $total += $it['price']*$it['qty'];
    }

    $paid = ($o['status']=='PAID' ? $o['grand_total'] : 0);
    $balance = $total - $paid;

$html .= "
<tr>
<td>$i</td>
<td>{$o['id']}</td>
<td>{$o['created_at']}</td>
<td>".number_format($total,2)." MK</td>
<td>".number_format($paid,2)." MK</td>
<td>".number_format($balance,2)." MK</td>
<td>{$o['status']}</td>
</tr>";

$i++;
}

$html .= "</table>";

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4','landscape');
$dompdf->render();
$dompdf->stream("Restaurant_Sales_Report.pdf");
?>