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

require_once "../vendor/autoload.php";
use Dompdf\Dompdf;

$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to'] ?? date('Y-m-d');
$customer_id = $_GET['customer_id'] ?? '';
$itemWise = $_GET['itemwise'] ?? 0;
$hsnWise  = $_GET['hsnwise'] ?? 0;

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

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

$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; }
.total-box { margin-top:15px; padding:10px; border:1px solid #000; }
</style>

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

$totalTaxable = 0;
$totalGST = 0;
$totalCGST = 0;
$totalSGST = 0;
$totalNet = 0;

if ($hsnWise) {

    $html .= "<table>
        <thead>
            <tr>
                <th>HSN Code</th>
                <th>GST %</th>
                <th>Taxable</th>
                <th>CGST</th>
                <th>SGST</th>
                <th>Total GST</th>
            </tr>
        </thead><tbody>";

    $sql = "
        SELECT 
            p.hsn_code,
            s.gst_percent,
            SUM(s.taxable_amount) AS taxable_total,
            SUM(s.gst_amount) AS gst_total
        FROM sales_items s
        JOIN sales_invoices si ON si.id = s.sales_invoice_id
        JOIN products p ON p.id = s.product_id
        $where
        GROUP BY p.hsn_code, s.gst_percent
        ORDER BY p.hsn_code ASC
    ";

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

    while($row = $res->fetch_assoc()) {
        $cgst = $row['gst_total']/2;
        $sgst = $row['gst_total']/2;

        $totalTaxable += $row['taxable_total'];
        $totalGST += $row['gst_total'];
        $totalCGST += $cgst;
        $totalSGST += $sgst;

        $html .= "<tr>
            <td>{$row['hsn_code']}</td>
            <td>{$row['gst_percent']}%</td>
            <td>".number_format($row['taxable_total'],2)."</td>
            <td>".number_format($cgst,2)."</td>
            <td>".number_format($sgst,2)."</td>
            <td><b>".number_format($row['gst_total'],2)."</b></td>
        </tr>";
    }

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

} elseif ($itemWise) {

    $html .= "<table>
        <thead>
            <tr>
                <th>Invoice No</th>
                <th>Date</th>
                <th>Customer</th>
                <th>Product</th>
                <th>HSN</th>
                <th>Qty</th>
                <th>Taxable</th>
                <th>GST%</th>
                <th>CGST</th>
                <th>SGST</th>
                <th>Total GST</th>
                <th>Total</th>
            </tr>
        </thead><tbody>";

    $sql = "
        SELECT 
            si.invoice_no,
            si.invoice_date,
            c.name AS customer_name,
            p.name AS product_name,
            p.hsn_code,
            s.sold_qty,
            s.taxable_amount,
            s.gst_percent,
            s.gst_amount,
            (s.taxable_amount + s.gst_amount) AS total_amount
        FROM sales_items s
        JOIN sales_invoices si ON si.id = s.sales_invoice_id
        JOIN clients c ON c.id = si.client_id
        JOIN products p ON p.id = s.product_id
        $where
        ORDER BY si.id DESC
    ";

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

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

        $cgst = $row['gst_amount']/2;
        $sgst = $row['gst_amount']/2;

        $totalTaxable += $row['taxable_amount'];
        $totalGST += $row['gst_amount'];
        $totalCGST += $cgst;
        $totalSGST += $sgst;
        $totalNet += $row['total_amount'];

        $html .= "<tr>
            <td>{$row['invoice_no']}</td>
            <td>{$row['invoice_date']}</td>
            <td>{$row['customer_name']}</td>
            <td>{$row['product_name']}</td>
            <td>{$row['hsn_code']}</td>
            <td>{$row['sold_qty']}</td>
            <td>".number_format($row['taxable_amount'],2)."</td>
            <td>{$row['gst_percent']}%</td>
            <td>".number_format($cgst,2)."</td>
            <td>".number_format($sgst,2)."</td>
            <td>".number_format($row['gst_amount'],2)."</td>
            <td><b>".number_format($row['total_amount'],2)."</b></td>
        </tr>";
    }

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

} else {

    $html .= "<table>
        <thead>
            <tr>
                <th>Invoice No</th>
                <th>Date</th>
                <th>Customer</th>
                <th>Taxable</th>
                <th>CGST</th>
                <th>SGST</th>
                <th>Total GST</th>
                <th>Net Total</th>
            </tr>
        </thead><tbody>";

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

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

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

        $cgst = $row['total_gst']/2;
        $sgst = $row['total_gst']/2;

        $totalTaxable += $row['total_taxable'];
        $totalGST += $row['total_gst'];
        $totalCGST += $cgst;
        $totalSGST += $sgst;
        $totalNet += $row['net_total'];

        $html .= "<tr>
            <td>{$row['invoice_no']}</td>
            <td>{$row['invoice_date']}</td>
            <td>{$row['customer_name']}</td>
            <td>".number_format($row['total_taxable'],2)."</td>
            <td>".number_format($cgst,2)."</td>
            <td>".number_format($sgst,2)."</td>
            <td><b>".number_format($row['total_gst'],2)."</b></td>
            <td><b>".number_format($row['net_total'],2)."</b></td>
        </tr>";
    }

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

$html .= "
<div class='total-box'>
<b>Total Taxable:</b> ₹ ".number_format($totalTaxable,2)."<br>
<b>Total CGST:</b> ₹ ".number_format($totalCGST,2)."<br>
<b>Total SGST:</b> ₹ ".number_format($totalSGST,2)."<br>
<b>Total GST:</b> ₹ ".number_format($totalGST,2)."<br>
<b>Net Total:</b> ₹ ".number_format($totalNet,2)."
</div>
";

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

$fileName = "gst_report_" . date("YmdHis") . ".pdf";

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