<?php
require_once '../includes/auth.php';
requirePermission('reports_gstr1', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

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

$rows = [];
$totalTaxable = 0;
$totalGST = 0;
$totalNet = 0;

if ($mode === "b2b") {
    $sql = "
        SELECT si.id, 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()) {
        $totalTaxable += $row['total_taxable'];
        $totalGST += $row['total_gst'];
        $totalNet += $row['net_total'];
        $rows[] = $row;
    }
} 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 si.company_id = ?
          AND (c.gstin IS NULL OR c.gstin = '')
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssi", $from, $to, $cid);
    $stmt->execute();
    $rows[] = $stmt->get_result()->fetch_assoc();
} elseif ($mode === "hsn") {
    $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()) { $rows[] = $row; }
} 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' AND company_id = ?
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssi", $from, $to, $cid);
    $stmt->execute();
    $rows[] = $stmt->get_result()->fetch_assoc();
} elseif ($mode === "all") {
    // B2B
    $stmt = $conn->prepare("SELECT si.id, 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->bind_param("ssi", $from, $to, $cid);
    $stmt->execute();
    $allB2B = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    // B2C
    $stmt = $conn->prepare("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->bind_param("ssi", $from, $to, $cid);
    $stmt->execute();
    $allB2C = $stmt->get_result()->fetch_assoc();
    // HSN
    $stmt = $conn->prepare("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->bind_param("ssi", $from, $to, $cid);
    $stmt->execute();
    $allHSN = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    // Docs
    $stmt = $conn->prepare("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->bind_param("ssi", $from, $to, $cid);
    $stmt->execute();
    $allDocs = $stmt->get_result()->fetch_assoc();
}

$modeLabels = ['b2b'=>'B2B (GSTIN Wise)', 'b2c'=>'B2C Summary', 'hsn'=>'HSN Summary', 'docs'=>'Document Summary', 'all'=>'All Sections'];
?>

<div class="page-header">
    <h2><i class="fas fa-file-invoice" style="color:var(--primary);margin-right:8px;"></i>GSTR-1 Report</h2>
    <div style="display:flex;gap:8px;">
        <a href="gstr1_export_excel.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&mode=<?= urlencode($mode) ?>"
           target="_blank" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</a>
        <a href="gstr1_export_pdf.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&mode=<?= urlencode($mode) ?>"
           target="_blank" class="btn btn-danger btn-sm"><i class="fas fa-file-pdf"></i> PDF</a>
    </div>
</div>

<!-- Filters -->
<div class="filter-panel">
    <form method="GET" class="filter-form">
        <div class="filter-group">
            <label>From</label>
            <input type="date" name="from" value="<?= htmlspecialchars($from) ?>">
        </div>
        <div class="filter-group">
            <label>To</label>
            <input type="date" name="to" value="<?= htmlspecialchars($to) ?>">
        </div>
        <div class="filter-group">
            <label>Report Type</label>
            <select name="mode">
                <option value="b2b" <?= ($mode=='b2b')?'selected':'' ?>>B2B (GSTIN Wise)</option>
                <option value="b2c" <?= ($mode=='b2c')?'selected':'' ?>>B2C Summary</option>
                <option value="hsn" <?= ($mode=='hsn')?'selected':'' ?>>HSN Summary</option>
                <option value="docs" <?= ($mode=='docs')?'selected':'' ?>>Document Summary</option>
                <option value="all" <?= ($mode=='all')?'selected':'' ?>>All Sections (Combined)</option>
            </select>
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Generate</button>
            <a href="gstr1_report.php" class="btn btn-secondary">Reset</a>
        </div>
    </form>
</div>

<?php if($mode === 'b2b' && count($rows) > 0): ?>
<!-- B2B Summary -->
<div class="stat-cards">
    <div class="stat-card">
        <div class="stat-card-label">Taxable Amount</div>
        <div class="stat-card-value" style="color:var(--primary);">&#8377; <?= number_format($totalTaxable, 2) ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-label">Total GST</div>
        <div class="stat-card-value" style="color:var(--warning);">&#8377; <?= number_format($totalGST, 2) ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-label">Total Sales</div>
        <div class="stat-card-value" style="color:var(--success);">&#8377; <?= number_format($totalNet, 2) ?></div>
    </div>
</div>
<?php endif; ?>

<?php if($mode !== 'all'): ?>
<!-- Single-mode Table -->
<div class="panel">
    <?php if(!empty($modeLabels[$mode])): ?>
    <div class="panel-header">
        <span class="panel-title"><?= $modeLabels[$mode] ?></span>
    </div>
    <?php endif; ?>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <?php if($mode === 'b2b'): ?>
                <tr>
                    <th>GSTIN</th><th>Customer</th><th>Invoice No</th><th>Date</th>
                    <th style="text-align:right;">Taxable</th>
                    <th style="text-align:right;">CGST</th>
                    <th style="text-align:right;">SGST</th>
                    <th style="text-align:right;">Total GST</th>
                    <th style="text-align:right;">Invoice Total</th>
                </tr>
                <?php elseif($mode === 'b2c'): ?>
                <tr>
                    <th style="text-align:center;">Total Invoices</th>
                    <th style="text-align:right;">Taxable</th>
                    <th style="text-align:right;">CGST</th>
                    <th style="text-align:right;">SGST</th>
                    <th style="text-align:right;">Total GST</th>
                    <th style="text-align:right;">Total Sales</th>
                </tr>
                <?php elseif($mode === 'hsn'): ?>
                <tr>
                    <th>HSN Code</th><th>Product</th>
                    <th style="text-align:center;">Total Qty</th>
                    <th style="text-align:right;">Taxable</th>
                    <th style="text-align:right;">CGST</th>
                    <th style="text-align:right;">SGST</th>
                    <th style="text-align:right;">Total GST</th>
                    <th style="text-align:right;">Total</th>
                </tr>
                <?php elseif($mode === 'docs'): ?>
                <tr>
                    <th style="text-align:center;">Total Final Invoices</th>
                    <th>Invoice Series From</th>
                    <th>Invoice Series To</th>
                </tr>
                <?php endif; ?>
            </thead>
            <tbody>
            <?php if(count($rows) > 0): ?>
                <?php foreach($rows as $row): ?>
                <tr>
                    <?php if($mode === 'b2b'): ?>
                        <td style="font-size:12px;"><?= htmlspecialchars($row['gstin']) ?></td>
                        <td><?= htmlspecialchars($row['customer_name']) ?></td>
                        <td><a href="#" onclick="openDocPopup('sale',<?= $row['id'] ?>,'<?= htmlspecialchars($row['invoice_no'],ENT_QUOTES) ?>');return false;" style="font-weight:700;color:var(--primary);text-decoration:none;"><?= htmlspecialchars($row['invoice_no']) ?></a></td>
                        <td><?= date('d-m-Y', strtotime($row['invoice_date'])) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['total_taxable'], 2) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['total_gst']/2, 2) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['total_gst']/2, 2) ?></td>
                        <td style="text-align:right;"><strong>&#8377; <?= number_format($row['total_gst'], 2) ?></strong></td>
                        <td style="text-align:right;"><strong>&#8377; <?= number_format($row['net_total'], 2) ?></strong></td>
                    <?php elseif($mode === 'b2c'): ?>
                        <td style="text-align:center;"><strong><?= $row['invoice_count'] ?></strong></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['taxable_total'], 2) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['gst_total']/2, 2) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['gst_total']/2, 2) ?></td>
                        <td style="text-align:right;"><strong>&#8377; <?= number_format($row['gst_total'], 2) ?></strong></td>
                        <td style="text-align:right;"><strong>&#8377; <?= number_format($row['net_total'], 2) ?></strong></td>
                    <?php elseif($mode === 'hsn'):
                        $total = $row['taxable_total'] + $row['gst_total'];
                    ?>
                        <td><strong><?= htmlspecialchars($row['hsn_code']) ?></strong></td>
                        <td><?= htmlspecialchars($row['product_name']) ?></td>
                        <td style="text-align:center;"><?= $row['total_qty'] ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['taxable_total'], 2) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['gst_total']/2, 2) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['gst_total']/2, 2) ?></td>
                        <td style="text-align:right;"><strong>&#8377; <?= number_format($row['gst_total'], 2) ?></strong></td>
                        <td style="text-align:right;"><strong>&#8377; <?= number_format($total, 2) ?></strong></td>
                    <?php elseif($mode === 'docs'): ?>
                        <td style="text-align:center;"><strong><?= $row['total_invoices'] ?></strong></td>
                        <td><?= htmlspecialchars($row['from_no']) ?></td>
                        <td><?= htmlspecialchars($row['to_no']) ?></td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="9" style="text-align:center;padding:40px;color:var(--text-muted);">No data found for this period.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php else: ?>
<!-- All Sections View -->

<!-- Section 1: B2B -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title">1. B2B — GSTIN Wise Invoices</span></div>
    <div style="overflow-x:auto;">
        <table>
            <thead><tr>
                <th>GSTIN</th><th>Customer</th><th>Invoice No</th><th>Date</th>
                <th style="text-align:right;">Taxable</th>
                <th style="text-align:right;">CGST</th>
                <th style="text-align:right;">SGST</th>
                <th style="text-align:right;">Total GST</th>
                <th style="text-align:right;">Invoice Total</th>
            </tr></thead>
            <tbody>
            <?php if(!empty($allB2B)): foreach($allB2B as $row): ?>
            <tr>
                <td style="font-size:12px;"><?= htmlspecialchars($row['gstin']) ?></td>
                <td><?= htmlspecialchars($row['customer_name']) ?></td>
                <td><a href="#" onclick="openDocPopup('sale',<?= $row['id'] ?>,'<?= htmlspecialchars($row['invoice_no'],ENT_QUOTES) ?>');return false;" style="font-weight:700;color:var(--primary);text-decoration:none;"><?= htmlspecialchars($row['invoice_no']) ?></a></td>
                <td><?= date('d-m-Y', strtotime($row['invoice_date'])) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['total_taxable'],2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['total_gst']/2,2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['total_gst']/2,2) ?></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($row['total_gst'],2) ?></strong></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($row['net_total'],2) ?></strong></td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="9" style="text-align:center;padding:24px;color:var(--text-muted);">No B2B invoices for this period.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Section 2: B2C -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title">2. B2C — Summary</span></div>
    <div style="overflow-x:auto;">
        <table>
            <thead><tr>
                <th style="text-align:center;">Total Invoices</th>
                <th style="text-align:right;">Taxable</th>
                <th style="text-align:right;">CGST</th>
                <th style="text-align:right;">SGST</th>
                <th style="text-align:right;">Total GST</th>
                <th style="text-align:right;">Total Sales</th>
            </tr></thead>
            <tbody><tr>
                <td style="text-align:center;"><strong><?= $allB2C['invoice_count'] ?? 0 ?></strong></td>
                <td style="text-align:right;">&#8377; <?= number_format($allB2C['taxable_total'] ?? 0,2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format(($allB2C['gst_total'] ?? 0)/2,2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format(($allB2C['gst_total'] ?? 0)/2,2) ?></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($allB2C['gst_total'] ?? 0,2) ?></strong></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($allB2C['net_total'] ?? 0,2) ?></strong></td>
            </tr></tbody>
        </table>
    </div>
</div>

<!-- Section 3: HSN -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title">3. HSN — Summary</span></div>
    <div style="overflow-x:auto;">
        <table>
            <thead><tr>
                <th>HSN Code</th><th>Product</th>
                <th style="text-align:center;">Total Qty</th>
                <th style="text-align:right;">Taxable</th>
                <th style="text-align:right;">CGST</th>
                <th style="text-align:right;">SGST</th>
                <th style="text-align:right;">Total GST</th>
                <th style="text-align:right;">Total</th>
            </tr></thead>
            <tbody>
            <?php if(!empty($allHSN)): foreach($allHSN as $row):
                $hsnTotal = $row['taxable_total'] + $row['gst_total']; ?>
            <tr>
                <td><strong><?= htmlspecialchars($row['hsn_code']) ?></strong></td>
                <td><?= htmlspecialchars($row['product_name']) ?></td>
                <td style="text-align:center;"><?= $row['total_qty'] ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['taxable_total'],2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['gst_total']/2,2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['gst_total']/2,2) ?></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($row['gst_total'],2) ?></strong></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($hsnTotal,2) ?></strong></td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="8" style="text-align:center;padding:24px;color:var(--text-muted);">No HSN data for this period.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Section 4: Docs -->
<div class="panel">
    <div class="panel-header"><span class="panel-title">4. Document Summary</span></div>
    <div style="overflow-x:auto;">
        <table>
            <thead><tr>
                <th style="text-align:center;">Total Final Invoices</th>
                <th>Invoice Series From</th>
                <th>Invoice Series To</th>
            </tr></thead>
            <tbody><tr>
                <td style="text-align:center;"><strong><?= $allDocs['total_invoices'] ?? 0 ?></strong></td>
                <td><?= htmlspecialchars($allDocs['from_no'] ?? '-') ?></td>
                <td><?= htmlspecialchars($allDocs['to_no'] ?? '-') ?></td>
            </tr></tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<?php require_once '../includes/doc_popup_modal.php'; ?>
<?php require_once '../includes/footer.php'; ?>
