<?php
$page_title = 'Invoices';
require __DIR__ . '/_guard.php';
require_once __DIR__ . '/../includes/zoho.php';

// Member is in $member from _guard. Pull their invoices from Zoho if linked.
$invoices = [];
$zoho_offline = !zoho_is_configured();
$not_linked   = empty($member['zoho_contact_id']);

if (!$zoho_offline && !$not_linked) {
    $invoices = zoho_list_invoices_for_contact((string)$member['zoho_contact_id']);
}

// Build a map of zoho_invoice_id → local id so the View/PDF links use our proxy
$z_ids = array_filter(array_map(fn($i) => $i['invoice_id'] ?? null, $invoices));
$local_map = [];
if ($z_ids) {
    $placeholders = implode(',', array_fill(0, count($z_ids), '?'));
    $rows = db_all(
        "SELECT id, zoho_invoice_id FROM invoices
          WHERE member_id = ? AND zoho_invoice_id IN ($placeholders)",
        array_merge([(int)$member['id']], array_values($z_ids))
    );
    foreach ($rows as $r) {
        $local_map[$r['zoho_invoice_id']] = (int)$r['id'];
    }
}

function inv_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;',
    ];
    $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>';
}
?>

<style>
.inv-tbl{width:100%;border-collapse:collapse;font-size:.9rem;}
.inv-tbl th{padding:.65rem 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;}
.inv-tbl td{padding:.85rem 1rem;border-bottom:1px solid var(--line);vertical-align:middle;}
.inv-tbl tr:hover td{background:#fafaf8;}
.empty-state{text-align:center;padding:3rem 1rem;color:var(--ink-muted);}
.empty-state .ic{font-size:2.5rem;margin-bottom:.5rem;}
.summary{display:flex;gap:1rem;flex-wrap:wrap;margin-bottom:1.25rem;}
.summary .stat{flex:1;min-width:160px;background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1rem 1.25rem;}
.summary .stat .lbl{font-size:.7rem;color:var(--ink-muted);text-transform:uppercase;letter-spacing:.05em;}
.summary .stat .val{font-size:1.4rem;font-weight:700;margin-top:.15rem;}
.summary .stat .sub{font-size:.78rem;color:var(--ink-muted);}
</style>

<section class="section">
<div class="container">

<div style="margin-bottom:1.25rem;">
    <h1 style="margin:0;">Your Invoices</h1>
    <p class="muted" style="margin:.25rem 0 0;font-size:.9rem;">
        All invoices, receipts, and payment history — pulled live from our accounting system.
    </p>
</div>

<?php if ($zoho_offline): ?>
    <div class="card">
        <p class="muted" style="margin:0;">Invoice history is temporarily unavailable. Please check back later.</p>
    </div>

<?php elseif ($not_linked): ?>
    <div class="empty-state">
        <div class="ic">📄</div>
        <h2 style="margin:0 0 .5rem;font-size:1.1rem;">No invoices yet</h2>
        <p>Your invoice history will appear here as soon as your first payment goes through.</p>
        <p style="margin-top:1.5rem;">
            <a href="welcome.php" class="btn">← Back to dashboard</a>
        </p>
    </div>

<?php elseif (empty($invoices)): ?>
    <div class="empty-state">
        <div class="ic">📄</div>
        <h2 style="margin:0 0 .5rem;font-size:1.1rem;">No invoices yet</h2>
        <p>Once your first payment is processed, your invoices will show up here.</p>
        <p style="margin-top:1.5rem;">
            <a href="welcome.php" class="btn">← Back to dashboard</a>
        </p>
    </div>

<?php else:
    // Compute summary stats
    $total_paid = 0;
    $total_due  = 0;
    $count_paid = 0;
    $count_due  = 0;
    foreach ($invoices as $i) {
        $st = strtolower($i['status'] ?? '');
        $amt = (float)($i['total'] ?? 0);
        if ($st === 'paid') {
            $total_paid += $amt;
            $count_paid++;
        } elseif (in_array($st, ['unpaid','sent','viewed','overdue','partially_paid'], true)) {
            $bal = (float)($i['balance'] ?? $amt);
            $total_due += $bal;
            $count_due++;
        }
    }
?>

<div class="summary">
    <div class="stat">
        <div class="lbl">Invoices</div>
        <div class="val"><?= count($invoices) ?></div>
        <div class="sub">All time</div>
    </div>
    <div class="stat">
        <div class="lbl">Total paid</div>
        <div class="val">R <?= number_format($total_paid, 2) ?></div>
        <div class="sub"><?= $count_paid ?> invoice<?= $count_paid===1?'':'s' ?></div>
    </div>
    <?php if ($count_due > 0): ?>
        <div class="stat" style="border-color:#fca5a5;background:#fef2f2;">
            <div class="lbl" style="color:#b91c1c;">Outstanding</div>
            <div class="val" style="color:#991b1b;">R <?= number_format($total_due, 2) ?></div>
            <div class="sub"><?= $count_due ?> invoice<?= $count_due===1?'':'s' ?> due</div>
        </div>
    <?php endif; ?>
</div>

<div class="card" style="padding:0;overflow:auto;">
    <table class="inv-tbl">
        <thead>
            <tr>
                <th>Number</th>
                <th>Date</th>
                <th>Description</th>
                <th style="text-align:right;">Total</th>
                <th>Status</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($invoices as $i):
            $zid = (string)($i['invoice_id'] ?? '');
            $local_id = $local_map[$zid] ?? null;
            // Try to derive a description from the customer-facing line items
            $desc = '';
            // Zoho's list endpoint doesn't always include line_items; use available fields
            if (!empty($i['line_item_total_count'])) {
                $desc = $i['line_item_total_count'] . ' line item' . ($i['line_item_total_count']==1?'':'s');
            }
        ?>
            <tr>
                <td><strong><?= htmlspecialchars($i['invoice_number'] ?? '') ?></strong></td>
                <td style="font-size:.85rem;color:var(--ink-muted);white-space:nowrap;">
                    <?= htmlspecialchars(date('j M Y', strtotime($i['date'] ?? 'now'))) ?>
                </td>
                <td style="font-size:.85rem;color:var(--ink-muted);">
                    <?= htmlspecialchars($desc) ?>
                </td>
                <td style="text-align:right;white-space:nowrap;font-weight:600;">
                    R <?= number_format((float)($i['total'] ?? 0), 2) ?>
                </td>
                <td><?= inv_status_pill($i['status'] ?? '') ?></td>
                <td style="text-align:right;white-space:nowrap;">
                    <?php if ($local_id): ?>
                        <a href="invoice.php?id=<?= $local_id ?>" target="_blank">View</a>
                        &nbsp;·&nbsp;
                        <a href="invoice.php?id=<?= $local_id ?>&pdf=1" target="_blank">PDF</a>
                    <?php else: ?>
                        <span class="muted" style="font-size:.85rem;">—</span>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<p class="muted" style="font-size:.78rem;margin:.75rem 0 0;text-align:right;">
    <?= count($invoices) ?> invoice<?= count($invoices)===1?'':'s' ?> · pulled live from accounting
</p>

<?php endif; ?>

</div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>