<?php
$pageTitle = 'Invoices';
require_once '../includes/functions.php';
requireLogin();
$db = getDB();

$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);

// Delete invoice
if ($action === 'delete' && $id) {
    try {
        $db->prepare("DELETE FROM invoices WHERE id=?")->execute([$id]);
        setFlash('success', 'Invoice deleted.');
    } catch (PDOException $e) {
        setFlash('error', 'Failed to delete invoice.');
    }
    header('Location: invoices.php');
    exit;
}

// Update status
if ($action === 'status' && $id && isset($_GET['s'])) {
    $validStatuses = ['draft','sent','paid','overdue','cancelled'];
    $s = $_GET['s'];
    if (in_array($s, $validStatuses)) {
        try {
            $db->prepare("UPDATE invoices SET status=? WHERE id=?")->execute([$s, $id]);
            setFlash('success', 'Invoice status updated.');
        } catch (PDOException $e) {
            setFlash('error', 'Failed to update invoice status.');
        }
    }
    header('Location: invoices.php');
    exit;
}

// Filters
$search     = trim($_GET['search'] ?? '');
$status_f   = trim($_GET['status'] ?? '');
$page       = max(1, (int)($_GET['page'] ?? 1));
$where      = 'WHERE 1=1';
$params     = [];

if ($search) {
    $where .= ' AND (i.invoice_number LIKE ? OR c.name LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($status_f) {
    $where .= ' AND i.status = ?';
    $params[] = $status_f;
}

$query  = "SELECT i.*, c.name as customer_name FROM invoices i JOIN customers c ON i.customer_id = c.id $where ORDER BY i.created_at DESC";
$result = paginate($query, $params, $page);
require_once '../includes/header.php';
?>

<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
    <div>
        <h2 class="text-lg font-bold text-slate-800">Invoices</h2>
        <p class="text-sm text-slate-400"><?= $result['total'] ?> invoices</p>
    </div>
    <a href="invoice_create.php" class="btn-primary"><i class="fas fa-plus"></i> New Invoice</a>
</div>

<!-- Filters -->
<form method="GET" class="mb-4 flex flex-wrap gap-2">
    <div class="relative">
        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-sm"></i>
        <input type="text" name="search" value="<?= sanitize($search) ?>" placeholder="Search invoice / customer..." class="form-input pl-9 w-56">
    </div>
    <select name="status" class="form-input w-36">
        <option value="">All Statuses</option>
        <?php foreach (['draft','sent','paid','overdue','cancelled'] as $st): ?>
        <option value="<?= $st ?>" <?= $status_f === $st ? 'selected' : '' ?>><?= ucfirst($st) ?></option>
        <?php endforeach; ?>
    </select>
    <button type="submit" class="btn-outline">Filter</button>
    <?php if ($search || $status_f): ?><a href="invoices.php" class="btn-outline">Clear</a><?php endif; ?>
</form>

<div class="card overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead class="bg-slate-50 border-b border-slate-100">
                <tr>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Invoice #</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Customer</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Date</th>
                    <th class="text-right px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Subtotal</th>
                    <th class="text-right px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">GST</th>
                    <th class="text-right px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Total</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Status</th>
                    <th class="text-right px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-50">
                <?php if (empty($result['data'])): ?>
                <tr><td colspan="8" class="text-center py-12 text-slate-400">
                    <i class="fas fa-file-invoice text-3xl mb-2 block"></i>No invoices found.
                    <a href="invoice_create.php" class="text-brand-600 font-semibold">Create your first invoice</a>
                </td></tr>
                <?php else: foreach ($result['data'] as $inv): ?>
                <tr class="table-row">
                    <td class="px-5 py-3.5">
                        <span class="font-mono text-xs bg-slate-100 px-2 py-1 rounded font-semibold text-slate-700"><?= sanitize($inv['invoice_number']) ?></span>
                    </td>
                    <td class="px-5 py-3.5 font-medium text-slate-800"><?= sanitize($inv['customer_name']) ?></td>
                    <td class="px-5 py-3.5 text-slate-500 text-xs"><?= formatDate($inv['invoice_date']) ?></td>
                    <td class="px-5 py-3.5 text-right text-slate-600"><?= formatCurrency($inv['subtotal']) ?></td>
                    <td class="px-5 py-3.5 text-right text-slate-600"><?= formatCurrency($inv['gst_amount']) ?></td>
                    <td class="px-5 py-3.5 text-right font-bold text-slate-800"><?= formatCurrency($inv['total_amount']) ?></td>
                    <td class="px-5 py-3.5">
                        <div class="flex items-center gap-2">
                            <?= statusBadge($inv['status']) ?>
                            <div class="relative group">
                                <button class="text-slate-400 hover:text-slate-600 text-xs"><i class="fas fa-chevron-down"></i></button>
                                <div class="absolute left-0 top-6 bg-white shadow-xl rounded-xl border border-slate-100 py-1.5 z-20 hidden group-hover:block w-36">
                                    <?php foreach(['draft','sent','paid','overdue','cancelled'] as $st): ?>
                                    <a href="invoices.php?action=status&id=<?= $inv['id'] ?>&s=<?= $st ?>" class="block px-3 py-1.5 text-xs text-slate-700 hover:bg-slate-50 capitalize"><?= ucfirst($st) ?></a>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </td>
                    <td class="px-5 py-3.5 text-right">
                        <a href="invoice_view.php?id=<?= $inv['id'] ?>" class="text-brand-600 hover:text-brand-700 font-semibold text-xs mr-2"><i class="fas fa-eye"></i></a>
                        <a href="invoice_create.php?clone=<?= $inv['id'] ?>" class="text-slate-500 hover:text-slate-700 font-semibold text-xs mr-2" title="Clone"><i class="fas fa-copy"></i></a>
                        <form method="POST" action="invoices.php?action=delete&id=<?= $inv['id'] ?>" class="inline" onsubmit="return confirm('Delete this invoice?')">
                            <button type="submit" class="text-red-400 hover:text-red-600 text-xs"><i class="fas fa-trash"></i></button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($result['totalPages'] > 1): ?>
    <div class="px-5 py-4 border-t border-slate-100 flex items-center justify-between">
        <span class="text-xs text-slate-400">Page <?= $page ?> of <?= $result['totalPages'] ?></span>
        <div class="flex gap-2">
            <?php for ($p = 1; $p <= $result['totalPages']; $p++): ?>
            <a href="?page=<?= $p ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status_f) ?>" class="w-8 h-8 flex items-center justify-center rounded-lg text-xs font-semibold <?= $p == $page ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' ?>">
                <?= $p ?>
            </a>
            <?php endfor; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

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