<?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');
$status = $_GET['status'] ?? 'final';
$search = trim($_GET['search'] ?? '');

$where = " WHERE si.invoice_date BETWEEN ? AND ? AND si.company_id = ? ";
$params = [$from, $to, $cid]; $types = "ssi";
if ($status !== 'all') { $where .= " AND si.status = ? "; $params[] = $status; $types .= "s"; }
if (!empty($search)) {
    $where .= " AND (si.invoice_no LIKE ? OR c.name LIKE ? OR c.phone LIKE ?) ";
    $like = "%$search%"; $params[] = $like; $params[] = $like; $params[] = $like; $types .= "sss";
}

$sql = "SELECT si.*, c.name AS customer_name, c.phone AS customer_phone
        FROM sales_invoices si JOIN clients c ON c.id = si.client_id
        $where ORDER BY si.invoice_date DESC, si.id DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$totalGross = $totalTaxable = $totalGST = $totalNet = $totalReceived = $totalBalance = 0;
$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = $row;
    $totalGross    += $row['gross_total'];
    $totalTaxable  += $row['total_taxable'];
    $totalGST      += $row['total_gst'];
    $totalNet      += $row['net_total'];
    $totalReceived += $row['received_amount'];
    $totalBalance  += $row['balance_amount'];
}
?>

<div class="page-header">
    <h2><i class="fas fa-chart-line" style="color:var(--primary);margin-right:8px;"></i>Sales Report</h2>
    <div style="display:flex;gap:8px;">
        <a href="sales_report_export_excel.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&status=<?= urlencode($status) ?>&search=<?= urlencode($search) ?>"
           class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</a>
        <a href="sales_report_export_pdf.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&status=<?= urlencode($status) ?>&search=<?= urlencode($search) ?>"
           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>Status</label>
            <select name="status">
                <option value="all"   <?= $status=='all'  ?'selected':'' ?>>All</option>
                <option value="draft" <?= $status=='draft'?'selected':'' ?>>Draft</option>
                <option value="final" <?= $status=='final'?'selected':'' ?>>Final</option>
            </select>
        </div>
        <div class="filter-group" style="flex:1;min-width:220px;">
            <label>Search</label>
            <input type="text" name="search" placeholder="Invoice / Customer / Phone"
                   value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Filter</button>
            <a href="sales_report.php" class="btn btn-secondary">Reset</a>
        </div>
    </form>
</div>

<!-- Summary -->
<div class="stat-cards">
    <?php foreach ([
        ['Gross',    $totalGross,    'var(--primary)'],
        ['Taxable',  $totalTaxable,  '#7c3aed'],
        ['GST',      $totalGST,      'var(--info)'],
        ['Net Total',$totalNet,      'var(--success)'],
        ['Received', $totalReceived, 'var(--warning)'],
        ['Balance',  $totalBalance,  'var(--danger)'],
    ] as [$label, $val, $color]): ?>
    <div class="stat-card">
        <div class="stat-card-label"><?= $label ?></div>
        <div class="stat-card-value" style="color:<?= $color ?>;">&#8377; <?= number_format($val, 2) ?></div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Table -->
<div class="panel">
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>#</th><th>Date</th><th>Invoice No</th><th>Customer</th><th>Phone</th>
                    <th style="text-align:right;">Gross</th><th style="text-align:right;">Taxable</th>
                    <th style="text-align:right;">GST</th><th style="text-align:right;">Net</th>
                    <th style="text-align:right;">Received</th><th style="text-align:right;">Balance</th>
                    <th>Status</th><th style="text-align:center;">Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if (count($data) > 0): $i = 1; foreach ($data as $row): ?>
            <tr>
                <td style="color:var(--text-muted);"><?= $i++ ?></td>
                <td><?= date('d-m-Y', strtotime($row['invoice_date'])) ?></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><?= htmlspecialchars($row['customer_name']) ?></td>
                <td style="color:var(--text-secondary);"><?= htmlspecialchars($row['customer_phone']) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['gross_total'],2) ?></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) ?></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($row['net_total'],2) ?></strong></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['received_amount'],2) ?></td>
                <td style="text-align:right;color:<?= $row['balance_amount'] > 0 ? 'var(--danger)' : 'var(--success)' ?>;">
                    &#8377; <?= number_format($row['balance_amount'],2) ?>
                </td>
                <td>
                    <span class="badge <?= $row['status']=='final' ? 'badge-success' : 'badge-warning' ?>">
                        <?= ucfirst($row['status']) ?>
                    </span>
                </td>
                <td style="text-align:center;">
                    <a href="../sales/view.php?id=<?= $row['id'] ?>" class="action-btn view" title="View">
                        <i class="fas fa-eye"></i>
                    </a>
                </td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="13" style="text-align:center;padding:40px;color:var(--text-muted);">No sales found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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