<?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');
$itemWise = isset($_GET['itemwise']) ? 1 : 0;
$hsnWise  = isset($_GET['hsnwise']) ? 1 : 0;
$customers = $conn->query("SELECT id, name FROM clients ORDER BY name ASC");
$customer_id = $_GET['customer_id'] ?? '';

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

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

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

if ($hsnWise) {
    $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()) {
        $totalTaxable += $row['taxable_total'];
        $totalGST += $row['gst_total'];
        $totalCGST += $row['gst_total'] / 2;
        $totalSGST += $row['gst_total'] / 2;
        $rows[] = $row;
    }
} elseif ($itemWise) {
    $sql = "
        SELECT si.id, 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()) {
        $totalTaxable += $row['taxable_amount'];
        $totalGST += $row['gst_amount'];
        $totalCGST += $row['gst_amount'] / 2;
        $totalSGST += $row['gst_amount'] / 2;
        $totalNet += $row['total_amount'];
        $rows[] = $row;
    }
} else {
    $sql = "
        SELECT si.id, 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()) {
        $totalTaxable += $row['total_taxable'];
        $totalGST += $row['total_gst'];
        $totalCGST += $row['total_gst'] / 2;
        $totalSGST += $row['total_gst'] / 2;
        $totalNet += $row['net_total'];
        $rows[] = $row;
    }
}
?>

<div class="page-header">
    <h2><i class="fas fa-percent" style="color:var(--primary);margin-right:8px;"></i>GST Report</h2>
    <div style="display:flex;gap:8px;">
        <a href="gst_export_excel.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&customer_id=<?= urlencode($customer_id) ?>&itemwise=<?= $itemWise ?>&hsnwise=<?= $hsnWise ?>"
           target="_blank" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</a>
        <a href="gst_export_pdf.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&customer_id=<?= urlencode($customer_id) ?>&itemwise=<?= $itemWise ?>&hsnwise=<?= $hsnWise ?>"
           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>Customer</label>
            <select name="customer_id">
                <option value="">All Customers</option>
                <?php while($c = $customers->fetch_assoc()): ?>
                    <option value="<?= $c['id'] ?>" <?= ($customer_id==$c['id'])?'selected':'' ?>>
                        <?= htmlspecialchars($c['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="filter-group" style="justify-content:flex-end;">
            <div style="display:flex;flex-direction:column;gap:6px;margin-top:18px;">
                <label style="font-weight:400;text-transform:none;letter-spacing:0;display:flex;align-items:center;gap:6px;cursor:pointer;">
                    <input type="checkbox" name="itemwise" value="1" <?= $itemWise?'checked':'' ?> style="width:auto;accent-color:var(--primary);">
                    Item Wise
                </label>
                <label style="font-weight:400;text-transform:none;letter-spacing:0;display:flex;align-items:center;gap:6px;cursor:pointer;">
                    <input type="checkbox" name="hsnwise" value="1" <?= $hsnWise?'checked':'' ?> style="width:auto;accent-color:var(--primary);">
                    HSN Wise Summary
                </label>
            </div>
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Generate</button>
            <a href="gst_report.php" class="btn btn-secondary">Reset</a>
        </div>
    </form>
</div>

<!-- 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 CGST</div>
        <div class="stat-card-value" style="color:var(--info);">&#8377; <?= number_format($totalCGST, 2) ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-label">Total SGST</div>
        <div class="stat-card-value" style="color:var(--info);">&#8377; <?= number_format($totalSGST, 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>
    <?php if(!$hsnWise): ?>
    <div class="stat-card">
        <div class="stat-card-label">Net Total</div>
        <div class="stat-card-value" style="color:var(--success);">&#8377; <?= number_format($totalNet, 2) ?></div>
    </div>
    <?php endif; ?>
</div>

<!-- Table -->
<div class="panel">
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <?php if($hsnWise): ?>
                <tr>
                    <th>HSN Code</th><th style="text-align:center;">GST %</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>
                </tr>
                <?php elseif($itemWise): ?>
                <tr>
                    <th>Invoice No</th><th>Date</th><th>Customer</th><th>Product</th>
                    <th>HSN</th><th style="text-align:center;">Qty</th>
                    <th style="text-align:right;">Taxable</th>
                    <th style="text-align:center;">GST%</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 else: ?>
                <tr>
                    <th>Invoice No</th><th>Date</th><th>Customer</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;">Net Total</th>
                </tr>
                <?php endif; ?>
            </thead>
            <tbody>
            <?php if(count($rows) > 0): ?>
                <?php foreach($rows as $row): ?>
                <tr>
                    <?php if($hsnWise): ?>
                        <td><strong><?= htmlspecialchars($row['hsn_code']) ?></strong></td>
                        <td style="text-align:center;"><?= $row['gst_percent'] ?>%</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>
                    <?php elseif($itemWise): ?>
                        <td><a href="#" onclick="openDocPopup('sale',<?= $row['id'] ?>,'<?= htmlspecialchars($row['invoice_no'],ENT_QUOTES) ?>');return false;" style="color:var(--primary);text-decoration:none;"><?= htmlspecialchars($row['invoice_no']) ?></a></td>
                        <td><?= date('d-m-Y', strtotime($row['invoice_date'])) ?></td>
                        <td><?= htmlspecialchars($row['customer_name']) ?></td>
                        <td><?= htmlspecialchars($row['product_name']) ?></td>
                        <td style="color:var(--text-secondary);font-size:12px;"><?= htmlspecialchars($row['hsn_code']) ?></td>
                        <td style="text-align:center;"><?= $row['sold_qty'] ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['taxable_amount'], 2) ?></td>
                        <td style="text-align:center;"><?= $row['gst_percent'] ?>%</td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['gst_amount']/2, 2) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['gst_amount']/2, 2) ?></td>
                        <td style="text-align:right;">&#8377; <?= number_format($row['gst_amount'], 2) ?></td>
                        <td style="text-align:right;"><strong>&#8377; <?= number_format($row['total_amount'], 2) ?></strong></td>
                    <?php else: ?>
                        <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><?= htmlspecialchars($row['customer_name']) ?></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 endif; ?>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="12" style="text-align:center;padding:40px;color:var(--text-muted);">No data found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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