<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

// Filters
$status = $_GET['status'] ?? '';
$fromDate = $_GET['from'] ?? '';
$toDate = $_GET['to'] ?? '';

$where = ["i.invoice_type='sale'"];
$params = [];
if ($status) { $where[] = "i.payment_status = ?"; $params[] = $status; }
if ($fromDate) { $where[] = "i.invoice_date >= ?"; $params[] = $fromDate; }
if ($toDate) { $where[] = "i.invoice_date <= ?"; $params[] = $toDate; }
$whereSql = 'WHERE ' . implode(' AND ', $where);

$stmt = $pdo->prepare("SELECT i.*, c.customer_name, u.name as marked_by_name
                        FROM invoices i
                        JOIN sale_vendors c ON c.id=i.customer_id
                        LEFT JOIN users u ON u.id=i.payment_marked_by
                        $whereSql ORDER BY i.invoice_date DESC, i.id DESC");
$stmt->execute($params);
$bills = $stmt->fetchAll();

// Summary
$totalBilled = array_sum(array_column($bills, 'grand_total'));
$totalPaid = array_sum(array_column($bills, 'paid_amount'));
$totalTds = array_sum(array_column($bills, 'tds_amount'));
$totalDue = $totalBilled - $totalPaid - $totalTds;

// All logic/redirects above are done - safe to render layout now
$pageTitle = 'Sale Billing';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Billing</div>
        <h2 class="mb-0">Sale Billing</h2>
    </div>
    <div class="flex gap-8" style="flex-wrap:wrap;">
        <form method="GET" class="flex gap-8">
            <select name="status">
                <option value="">All Status</option>
                <option value="pending" <?= $status=='pending'?'selected':'' ?>>Pending</option>
                <option value="partial" <?= $status=='partial'?'selected':'' ?>>Partial</option>
                <option value="paid" <?= $status=='paid'?'selected':'' ?>>Paid</option>
            </select>
            <input type="date" name="from" value="<?= sanitize($fromDate) ?>">
            <input type="date" name="to" value="<?= sanitize($toDate) ?>">
            <button class="btn"><?= icon('filter') ?> Filter</button>
            <a href="sale_billing.php" class="btn">Reset</a>
        </form>
        <?php $qstr = http_build_query(['status'=>$status,'from'=>$fromDate,'to'=>$toDate]); ?>
        <a href="billing_export.php?type=sale&format=csv&<?= $qstr ?>" class="btn"><?= icon('file-type-csv') ?> CSV</a>
        <a href="billing_export.php?type=sale&format=excel&<?= $qstr ?>" class="btn"><?= icon('file-spreadsheet') ?> Excel</a>
        <a href="billing_export.php?type=sale&format=pdf&<?= $qstr ?>" target="_blank" class="btn"><?= icon('file-type-pdf') ?> PDF</a>
        <button class="btn" onclick="window.print()"><?= icon('printer') ?> Print</button>
    </div>
</div>

<div class="stat-grid">
    <div class="stat-card info">
        <div class="stat-label">Total billed</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totalBilled) ?></div>
    </div>
    <div class="stat-card success">
        <div class="stat-label">Total received</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totalPaid) ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Total TDS deducted</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totalTds) ?></div>
    </div>
    <div class="stat-card danger">
        <div class="stat-label">Outstanding</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totalDue) ?></div>
    </div>
</div>

<div class="card">
    <?php if ($bills): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Invoice #</th><th>Customer</th><th>Date</th>
                    <th class="text-right">Total</th><th class="text-right">Paid</th><th class="text-right">TDS</th><th class="text-right">Due</th>
                    <th>Status</th><th>Payment Date</th><th>Mode</th><th>Marked By</th><th></th></tr>
            </thead>
            <tbody>
            <?php foreach ($bills as $b): ?>
            <tr>
                <td class="mono"><?= sanitize($b['invoice_no']) ?></td>
                <td><?= sanitize($b['customer_name']) ?></td>
                <td><?= formatDate($b['invoice_date']) ?></td>
                <td class="num"><strong><?= formatMoney($b['grand_total']) ?></strong></td>
                <td class="num"><?= formatMoney($b['paid_amount']) ?></td>
                <td class="num"><?= formatMoney($b['tds_amount']) ?></td>
                <td class="num"><?= formatMoney($b['grand_total']-$b['paid_amount']-$b['tds_amount']) ?></td>
                <td><span class="badge badge-<?= $b['payment_status']=='paid'?'success':($b['payment_status']=='partial'?'warning':'danger') ?>"><?= $b['payment_status'] ?></span></td>
                <td><?= $b['payment_date'] ? formatDateTime($b['payment_date']) : '-' ?></td>
                <td><?= sanitize($b['payment_mode']) ?: '-' ?></td>
                <td><?= sanitize($b['marked_by_name']) ?: '-' ?></td>
                <td><a href="../invoice/invoice_view.php?id=<?= $b['id'] ?>" class="btn btn-icon btn-sm"><?= icon('eye') ?></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('file-invoice') ?>No sale bills found for selected filters.</div>
    <?php endif; ?>
</div>

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