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

$stmt = $pdo->query("SELECT i.*, c.customer_name FROM invoices i
                      JOIN sale_vendors c ON c.id=i.customer_id
                      WHERE i.invoice_type='sale'
                      ORDER BY i.id DESC");
$invoices = $stmt->fetchAll();

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

<div class="page-header">
    <div>
        <div class="eyebrow">Sales Flow</div>
        <h2 class="mb-0">Tax Invoices</h2>
    </div>
</div>

<div class="card">
    <?php if ($invoices): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Invoice #</th><th>Customer</th><th>Date</th>
                    <th class="text-right">Grand Total</th><th class="text-right">Paid</th><th class="text-right">Balance</th>
                    <th>Payment Status</th><th>Email</th><th>Actions</th></tr>
            </thead>
            <tbody>
            <?php foreach ($invoices as $inv): ?>
            <tr>
                <td class="mono"><?= sanitize($inv['invoice_no']) ?></td>
                <td><?= sanitize($inv['customer_name']) ?></td>
                <td><?= formatDate($inv['invoice_date']) ?></td>
                <td class="num"><strong><?= formatMoney($inv['grand_total']) ?></strong></td>
                <td class="num"><?= formatMoney($inv['paid_amount']) ?></td>
                <td class="num"><?= formatMoney($inv['grand_total'] - $inv['paid_amount']) ?></td>
                <td><span class="badge badge-<?= $inv['payment_status']=='paid'?'success':($inv['payment_status']=='partial'?'warning':'danger') ?>"><?= $inv['payment_status'] ?></span></td>
                <td><?php if ($inv['email_sent']): ?><span class="badge badge-success"><?= icon('mail-forward') ?> Sent</span><?php else: ?><span class="badge badge-muted">Not sent</span><?php endif; ?></td>
                <td><a href="invoice_view.php?id=<?= $inv['id'] ?>" class="btn btn-icon btn-sm" title="View"><?= icon('eye') ?></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('receipt') ?>No tax invoices yet. They are generated from delivered orders.</div>
    <?php endif; ?>
</div>

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