<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/zoho.php';
auth_require_admin();

$page_title = 'Invoices';
require __DIR__ . '/_guard.php';

// ── Read filter inputs ──────────────────────────────────────
$page       = max(1, (int)($_GET['page'] ?? 1));
$per        = 50;
$filter     = $_GET['filter']     ?? '';        // status tab: '', unpaid, overdue, paid, draft
$search     = trim((string)($_GET['q']        ?? ''));
$date_start = trim((string)($_GET['date_start'] ?? ''));
$date_end   = trim((string)($_GET['date_end']   ?? ''));

// Validate dates lightly — drop invalid silently rather than erroring
if ($date_start && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_start)) $date_start = '';
if ($date_end   && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_end))   $date_end   = '';

// ── Pull from Zoho with filters applied server-side ─────────
$zoho_data = zoho_list_invoices_all($page, $per, [
    'status'     => $filter,
    'search'     => $search,
    'date_start' => $date_start,
    'date_end'   => $date_end,
]);
$invoices = $zoho_data['invoices'];
$has_next = $zoho_data['has_more_page'] ?? false;

// ── Map Zoho IDs back to local invoice IDs (for view/PDF links) ─
$z_ids = array_filter(array_map(fn($i) => $i['invoice_id'] ?? null, $invoices));
$local_map  = [];
$member_map = [];
if ($z_ids) {
    $placeholders = implode(',', array_fill(0, count($z_ids), '?'));
    $rows = db_all(
        "SELECT i.id AS local_id, i.zoho_invoice_id, i.member_id,
                m.first_name, m.last_name, m.business_name, m.email
           FROM invoices i
           LEFT JOIN members m ON m.id = i.member_id
          WHERE i.zoho_invoice_id IN ($placeholders)",
        array_values($z_ids)
    );
    foreach ($rows as $r) {
        $local_map[$r['zoho_invoice_id']]  = (int)$r['local_id'];
        $member_map[$r['zoho_invoice_id']] = $r;
    }
}

// Helpers
function status_pill(string $st): string {
    $st = strtolower($st);
    $colors = [
        'paid'             => 'background:#dcfce7;color:#166534;',
        'sent'             => 'background:#dbeafe;color:#1e40af;',
        'viewed'           => 'background:#dbeafe;color:#1e40af;',
        'unpaid'           => 'background:#fef3c7;color:#92400e;',
        'overdue'          => 'background:#fee2e2;color:#991b1b;',
        'partially_paid'   => 'background:#fef3c7;color:#92400e;',
        'draft'            => 'background:#e5e7eb;color:#374151;',
        'void'             => 'background:#e5e7eb;color:#374151;',
    ];
    $style = $colors[$st] ?? 'background:#e5e7eb;color:#374151;';
    $label = ucwords(str_replace('_', ' ', $st));
    return '<span style="' . $style . 'display:inline-block;padding:.15em .55em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;">' . htmlspecialchars($label) . '</span>';
}

// Helper to build query string preserving filters but updating one or more keys
function qs_with(array $overrides): string {
    $base = $_GET;
    foreach ($overrides as $k => $v) {
        if ($v === null || $v === '') unset($base[$k]); else $base[$k] = $v;
    }
    return http_build_query($base);
}

$has_active_filter = ($filter !== '' || $search !== '' || $date_start !== '' || $date_end !== '');
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.875rem;}
.atbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.atbl td{padding:.7rem 1rem;border-bottom:1px solid var(--line);vertical-align:top;}
.ftab{display:inline-flex;align-items:center;gap:.4rem;padding:.3rem .85rem;border-radius:999px;font-size:.82rem;border:1px solid var(--line);text-decoration:none;color:var(--ink);background:#fff;}
.ftab.on{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.ftab:hover:not(.on){background:#fafaf8;}
.unlinked{color:var(--ink-muted);font-style:italic;font-size:.78rem;}

.filter-bar{
    background:#fff;
    border:1px solid var(--line);
    border-radius:8px;
    padding:.85rem 1rem;
    margin-bottom:1rem;
    display:flex;
    gap:.75rem;
    align-items:flex-end;
    flex-wrap:wrap;
}
.filter-bar .field{display:flex;flex-direction:column;gap:.25rem;}
.filter-bar .field.grow{flex:1;min-width:200px;}
.filter-bar label{font-size:.7rem;color:var(--ink-muted);text-transform:uppercase;letter-spacing:.05em;}
.filter-bar input[type=text],
.filter-bar input[type=date]{
    padding:.4rem .55rem;
    border:1px solid var(--line);
    border-radius:6px;
    font-size:.85rem;
    background:#fff;
    font-family:inherit;
}
.filter-bar input[type=text]{width:100%;}
.filter-bar .actions{display:flex;gap:.4rem;}
.filter-bar .clear-link{font-size:.78rem;color:var(--ink-muted);text-decoration:none;align-self:center;}
.filter-bar .clear-link:hover{color:var(--ink);}

.tabs-row{display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:1rem;align-items:center;}
.result-summary{font-size:.8rem;color:var(--ink-muted);margin-left:auto;}
</style>

<section class="section">
<div class="container">

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;flex-wrap:wrap;gap:1rem;">
    <div>
        <h1 style="margin:0;">Invoices</h1>
        <p class="muted" style="margin:.25rem 0 0;font-size:.85rem;">
            <?php if (zoho_is_configured()): ?>
                Live from Zoho Books. Numbers, statuses, and totals match Zoho exactly.
            <?php else: ?>
                Zoho Books is not configured.
            <?php endif; ?>
        </p>
    </div>
</div>

<?php if (!zoho_is_configured()): ?>
    <div class="card">
        <p class="muted" style="margin:0;">Connect Zoho Books to view invoices.
            Go to <a href="zoho-log.php">Settings → Zoho Books</a> to configure.</p>
    </div>
<?php else: ?>

<!-- Search + date range filter bar -->
<form method="get" class="filter-bar">
    <!-- preserve current status tab -->
    <?php if ($filter !== ''): ?>
        <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
    <?php endif; ?>

    <div class="field grow">
        <label for="q">Search</label>
        <input type="text" id="q" name="q" value="<?= htmlspecialchars($search) ?>"
               placeholder="Invoice number, customer name…" autocomplete="off">
    </div>
    <div class="field">
        <label for="date_start">From</label>
        <input type="date" id="date_start" name="date_start" value="<?= htmlspecialchars($date_start) ?>">
    </div>
    <div class="field">
        <label for="date_end">To</label>
        <input type="date" id="date_end" name="date_end" value="<?= htmlspecialchars($date_end) ?>">
    </div>
    <div class="actions">
        <button type="submit" class="btn">Apply</button>
        <?php if ($has_active_filter): ?>
            <a href="invoices.php" class="clear-link">✕ Clear all</a>
        <?php endif; ?>
    </div>
</form>

<!-- Status tabs (preserve search & date filters when switching tabs) -->
<div class="tabs-row">
    <a href="?<?= htmlspecialchars(qs_with(['filter'=>null,'page'=>null])) ?>"      class="ftab <?= $filter===''       ? 'on' : '' ?>">All</a>
    <a href="?<?= htmlspecialchars(qs_with(['filter'=>'unpaid','page'=>null])) ?>"  class="ftab <?= $filter==='unpaid' ? 'on' : '' ?>">Unpaid</a>
    <a href="?<?= htmlspecialchars(qs_with(['filter'=>'overdue','page'=>null])) ?>" class="ftab <?= $filter==='overdue'? 'on' : '' ?>">Overdue</a>
    <a href="?<?= htmlspecialchars(qs_with(['filter'=>'paid','page'=>null])) ?>"    class="ftab <?= $filter==='paid'   ? 'on' : '' ?>">Paid</a>
    <a href="?<?= htmlspecialchars(qs_with(['filter'=>'draft','page'=>null])) ?>"   class="ftab <?= $filter==='draft'  ? 'on' : '' ?>">Draft</a>
    <span class="result-summary">
        <?= count($invoices) ?> result<?= count($invoices)===1?'':'s' ?> on this page<?= $page > 1 ? ' (page '.$page.')' : '' ?>
    </span>
</div>

<?php if (empty($invoices)): ?>
    <div class="card" style="text-align:center;padding:2.5rem 1rem;">
        <p class="muted" style="margin:0 0 .5rem;font-size:1rem;">No invoices found.</p>
        <?php if ($has_active_filter): ?>
            <p class="muted" style="margin:0;font-size:.85rem;">Try widening your search or <a href="invoices.php">clear the filters</a>.</p>
        <?php endif; ?>
    </div>
<?php else: ?>

<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th>Number</th>
                <th>Date</th>
                <th>Customer</th>
                <th style="text-align:right;">Total</th>
                <th>Status</th>
                <th>Linked member</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($invoices as $inv):
            $zid       = (string)($inv['invoice_id'] ?? '');
            $local_id  = $local_map[$zid] ?? null;
            $member    = $member_map[$zid] ?? null;
        ?>
            <tr>
                <td><strong><?= htmlspecialchars($inv['invoice_number'] ?? '') ?></strong></td>
                <td style="font-size:.82rem;color:var(--ink-muted);white-space:nowrap;">
                    <?= htmlspecialchars($inv['date'] ?? '') ?>
                </td>
                <td>
                    <strong><?= htmlspecialchars($inv['customer_name'] ?? '') ?></strong>
                    <?php if (!empty($inv['email'])): ?>
                        <br><span class="muted" style="font-size:.78rem;"><?= htmlspecialchars($inv['email']) ?></span>
                    <?php endif; ?>
                </td>
                <td style="text-align:right;white-space:nowrap;">
                    <?= htmlspecialchars($inv['currency_symbol'] ?? 'R ') ?><?= number_format((float)($inv['total'] ?? 0), 2) ?>
                </td>
                <td><?= status_pill($inv['status'] ?? '') ?></td>
                <td>
                    <?php if ($member && !empty($member['member_id'])): ?>
                        <a href="member-edit.php?id=<?= (int)$member['member_id'] ?>"><?= htmlspecialchars($member['business_name'] ?? '—') ?></a>
                    <?php else: ?>
                        <span class="unlinked">not linked</span>
                    <?php endif; ?>
                </td>
                <td style="text-align:right;white-space:nowrap;">
                    <?php if ($local_id): ?>
                        <a href="../member/invoice.php?id=<?= $local_id ?>" target="_blank">View</a>
                        &nbsp;
                        <a href="../member/invoice.php?id=<?= $local_id ?>&pdf=1" target="_blank">PDF</a>
                    <?php else: ?>
                        <span class="unlinked">—</span>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Pagination (preserves all current filters) -->
<div style="margin-top:1rem;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:.5rem;">
    <span class="muted" style="font-size:.85rem;">Page <?= $page ?></span>
    <div style="display:flex;gap:.5rem;">
        <?php if ($page > 1): ?>
            <a href="?<?= htmlspecialchars(qs_with(['page'=>$page-1])) ?>" class="btn btn-outline">← Previous</a>
        <?php endif; ?>
        <?php if ($has_next): ?>
            <a href="?<?= htmlspecialchars(qs_with(['page'=>$page+1])) ?>" class="btn btn-outline">Next →</a>
        <?php endif; ?>
    </div>
</div>

<?php endif; ?>
<?php endif; ?>

</div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>