<?php

declare(strict_types=1);

// Store workspace in session before validation to prevent logout on filter submission
if (!session_id()) {
    session_start();
}
if (isset($_GET['workspace'])) {
    $_SESSION['workspace'] = $_GET['workspace'];
}

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/TenantInvoice.php';
require_once __DIR__ . '/../src/Invoice.php';
require_once __DIR__ . '/../src/InvoiceModels.php';
require_once __DIR__ . '/../src/ActivityLog.php';
require_once __DIR__ . '/navigation.php';

// Check permission
requirePermission('invoices_view');

// Get action-specific permissions
$canCreateInvoice = hasPermission('invoices_create');
$canEditInvoice = hasPermission('invoices_edit');
$canDeleteInvoice = hasPermission('invoices_delete');

// Check plan limits
$canAddMoreInvoices = canAddWithinLimits('invoices_per_month');

$errors = [];
$successMessage = $_GET['success'] ?? null;

// Get workspace from URL or session
$workspace = $_GET['workspace'] ?? $_SESSION['workspace'] ?? ($company['username'] ?? null);

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_payment') {
        $invoiceId = (int) ($_POST['invoice_id'] ?? 0);
        $amount = (float) ($_POST['amount'] ?? 0);
        $paymentDate = $_POST['payment_date'] ?? date('Y-m-d');
        $paymentMethod = $_POST['payment_method'] ?? '';
        $notes = $_POST['payment_notes'] ?? '';
        
        if ($invoiceId > 0 && $amount > 0) {
            $pdo = getPDO();
            
            // Get invoice details
            $stmt = $pdo->prepare('SELECT * FROM invoices WHERE id = ?');
            $stmt->execute([$invoiceId]);
            $invoice = $stmt->fetch();
            
            if ($invoice) {
                // Add payment record
                $stmt = $pdo->prepare('INSERT INTO invoice_payments (invoice_id, amount, payment_date, payment_method, notes, created_at) VALUES (?, ?, ?, ?, ?, NOW())');
                if ($stmt->execute([$invoiceId, $amount, $paymentDate, $paymentMethod, $notes])) {
                    // Update invoice paid amount
                    $stmt = $pdo->prepare('UPDATE invoices SET paid_amount = paid_amount + ?, status = ? WHERE id = ?');
                    $newPaidAmount = $invoice['paid_amount'] + $amount;
                    // Use existing statuses only: sent / paid
                    $newStatus = $newPaidAmount >= $invoice['total'] ? 'paid' : 'sent';
                    $stmt->execute([$amount, $newStatus, $invoiceId]);
                    
                    // Get the payment ID for receipt
                    $paymentId = $pdo->lastInsertId();

                    // Log payment activity in workspace log (best-effort)
                    try {
                        if (!empty($companyId)) {
                            $actorId = isset($user['id']) ? (int) $user['id'] : null;

                            // Log generic payment received
                            ActivityLog::log(
                                (int) $companyId,
                                $actorId,
                                'payment_received',
                                'invoice',
                                (int) $invoiceId,
                                $invoice['invoice_number'] ?? null,
                                [
                                    'previous_status' => $invoice['status'] ?? null,
                                    'previous_paid_amount' => $invoice['paid_amount'] ?? 0,
                                ],
                                [
                                    'new_status' => $newStatus,
                                    'payment_amount' => $amount,
                                    'new_paid_amount' => $newPaidAmount,
                                    'payment_method' => $paymentMethod,
                                ]
                            );

                            // If invoice is now fully paid, log invoice_paid
                            if ($newStatus === 'paid') {
                                ActivityLog::log(
                                    (int) $companyId,
                                    $actorId,
                                    'invoice_paid',
                                    'invoice',
                                    (int) $invoiceId,
                                    $invoice['invoice_number'] ?? null,
                                    null,
                                    [
                                        'total' => $invoice['total'] ?? null,
                                        'paid_amount' => $newPaidAmount,
                                    ]
                                );
                            }
                        }
                    } catch (Throwable $e) {
                        // Ignore logging failures
                    }
                    
                    redirect('/invoices.php', [
                        'success' => 'Payment recorded successfully!', 
                        'payment_id' => $paymentId,
                        'invoice_id' => $invoiceId,
                        'workspace' => $workspace
                    ]);
                } else {
                    $errors[] = 'Failed to record payment.';
                }
            } else {
                $errors[] = 'Invoice not found.';
            }
        } else {
            $errors[] = 'Invalid payment amount.';
        }
    } elseif ($action === 'update_status') {
        $invoiceId = (int) ($_POST['invoice_id'] ?? 0);
        $status = $_POST['status'] ?? '';
        
        // Only allow statuses that exist in the DB enum
        $allowedStatuses = ['draft', 'sent', 'paid', 'overdue', 'void'];
        if ($invoiceId > 0 && in_array($status, $allowedStatuses, true)) {
            $pdo = getPDO();

            // Load existing invoice for logging
            $existingStmt = $pdo->prepare('SELECT * FROM invoices WHERE id = ?');
            $existingStmt->execute([$invoiceId]);
            $existingInvoice = $existingStmt->fetch();

            $stmt = $pdo->prepare('UPDATE invoices SET status = ? WHERE id = ?');
            if ($stmt->execute([$status, $invoiceId])) {

                // Log status update
                try {
                    if (!empty($companyId)) {
                        $actorId = isset($user['id']) ? (int) $user['id'] : null;
                        ActivityLog::log(
                            (int) $companyId,
                            $actorId,
                            'invoice_updated',
                            'invoice',
                            (int) $invoiceId,
                            $existingInvoice['invoice_number'] ?? null,
                            [
                                'status' => $existingInvoice['status'] ?? null,
                            ],
                            [
                                'status' => $status,
                            ]
                        );

                        if ($status === 'paid') {
                            ActivityLog::log(
                                (int) $companyId,
                                $actorId,
                                'invoice_paid',
                                'invoice',
                                (int) $invoiceId,
                                $existingInvoice['invoice_number'] ?? null,
                                null,
                                [
                                    'total' => $existingInvoice['total'] ?? null,
                                ]
                            );
                        }
                    }
                } catch (Throwable $e) {
                    // Ignore logging failures
                }

                $params = ['success' => 'Invoice status updated successfully!'];
                if ($workspace) {
                    $params['workspace'] = $workspace;
                }
                redirect('/invoices.php', $params);
            } else {
                $errors[] = 'Failed to update invoice status.';
            }
        } else {
            $errors[] = 'Invalid invoice ID or status.';
        }
    } elseif ($action === 'delete_invoice') {
        $invoiceId = (int) ($_POST['invoice_id'] ?? 0);
        if ($invoiceId > 0) {
            // Load existing invoice for logging before deletion
            $pdo = getPDO();
            $existingStmt = $pdo->prepare('SELECT * FROM invoices WHERE id = ?');
            $existingStmt->execute([$invoiceId]);
            $existingInvoice = $existingStmt->fetch();

            if (Invoice::delete($invoiceId)) {

                // Log invoice deletion
                try {
                    if (!empty($companyId)) {
                        $actorId = isset($user['id']) ? (int) $user['id'] : null;
                        ActivityLog::log(
                            (int) $companyId,
                            $actorId,
                            'invoice_deleted',
                            'invoice',
                            (int) $invoiceId,
                            $existingInvoice['invoice_number'] ?? null,
                            $existingInvoice ? [
                                'status' => $existingInvoice['status'] ?? null,
                                'total' => $existingInvoice['total'] ?? null,
                            ] : null,
                            null
                        );
                    }
                } catch (Throwable $e) {
                    // Ignore logging failures
                }

                $params = ['success' => 'Invoice deleted successfully!'];
                if ($workspace) {
                    $params['workspace'] = $workspace;
                }
                redirect('/invoices.php', $params);
            } else {
                $errors[] = 'Failed to delete invoice.';
            }
        }
    }
}

// Get settings for currency
$settings = InvoiceSettings::get() ?? [];

// Get filter parameters
$search = $_GET['search'] ?? '';
$clientFilter = $_GET['client'] ?? '';
$statusFilter = $_GET['status'] ?? '';
$dateFilter = $_GET['date_filter'] ?? '';
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';

// Build query
$whereConditions = [];
$params = [];

// Add company filtering for multi-tenant isolation
// Always use the current workspace company resolved by secure_workspace
$companyId = isset($company['id']) ? (int) $company['id'] : 0;
$whereConditions[] = 'i.company_id = ?';
$params[] = $companyId;

if ($search) {
    $whereConditions[] = '(i.invoice_number LIKE ? OR c.name LIKE ? OR c.company LIKE ?)';
    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

if ($clientFilter) {
    $whereConditions[] = 'c.id = ?';
    $params[] = $clientFilter;
}

if ($statusFilter) {
    $whereConditions[] = 'i.status = ?';
    $params[] = $statusFilter;
}

// Date filtering
if ($dateFilter) {
    switch ($dateFilter) {
        case 'last_week':
            $whereConditions[] = 'i.created_at >= datetime("now", "-7 days")';
            break;
        case 'last_month':
            $whereConditions[] = 'i.created_at >= datetime("now", "-1 month")';
            break;
        case 'last_3_months':
            $whereConditions[] = 'i.created_at >= datetime("now", "-3 months")';
            break;
        case 'last_6_months':
            $whereConditions[] = 'i.created_at >= datetime("now", "-6 months")';
            break;
        case 'last_year':
            $whereConditions[] = 'i.created_at >= datetime("now", "-1 year")';
            break;
        case 'custom':
            if ($startDate) {
                $whereConditions[] = 'i.created_at >= ?';
                $params[] = $startDate;
            }
            if ($endDate) {
                $whereConditions[] = 'i.created_at <= ?';
                $params[] = $endDate;
            }
            break;
    }
}

$whereClause = $whereConditions ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

// Get invoices with filtering
$pdo = getPDO();
$sql = "SELECT i.*, c.name as client_name, c.company as client_company, c.email as client_email,
        COALESCE(SUM(p.amount), 0) as total_paid
        FROM invoices i 
        LEFT JOIN clients c ON i.client_id = c.id
        LEFT JOIN invoice_payments p ON i.id = p.invoice_id
        $whereClause
        GROUP BY i.id
        ORDER BY i.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$invoices = $stmt->fetchAll();

// Get clients for filter dropdown
$stmt = $pdo->prepare('SELECT id, name, company FROM clients ORDER BY name');
$stmt->execute();
$clients = $stmt->fetchAll();

// Calculate totals
$totalInvoices = count($invoices);
$totalAmount = array_sum(array_column($invoices, 'total'));
$totalPaid = array_sum(array_column($invoices, 'total_paid'));
$totalDue = $totalAmount - $totalPaid;

// Status badge colors (design system)
$statusColors = [
    'draft' => 'status-chip',
    'sent' => 'status-chip',
    'paid' => 'status-chip',
    'overdue' => 'status-chip',
    'void' => 'status-chip',
];

// Status options (only DB-backed statuses)
$statusOptions = [
    'draft' => 'Draft',
    'sent' => 'Sent',
    'paid' => 'Paid',
    'overdue' => 'Overdue',
    'void' => 'Void',
];

// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

// Workspace context (match other dashboard pages)
$workspaceParam = $_GET['workspace'] ?? null;
$companyDisplayName = $company['name'] ?? 'Workspace';
$workspaceSlug = $workspaceParam ?? ($company['username'] ?? ($companyId ?? null));
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '';
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= h($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoices · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
<?php renderNavigationNew('Invoices', $currentTheme); ?>

<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';

    $actions = [];
    if ($canCreateInvoice) {
        $actions[] = ['label' => 'New invoice', 'url' => '/invoice_create.php', 'type' => 'primary', 'icon' => 'M12 4v16m8-8H4', 'append_workspace' => true];
    }

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php' . $workspaceQuery, 'icon' => 'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2z'],
        ],
        currentPage: 'Invoices',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <?php if ($successMessage): ?>
            <div class="dash-section">
                <div class="status-banner success" style="display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                    <span><?= h($successMessage) ?></span>
                    <?php if (!empty($_GET['payment_id']) && !empty($_GET['invoice_id'])): ?>
                        <a href="/download.php?workspace=<?= urlencode($workspace) ?>&action=view_payment_receipt&invoice_id=<?= (int) $_GET['invoice_id'] ?>&payment_id=<?= (int) $_GET['payment_id'] ?>&t=<?= time() ?>" target="_blank" class="btn-secondary btn-sm">Download receipt</a>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <div style="display: flex; flex-direction: column; gap: 4px;">
                        <strong style="font-size: 12px;">Error</strong>
                        <?php foreach ($errors as $error): ?>
                            <div><?= h($error) ?></div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="dash-section">
            <section class="card template-hero">
                <div>
                    <p class="section-title">Invoices</p>
                    <h1 class="template-hero__title">Invoices for <?= htmlspecialchars($companyDisplayName) ?></h1>
                    <p class="template-hero__subtitle">Track invoice totals, record payments, and keep client balances up to date.</p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= (int) $totalInvoices ?> total</span>
                    <span class="status-chip"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $totalPaid, 2) ?> paid</span>
                    <span class="status-chip"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $totalDue, 2) ?> due</span>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card template-stats">
                <div class="template-stats-grid">
                    <div class="template-stat">
                        <p class="template-stat__label">Total invoices</p>
                        <p class="template-stat__value"><?= (int) $totalInvoices ?></p>
                        <p class="template-stat__hint">Across this workspace</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Total paid</p>
                        <p class="template-stat__value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $totalPaid, 2) ?></p>
                        <p class="template-stat__hint">Payments recorded</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Total due</p>
                        <p class="template-stat__value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $totalDue, 2) ?></p>
                        <p class="template-stat__hint">Outstanding balance</p>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div style="margin-bottom: 16px;">
                    <p class="section-title">Filters</p>
                    <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Search invoices by number or client</p>
                </div>
                <form id="filterForm" method="GET" action="/invoices.php">
                    <?php if ($workspaceSlug): ?>
                        <input type="hidden" name="workspace" value="<?= h((string) $workspaceSlug) ?>">
                    <?php endif; ?>
                    <div style="display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end;">
                        <div style="flex: 1; min-width: 220px;">
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Search</label>
                            <div class="input-with-icon">
                                <svg style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 14px; height: 14px; color: var(--text-tertiary); pointer-events: none;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                </svg>
                                <input type="text" name="search" value="<?= h($_GET['search'] ?? '') ?>" placeholder="Search invoices..." class="input" style="padding-left: 36px;">
                            </div>
                        </div>

                        <div style="flex: 1; min-width: 220px; position: relative;">
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Client</label>
                            <input type="text" id="clientSearch" name="client_search" value="<?= h($_GET['client_search'] ?? '') ?>" placeholder="Search clients..." class="input" autocomplete="off">
                            <input type="hidden" id="clientId" name="client_id" value="<?= (int) ($_GET['client_id'] ?? 0) ?>">
                            <div id="clientDropdown" class="hidden" style="position: absolute; left: 0; right: 0; top: calc(100% + 6px); z-index: 50; border: 1px solid var(--border-default); background: var(--bg-dropdown); border-radius: 10px; box-shadow: 0 18px 45px rgba(0,0,0,0.35); padding: 10px; max-height: 260px; overflow: auto;">
                                <div style="font-size: 11px; font-weight: 650; letter-spacing: 0.08em; text-transform: uppercase; color: var(--text-tertiary); padding: 0 6px 8px;">Clients</div>
                                <div id="clientList">
                                    <div style="padding: 8px 10px; font-size: 12px; color: var(--text-tertiary);">Type to search clients...</div>
                                </div>
                            </div>
                        </div>

                        <div style="flex: 1; min-width: 180px;">
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Status</label>
                            <select name="status" class="input">
                                <option value="">All statuses</option>
                                <?php foreach ($statusOptions as $value => $label): ?>
                                    <option value="<?= $value ?>" <?= (isset($_GET['status']) && $_GET['status'] == $value) ? 'selected' : '' ?>><?= h($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div style="display: flex; gap: 8px;">
                            <button type="submit" class="btn-primary">
                                <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.707A1 1 0 013 7V4z"></path>
                                </svg>
                                Apply
                            </button>
                            <a href="/invoices.php<?= $workspaceQuery ?>" class="btn-secondary">
                                <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                                </svg>
                                Reset
                            </a>
                        </div>
                    </div>
                </form>
            </section>
        </div>

        <div class="dash-section">
            <section class="card" style="padding: 0; overflow: hidden; margin-bottom: 0;">
                <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle); display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px;">
                    <div>
                        <p class="section-title">Invoice list</p>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Showing <?= count($invoices) ?> invoice<?= count($invoices) === 1 ? '' : 's' ?></p>
                    </div>
                    <?php if ($canCreateInvoice): ?>
                        <a href="/invoice_create.php<?= $workspaceQuery ?>" class="btn-secondary">New</a>
                    <?php endif; ?>
                </div>

                <?php if (empty($invoices)): ?>
                    <div class="empty-state" style="padding: 24px;">
                        <h3>No invoices yet</h3>
                        <p>Create your first invoice to get started.</p>
                        <?php if ($canCreateInvoice): ?>
                            <a href="/invoice_create.php<?= $workspaceQuery ?>" class="btn-primary">Create invoice</a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div style="overflow-x: auto;">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Invoice</th>
                                    <th>Client</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th style="text-align: right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($invoices as $invoice): ?>
                                    <?php
                                    $createdLabel = !empty($invoice['issue_date']) ? date('M j, Y', strtotime((string) $invoice['issue_date'])) : '';
                                    $amountLabel = h($settings['currency'] ?? 'USD') . ' ' . number_format((float) $invoice['total'], 2);
                                    $paidLabel = ((float) ($invoice['paid_amount'] ?? 0) > 0) ? (h($settings['currency'] ?? 'USD') . ' ' . number_format((float) $invoice['paid_amount'], 2)) : null;
                                    $viewLink = "/invoice_view.php?id=" . (int) $invoice['id'] . ($workspaceSlug ? "&workspace=" . urlencode((string) $workspaceSlug) : '');
                                    ?>
                                    <tr>
                                        <td style="vertical-align: top;">
                                            <div style="display: flex; flex-direction: column; gap: 2px;">
                                                <div style="font-size: 13px; font-weight: 500; color: var(--text-primary);">
                                                    <?= h($invoice['invoice_number'] ?? ('INV-' . $invoice['id'])) ?>
                                                </div>
                                                <div style="font-size: 11px; color: var(--text-secondary);"><?= h($createdLabel) ?></div>
                                            </div>
                                        </td>
                                        <td style="vertical-align: top;">
                                            <div style="font-size: 13px; color: var(--text-primary);"><?= h($invoice['client_name'] ?? 'Unknown') ?></div>
                                            <?php if (!empty($invoice['client_company'])): ?>
                                                <div style="font-size: 11px; color: var(--text-secondary);"><?= h($invoice['client_company']) ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td style="vertical-align: top;">
                                            <div style="font-size: 13px; font-weight: 500; color: var(--text-primary);"><?= $amountLabel ?></div>
                                            <?php if ($paidLabel): ?>
                                                <div style="font-size: 11px; color: var(--text-secondary);">Paid: <?= h($paidLabel) ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td style="vertical-align: top;">
                                            <span class="status-chip"><?= h($statusOptions[$invoice['status']] ?? $invoice['status']) ?></span>
                                        </td>
                                        <td style="vertical-align: top; text-align: right;">
                                            <div style="display: flex; justify-content: flex-end; gap: 6px; flex-wrap: wrap;">
                                                <a href="<?= h($viewLink) ?>" class="btn-secondary btn-sm" style="white-space: nowrap;">View</a>
                                                <button type="button" class="btn-secondary btn-sm" style="white-space: nowrap;" onclick="showPaymentModal(<?= (int) $invoice['id'] ?>, '<?= h($invoice['invoice_number']) ?>', <?= (float) ($invoice['total'] - $invoice['paid_amount']) ?>)">Payment</button>
                                                <button type="button" class="btn-secondary btn-sm" style="white-space: nowrap;" onclick="toggleStatusDropdown(<?= (int) $invoice['id'] ?>)">Status</button>
                                            </div>
                                            <div id="statusDropdown-<?= (int) $invoice['id'] ?>" class="hidden" style="position: relative;">
                                                <div style="position: absolute; right: 0; top: 8px; min-width: 220px; z-index: 60; border: 1px solid var(--border-default); background: var(--bg-dropdown); border-radius: 10px; box-shadow: 0 18px 45px rgba(0,0,0,0.35); padding: 8px; display: flex; flex-direction: column; gap: 6px;">
                                                    <?php foreach ($statusOptions as $value => $label): ?>
                                                        <?php if ($value !== $invoice['status']): ?>
                                                            <button type="button" onclick="updateInvoiceStatus(<?= (int) $invoice['id'] ?>, '<?= $value ?>')" style="width: 100%; text-align: left; border: 1px solid transparent; background: transparent; padding: 8px 10px; border-radius: 10px; cursor: pointer; color: var(--text-primary);" onmouseover="this.style.background='var(--bg-hover)';" onmouseout="this.style.background='transparent';">
                                                                <span class="status-chip"><?= h($label) ?></span>
                                                            </button>
                                                        <?php endif; ?>
                                                    <?php endforeach; ?>
                                                    <div style="height: 1px; background: var(--border-subtle); margin: 4px 2px;"></div>
                                                    <button type="button" onclick="confirmDeleteInvoice(<?= (int) $invoice['id'] ?>, '<?= h($invoice['invoice_number']) ?>')" style="width: 100%; text-align: left; border: 1px solid transparent; background: transparent; padding: 8px 10px; border-radius: 10px; cursor: pointer; color: var(--danger);" onmouseover="this.style.background='rgba(239, 68, 68, 0.08)';" onmouseout="this.style.background='transparent';">Delete invoice</button>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>
        </div>

    </div>

<!-- Payment Modal -->
<div id="paymentModal" class="delete-modal-overlay" style="position: fixed; inset: 0; z-index: 100; display: none; align-items: center; justify-content: center; padding: 16px;">
    <div class="delete-modal-content" style="max-width: 520px;">
        <div class="delete-modal-header">
            <p style="font-size: 11px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.03em; color: var(--text-tertiary); margin: 0 0 8px;">Payments</p>
            <h3 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0 0 4px;">Record payment</h3>
            <p style="font-size: 11px; color: var(--text-tertiary); margin: 0;">Add a payment to this invoice. The invoice status will update automatically.</p>
        </div>

        <form method="POST">
            <input type="hidden" name="action" value="add_payment">
            <input type="hidden" id="paymentInvoiceId" name="invoice_id">

            <div class="delete-modal-body">
                <div class="delete-modal-client-info">
                    <p style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.03em; color: var(--text-tertiary); margin: 0 0 4px;">Invoice</p>
                    <p style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0;" id="paymentInvoiceInfo"></p>

                    <p style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.03em; color: var(--text-tertiary); margin: 12px 0 4px;">Amount due</p>
                    <p style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0;" id="paymentAmountDue"></p>
                </div>

                <div>
                    <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin: 0 0 6px;">Payment amount</label>
                    <input type="number" name="amount" step="0.01" min="0" required oninput="if (parseFloat(this.value) > parseFloat(this.max)) this.value = this.max;" class="input">
                </div>

                <div>
                    <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin: 0 0 6px;">Payment date</label>
                    <input type="date" name="payment_date" required class="input">
                </div>

                <div>
                    <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin: 0 0 6px;">Payment method</label>
                    <select name="payment_method" required class="input">
                        <option value="">Select method</option>
                        <option value="cash">Cash</option>
                        <option value="bank_transfer">Bank transfer</option>
                        <option value="check">Check</option>
                        <option value="credit_card">Credit card</option>
                        <option value="paypal">PayPal</option>
                        <option value="other">Other</option>
                    </select>
                </div>

                <div>
                    <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin: 0 0 6px;">Notes (optional)</label>
                    <textarea name="payment_notes" rows="3" class="input"></textarea>
                </div>
            </div>

            <div class="delete-modal-footer">
                <button type="button" class="btn-secondary" style="flex: 1;" onclick="closePaymentModal()">Cancel</button>
                <button type="submit" class="btn-primary" style="flex: 1;">Record payment</button>
            </div>
        </form>
    </div>
</div>

<script>
// Set currency from PHP
const CURRENCY = '<?= h($settings['currency'] ?? 'USD') ?>';

// Client data from PHP
const CLIENTS = <?= json_encode($clients) ?>;

// Status dropdown functions
function toggleStatusDropdown(invoiceId) {
    const dropdown = document.getElementById('statusDropdown-' + invoiceId);
    
    // Close all other dropdowns
    document.querySelectorAll('[id^="statusDropdown-"]').forEach(d => {
        if (d.id !== 'statusDropdown-' + invoiceId) {
            d.classList.add('hidden');
        }
    });
    
    // Toggle current dropdown
    dropdown.classList.toggle('hidden');
}

function updateInvoiceStatus(invoiceId, newStatus) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.innerHTML = `
        <input type="hidden" name="action" value="update_status">
        <input type="hidden" name="invoice_id" value="${invoiceId}">
        <input type="hidden" name="status" value="${newStatus}">
    `;
    document.body.appendChild(form);
    form.submit();
}

function confirmDeleteInvoice(invoiceId, invoiceNumber) {
    if (confirm(`Are you sure you want to delete invoice ${invoiceNumber}? This action cannot be undone.`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete_invoice">
            <input type="hidden" name="invoice_id" value="${invoiceId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Close dropdowns when clicking outside
document.addEventListener('click', function(event) {
    if (!event.target.closest('[onclick^="toggleStatusDropdown"]') && !event.target.closest('[id^="statusDropdown-"]')) {
        document.querySelectorAll('[id^="statusDropdown-"]').forEach(d => {
            d.classList.add('hidden');
        });
    }
});

// Client Search Functionality
class ClientSearch {
    constructor() {
        this.searchInput = document.getElementById('clientSearch');
        this.hiddenInput = document.getElementById('clientId');
        this.dropdown = document.getElementById('clientDropdown');
        this.clientList = document.getElementById('clientList');
        this.clients = CLIENTS;
        this.selectedClient = null;
        
        this.init();
    }
    
    init() {
        // Set initial selected client
        const selectedClientId = parseInt(this.hiddenInput.value) || 0;
        if (selectedClientId > 0) {
            const client = this.clients.find(c => c.id === selectedClientId);
            if (client) {
                this.selectedClient = client;
                this.searchInput.value = client.name;
            }
        }
        
        // Event listeners
        this.searchInput.addEventListener('focus', () => this.showDropdown());
        this.searchInput.addEventListener('input', (e) => this.handleSearch(e.target.value));
        this.searchInput.addEventListener('keydown', (e) => this.handleKeydown(e));
        
        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!e.target.closest('#clientSearch') && !e.target.closest('#clientDropdown')) {
                this.hideDropdown();
            }
        });
    }
    
    showDropdown() {
        this.dropdown.classList.remove('hidden');
        if (this.searchInput.value.trim() === '') {
            this.showAllClients();
        }
    }
    
    hideDropdown() {
        this.dropdown.classList.add('hidden');
    }
    
    handleSearch(query) {
        if (query.trim() === '') {
            this.showAllClients();
            return;
        }
        
        const filtered = this.clients.filter(client => 
            client.name.toLowerCase().includes(query.toLowerCase()) ||
            (client.email && client.email.toLowerCase().includes(query.toLowerCase())) ||
            (client.company && client.company.toLowerCase().includes(query.toLowerCase()))
        );
        
        this.renderClients(filtered);
    }
    
    showAllClients() {
        // Show first 50 clients for performance
        const limitedClients = this.clients.slice(0, 50);
        this.renderClients(limitedClients);
        
        if (this.clients.length > 50) {
            this.clientList.innerHTML += `
                <div style="padding: 10px 10px 0; margin-top: 6px; border-top: 1px solid var(--border-subtle); font-size: 11px; color: var(--text-tertiary);">
                    Showing first 50 of ${this.clients.length} clients. Type to search for more.
                </div>
            `;
        }
    }
    
    renderClients(clients) {
        if (clients.length === 0) {
            this.clientList.innerHTML = '<div style="padding: 8px 10px; font-size: 12px; color: var(--text-tertiary);">No clients found</div>';
            return;
        }
        
        const html = clients.map(client => `
            <div class="client-option" 
                 data-client-id="${client.id}"
                 data-client-name="${client.name}">
                <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;">
                    <div>
                        <div style="font-size: 13px; font-weight: 650; color: var(--text-primary);">${client.name}</div>
                        ${client.company ? `<div style="margin-top: 4px; font-size: 12px; color: var(--text-tertiary);">${client.company}</div>` : ''}
                        ${client.email ? `<div style="margin-top: 4px; font-size: 12px; color: var(--text-tertiary);">${client.email}</div>` : ''}
                    </div>
                    ${client.id === this.selectedClient?.id ? 
                        '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" style="color: var(--success); margin-top: 2px;"><path stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"></path></svg>' : 
                        ''
                    }
                </div>
            </div>
        `).join('');
        
        this.clientList.innerHTML = html;
        
        // Add click handlers
        this.clientList.querySelectorAll('.client-option').forEach(option => {
            option.addEventListener('click', () => {
                this.selectClient({
                    id: parseInt(option.dataset.clientId),
                    name: option.dataset.clientName
                });
            });
        });
    }
    
    selectClient(client) {
        this.selectedClient = client;
        this.searchInput.value = client.name;
        this.hiddenInput.value = client.id;
        this.hideDropdown();
        
        // Update display to show selection
        this.renderClients(this.clients.filter(c => 
            c.name.toLowerCase().includes(this.searchInput.value.toLowerCase())
        ));
    }
    
    handleKeydown(e) {
        const options = this.clientList.querySelectorAll('.client-option');
        const currentIndex = Array.from(options).findIndex(opt => 
            opt.classList.contains('client-option--active')
        );
        
        switch (e.key) {
            case 'ArrowDown':
                e.preventDefault();
                if (currentIndex < options.length - 1) {
                    if (currentIndex >= 0) options[currentIndex].classList.remove('client-option--active');
                    options[currentIndex + 1].classList.add('client-option--active');
                    options[currentIndex + 1].scrollIntoView({ block: 'nearest' });
                }
                break;
                
            case 'ArrowUp':
                e.preventDefault();
                if (currentIndex > 0) {
                    options[currentIndex].classList.remove('client-option--active');
                    options[currentIndex - 1].classList.add('client-option--active');
                    options[currentIndex - 1].scrollIntoView({ block: 'nearest' });
                }
                break;
                
            case 'Enter':
                e.preventDefault();
                if (currentIndex >= 0) {
                    options[currentIndex].click();
                }
                break;
                
            case 'Escape':
                this.hideDropdown();
                break;
        }
    }
}

// Initialize client search and mobile sidebar when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    new ClientSearch();
    toggleCustomDate();

    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', function () {
            window.openAppSidebar();
        });
    }
});

function showPaymentModal(invoiceId, invoiceNumber, amountDue) {
    // Set form values
    const invoiceIdField = document.getElementById('paymentInvoiceId');
    const invoiceInfoField = document.getElementById('paymentInvoiceInfo');
    const amountDueField = document.getElementById('paymentAmountDue');
    
    if (invoiceIdField) invoiceIdField.value = invoiceId;
    if (invoiceInfoField) invoiceInfoField.textContent = invoiceNumber;
    if (amountDueField) amountDueField.textContent = CURRENCY + ' ' + amountDue.toFixed(2);
    
    // Set max amount for payment input
    const paymentInput = document.querySelector('input[name="amount"]');
    if (paymentInput) {
        paymentInput.max = amountDue.toFixed(2);
        paymentInput.placeholder = 'Max: ' + CURRENCY + ' ' + amountDue.toFixed(2);
        paymentInput.dataset.amountDue = amountDue.toFixed(2);
    }
    
    // Show modal
    const modal = document.getElementById('paymentModal');
    if (modal) {
        modal.style.display = 'flex';
    }
}

function closePaymentModal() {
    const modal = document.getElementById('paymentModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function toggleCustomDate() {
    const dateFilterEl = document.querySelector('select[name="date_filter"]');
    const customDateRange = document.getElementById('customDateRange');
    if (!dateFilterEl || !customDateRange) return;

    if (dateFilterEl.value === 'custom') {
        customDateRange.classList.remove('hidden');
    } else {
        customDateRange.classList.add('hidden');
    }
}

// Initialize custom date visibility
document.addEventListener('DOMContentLoaded', function() {
    toggleCustomDate();
});
</script>
</div>
</div>
</body>
</html>
