<?php
require_once '../includes/auth.php';
requirePermission('reports', '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();
}

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

<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>
            </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; ?>

<!-- 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 require_once '../includes/doc_popup_modal.php'; ?>
<?php require_once '../includes/footer.php'; ?>
