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

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

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=gstr1_" . $mode . "_" . $from . "_to_" . $to . ".xls");
header("Pragma: no-cache");
header("Expires: 0");

echo "<table border='1'>";

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

    echo "<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>Invoice 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 si.company_id = ?
          AND c.gstin IS NOT NULL
          AND c.gstin != ''
        ORDER BY c.gstin, si.invoice_date
    ";

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

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

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

}

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

    echo "<tr>
            <th>Total Invoices</th>
            <th>Taxable</th>
            <th>CGST</th>
            <th>SGST</th>
            <th>Total GST</th>
            <th>Total Sales</th>
          </tr>";

    $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 si.company_id = ?
          AND (c.gstin IS NULL OR c.gstin = '')
    ";

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

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

    echo "<tr>
        <td>{$row['invoice_count']}</td>
        <td>{$row['taxable_total']}</td>
        <td>".number_format($cgst,2)."</td>
        <td>".number_format($sgst,2)."</td>
        <td>{$row['gst_total']}</td>
        <td>{$row['net_total']}</td>
    </tr>";
}

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

    echo "<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'
          AND si.company_id = ?
        GROUP BY p.hsn_code, p.name
        ORDER BY p.hsn_code
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssi", $from, $to, $cid);
    $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'];

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

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

    echo "<tr>
            <th>Total Final Invoices</th>
            <th>Invoice Series From</th>
            <th>Invoice Series To</th>
          </tr>";

    $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'
          AND company_id = ?
    ";

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

    echo "<tr>
        <td>{$row['total_invoices']}</td>
        <td>{$row['from_no']}</td>
        <td>{$row['to_no']}</td>
    </tr>";
}

echo "</table>";
exit;