<?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');
$mode = $_GET['mode'] ?? 'b2b';

$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:5px; font-size:11px; }
    th { background:#f2f2f2; }
</style>

<h2>GSTR-1 Report (" . strtoupper($mode) . ")</h2>
<p><b>From:</b> $from &nbsp;&nbsp; <b>To:</b> $to</p>
<br>
";

if ($mode === "b2b") {

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

    $sql = "
        SELECT 
            c.gstin,
            c.name AS customer_name,
            si.invoice_no,
            si.invoice_date,
            si.total_taxable,
            si.total_gst,
            si.net_total
        FROM sales_invoices si
        JOIN clients c ON c.id = si.client_id
        WHERE si.invoice_date BETWEEN ? AND ?
          AND si.status = 'final'
          AND c.gstin IS NOT NULL
          AND c.gstin != ''
        ORDER BY c.gstin, si.invoice_date
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $from, $to);
    $stmt->execute();
    $res = $stmt->get_result();

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

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

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

elseif ($mode === "b2c") {

    $sql = "
        SELECT 
            COUNT(si.id) AS invoice_count,
            SUM(si.total_taxable) AS taxable_total,
            SUM(si.total_gst) AS gst_total,
            SUM(si.net_total) AS net_total
        FROM sales_invoices si
        JOIN clients c ON c.id = si.client_id
        WHERE si.invoice_date BETWEEN ? AND ?
          AND si.status = 'final'
          AND (c.gstin IS NULL OR c.gstin = '')
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $from, $to);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();

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

    $html .= "
    <table>
        <tr>
            <th>Total Invoices</th>
            <th>Taxable</th>
            <th>CGST</th>
            <th>SGST</th>
            <th>Total GST</th>
            <th>Total Sales</th>
        </tr>
        <tr>
            <td>{$row['invoice_count']}</td>
            <td>".number_format($row['taxable_total'],2)."</td>
            <td>".number_format($cgst,2)."</td>
            <td>".number_format($sgst,2)."</td>
            <td>".number_format($row['gst_total'],2)."</td>
            <td><b>".number_format($row['net_total'],2)."</b></td>
        </tr>
    </table>";
}

elseif ($mode === "hsn") {

    $html .= "
    <table>
        <tr>
            <th>HSN Code</th>
            <th>Product</th>
            <th>Total Qty</th>
            <th>Taxable</th>
            <th>CGST</th>
            <th>SGST</th>
            <th>Total GST</th>
            <th>Total</th>
        </tr>";

    $sql = "
        SELECT 
            p.hsn_code,
            p.name AS product_name,
            SUM(s.sold_qty) AS total_qty,
            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 si.invoice_date BETWEEN ? AND ?
          AND si.status = 'final'
        GROUP BY p.hsn_code, p.name
        ORDER BY p.hsn_code
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $from, $to);
    $stmt->execute();
    $res = $stmt->get_result();

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

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

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

elseif ($mode === "docs") {

    $sql = "
        SELECT 
            COUNT(*) AS total_invoices,
            MIN(invoice_no) AS from_no,
            MAX(invoice_no) AS to_no
        FROM sales_invoices
        WHERE invoice_date BETWEEN ? AND ?
          AND status = 'final'
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $from, $to);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();

    $html .= "
    <table>
        <tr>
            <th>Total Final Invoices</th>
            <th>Invoice Series From</th>
            <th>Invoice Series To</th>
        </tr>
        <tr>
            <td>{$row['total_invoices']}</td>
            <td>{$row['from_no']}</td>
            <td>{$row['to_no']}</td>
        </tr>
    </table>";
}

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

$filename = "gstr1_" . $mode . "_" . $from . "_to_" . $to . ".pdf";

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