<?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'];
}

// For filter submissions, use session workspace instead of URL validation
$isFilterSubmission = isset($_GET['client_search']) || isset($_GET['filter_label']) || isset($_GET['filter_client']);

if ($isFilterSubmission && isset($_SESSION['workspace'])) {
    // Use session workspace for filter submissions
    $workspace = $_SESSION['workspace'];
    require_once __DIR__ . '/../src/db.php';
    require_once __DIR__ . '/../src/Proposal.php';
    require_once __DIR__ . '/../src/TenantDB.php';
} else {
    // Use full workspace validation for normal access
    require_once __DIR__ . '/../src/secure_workspace.php';
    require_once __DIR__ . '/../src/Proposal.php';
    require_once __DIR__ . '/../src/TenantDB.php';
}

require_once __DIR__ . '/../src/Permissions/require_permission.php';

// Check permission
requirePermission('proposals_view');

// Get action-specific permissions
$canCreateProposal = hasPermission('proposals_create');
$canEditProposal = hasPermission('proposals_edit');
$canDeleteProposal = hasPermission('proposals_delete');

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

$pdo = getPDO();

// Normalize workspace value for downstream use (favor explicit query param, fall back to session)
$workspace = $_GET['workspace'] ?? ($workspace ?? ($_SESSION['workspace'] ?? null));

// Get current workspace company ID
$companyId = null;
$companyRecord = null;
if ($workspace) {
    $stmt = $pdo->prepare("SELECT * FROM companies WHERE username = ?");
    $stmt->execute([$workspace]);
    $companyRecord = $stmt->fetch() ?: null;
    $companyId = $companyRecord['id'] ?? null;
}
if (!$companyId) {
    $companyId = TenantDB::getTenant();
    if ($companyId) {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
        $stmt->execute([$companyId]);
        $companyRecord = $stmt->fetch() ?: $companyRecord;
    }
}
$companyDisplayName = $companyRecord['name'] ?? 'Workspace';
$workspaceSlug = $workspace ?: ($companyRecord['username'] ?? ($companyRecord['id'] ?? null));
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';

// Ensure tenant context matches the active workspace so downstream deletes/updates work
if ($companyId) {
    TenantDB::setTenant((int) $companyId);
}

// Handle delete action (now that tenant context is guaranteed)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    $proposalId = (int) ($_POST['proposal_id'] ?? 0);
    if ($proposalId > 0) {
        Proposal::delete($proposalId);

        // Log proposal deletion in workspace activity (best-effort)
        workspace_log(
            'proposal_deleted',
            'proposal',
            $proposalId,
            null,
            null,
            null
        );
        // Redirect to refresh the page with workspace parameter
        $workspaceParam = $workspace ? '&workspace=' . urlencode($workspace) : '';
        header('Location: /proposals.php?success=deleted' . $workspaceParam);
        exit;
    }
}

$successMessage = $_GET['success'] ?? null;
if ($successMessage === 'deleted') {
    $successMessage = 'Proposal deleted successfully.';
} elseif ($successMessage === 'updated') {
    $successMessage = 'Proposal updated and PDF regenerated successfully.';
}

// Get all proposals for current workspace
$proposals = $pdo->prepare(
    "SELECT p.*, c.name as client_name, c.company as client_company, t.name as template_name
     FROM proposals p
     LEFT JOIN clients c ON p.client_id = c.id
     LEFT JOIN templates t ON p.template_id = t.id
     WHERE p.company_id = ?
     ORDER BY p.created_at DESC"
);
$proposals->execute([$companyId]);
$proposals = $proposals->fetchAll();

// Get unique clients for current workspace
$clients = $pdo->prepare("SELECT DISTINCT c.id, c.name, c.company FROM clients c WHERE c.company_id = ? ORDER BY c.name");
$clients->execute([$companyId]);
$clients = $clients->fetchAll();

// Get unique labels for current workspace
$labels = $pdo->prepare("SELECT DISTINCT label FROM proposal_labels WHERE label IS NOT NULL AND label != '' AND proposal_id IN (SELECT id FROM proposals WHERE company_id = ?) ORDER BY label");
$labels->execute([$companyId]);
$labels = $labels->fetchAll();

// Handle filters
$filterClient = $_GET['filter_client'] ?? '';
$filterLabel = $_GET['filter_label'] ?? '';

if ($filterClient) {
    $proposals = array_filter($proposals, fn($p) => $p['client_id'] == $filterClient);
}

if ($filterLabel) {
    $proposalIdsStmt = $pdo->prepare(
        "SELECT DISTINCT proposal_id FROM proposal_labels WHERE label = ?"
    );
    $proposalIdsStmt->execute([$filterLabel]);
    $proposalIds = $proposalIdsStmt->fetchAll(PDO::FETCH_COLUMN);
    $proposals = array_filter($proposals, fn($p) => in_array($p['id'], $proposalIds));
}

// Calculate summary stats
$totalProposals = count($proposals);
$totalCompleted = count(array_filter($proposals, fn($p) => ($p['status'] ?? 'draft') === 'sent'));
$totalDrafts = count(array_filter($proposals, fn($p) => ($p['status'] ?? 'draft') === 'draft'));

?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Proposals · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Proposals', $currentTheme); ?>

<div class="main-container">
        <?php
        require_once __DIR__ . '/components/headers/page-header.php';
        
        $actions = [];
        if ($canCreateProposal) {
            $actions[] = ['label' => 'New proposal', 'url' => '/generate.php', 'type' => 'primary', 'icon' => 'M12 4v16m8-8H4', 'append_workspace' => true];
        }
        
        renderPageHeader(
            breadcrumbs: [
                ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php', 'icon' => 'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2z']
            ],
            currentPage: 'All proposals',
            actions: $actions,
            workspaceQuery: $workspaceQuery
        );
        ?>

    <div class="dash-container">
        <?php if ($successMessage): ?>
            <div class="status-banner success" style="margin-bottom: 20px;">
                <svg style="width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                </svg>
                <span><?= h($successMessage) ?></span>
            </div>
        <?php endif; ?>

        <!-- Hero Section -->
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                    <div style="display: flex; flex-direction: column; gap: 12px;">
                        <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">
                            <div>
                                <p class="section-title">Proposals</p>
                                <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 4px 0;">Pipeline for <?= htmlspecialchars($companyDisplayName) ?></h2>
                                <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Draft, send, and track proposals across every client in this workspace.</p>
                            </div>
                            <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                                <span class="status-chip" style="background: var(--bg-surface); border: 1px solid var(--border-default);">
                                    <svg style="width: 12px; height: 12px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                    </svg>
                                    <?= count($proposals) ?> active
                                </span>
                                <?php if ($canCreateProposal): ?>
                                    <a href="/generate.php<?= $workspaceQuery ?>" class="btn-emerald">
                                        <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="M12 4v16m8-8H4"></path>
                                        </svg>
                                        Create proposal
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
            </section>
        </div>

        <!-- Stats Grid -->
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                    <div style="margin-bottom: 16px;">
                        <p class="section-title">Snapshot</p>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Quick totals across your proposal pipeline</p>
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px;">
                        <?php
                        $snapshot = [
                            ['label' => 'Total proposals', 'value' => $totalProposals, 'hint' => 'Across this workspace', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'],
                            ['label' => 'Completed', 'value' => $totalCompleted, 'hint' => 'Marked as sent', 'icon' => 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'],
                            ['label' => 'Drafts', 'value' => $totalDrafts, 'hint' => 'Still in progress', 'icon' => 'M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z'],
                        ];
                        foreach ($snapshot as $card):
                        ?>
                            <div style="background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: 6px; padding: 14px;">
                                <div style="display: flex; align-items: center; justify-content: space-between;">
                                    <div>
                                        <p style="font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-tertiary); margin-bottom: 6px;"><?= htmlspecialchars($card['label']) ?></p>
                                        <p style="font-size: 20px; font-weight: 600; color: var(--text-primary); margin: 4px 0;"><?= htmlspecialchars((string) $card['value']) ?></p>
                                        <p style="font-size: 11px; color: var(--text-secondary); margin-top: 4px;"><?= htmlspecialchars($card['hint']) ?></p>
                                    </div>
                                    <div>
                                        <svg style="width: 18px; height: 18px; color: var(--text-tertiary);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="<?= $card['icon'] ?>"></path>
                                        </svg>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
            </section>
        </div>

        <!-- Filters -->
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                    <div style="margin-bottom: 16px;">
                        <p class="section-title">Filters</p>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Narrow down proposals by client or label</p>
                    </div>
                    <form id="filterForm" method="GET" action="/proposals.php">
                        <input type="hidden" name="workspace" value="<?= h($workspace) ?>">
                        <div style="display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end;">
                            <div style="flex: 1; min-width: 200px;">
                                <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Search client</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="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                                    </svg>
                                    <input type="text"
                                           id="clientSearch"
                                           name="client_search"
                                           value="<?= h($_GET['client_search'] ?? '') ?>"
                                           placeholder="Search clients..."
                                           class="input"
                                           style="padding-left: 36px;"
                                           autocomplete="off">
                                    <input type="hidden" id="clientId" name="filter_client" value="<?= h($_GET['filter_client'] ?? '') ?>">
                                    <div id="clientDropdown" style="display: none; position: absolute; z-index: 20; width: 100%; margin-top: 4px; background: var(--bg-card); border: 1px solid var(--border-default); border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); max-height: 240px; overflow-y: auto;">
                                        <div style="padding: 8px;">
                                            <div style="font-size: 10px; font-weight: 600; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 8px; padding: 0 8px;">Clients</div>
                                            <div id="clientList">
                                                <div style="padding: 8px; font-size: 11px; color: var(--text-tertiary);">Type to search clients...</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div style="flex: 1; min-width: 200px;">
                                <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Filter by label</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="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                                    </svg>
                                    <select id="filterLabel" name="filter_label" class="input" style="padding-left: 36px; appearance: none;">
                                        <option value="">All labels</option>
                                        <?php foreach ($labels as $label): ?>
                                            <option value="<?= h($label['label']) ?>" <?= $filterLabel == $label['label'] ? 'selected' : '' ?>>
                                                <?= h($label['label']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </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="/proposals.php?workspace=<?= h($workspace) ?>" 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>

        <!-- Proposal list -->
        <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">Proposal list</p>
                            <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Showing <?= count($proposals) ?> proposal<?= count($proposals) === 1 ? '' : 's' ?></p>
                        </div>
                        <?php if ($canCreateProposal): ?>
                            <a href="/generate.php<?= isset($_GET['workspace']) ? '?workspace=' . urlencode($_GET['workspace']) : '' ?>" 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="M12 4v16m8-8H4"></path>
                                </svg>
                                New
                            </a>
                        <?php endif; ?>
                    </div>
                    <div style="overflow-x: auto;">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Proposal</th>
                                    <th>Client</th>
                                    <th>Proposal type</th>
                                    <th>Status</th>
                                    <th style="text-align: center;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($proposals): ?>
                                    <?php foreach ($proposals as $proposal): ?>
                                        <?php
                                        $proposalLabelsStmt = $pdo->prepare(
                                            "SELECT label FROM proposal_labels WHERE proposal_id = ?"
                                        );
                                        $proposalLabelsStmt->execute([$proposal['id']]);
                                        $proposalLabels = $proposalLabelsStmt->fetchAll(PDO::FETCH_COLUMN);
                                        ?>
                                        <tr>
                                            <td style="vertical-align: top;">
                                                <div style="display: flex; flex-direction: column; gap: 2px;">
                                                    <a href="/generate.php?step=4&proposal_id=<?= (int) $proposal['id'] ?><?= isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '' ?>" style="font-size: 13px; font-weight: 500; color: var(--text-primary); text-decoration: none;">
                                                        <?= h($proposal['title']) ?>
                                                    </a>
                                                    <div style="font-size: 11px; color: var(--text-secondary);"><?= h($proposal['proposal_number'] ?? 'PRO-' . $proposal['id']) ?></div>
                                                    <div style="font-size: 11px; color: var(--text-tertiary);"><?= date('M j, Y', strtotime($proposal['created_at'])) ?></div>
                                                </div>
                                            </td>
                                            <td style="vertical-align: top;">
                                                <div style="font-size: 13px; color: var(--text-primary);">
                                                    <?= h($proposal['client_name'] ?? 'Unknown') ?>
                                                </div>
                                                <?php if ($proposal['client_company']): ?>
                                                    <div style="font-size: 11px; color: var(--text-secondary);">
                                                        <?= h($proposal['client_company']) ?>
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td style="vertical-align: top;">
                                                <?php if ($proposalLabels): ?>
                                                    <div style="display: flex; flex-wrap: wrap; gap: 4px;">
                                                        <?php foreach ($proposalLabels as $label): ?>
                                                            <span style="display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 999px; font-size: 11px; font-weight: 500; background: var(--bg-hover); color: var(--text-secondary); border: 1px solid var(--border-default);">
                                                                <?= h($label) ?>
                                                            </span>
                                                        <?php endforeach; ?>
                                                    </div>
                                                <?php else: ?>
                                                    <span style="display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 999px; font-size: 11px; font-weight: 500; background: var(--bg-surface); color: var(--text-secondary); border: 1px solid var(--border-default);">
                                                        Unassigned
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                            <td style="vertical-align: top;">
                                                <span style="display: inline-flex; align-items: center; padding: 3px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; background: var(--bg-hover); color: var(--text-primary); border: 1px solid var(--border-default);">
                                                    <?= h(ucfirst($proposal['status'] ?? 'draft')) ?>
                                                </span>
                                            </td>
                                            <td style="vertical-align: top; text-align: center;">
                                                <div style="display: flex; justify-content: center; gap: 6px;">
                                                    <a href="/generate.php?step=4&proposal_id=<?= (int) $proposal['id'] ?><?= isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '' ?>"
                                                       class="btn-secondary" style="padding: 4px 10px; font-size: 11px;">
                                                        View
                                                    </a>
                                                    <form method="POST" onsubmit="return confirm('Are you sure you want to delete this proposal? This action cannot be undone.')" style="display: inline;">
                                                        <input type="hidden" name="action" value="delete">
                                                        <input type="hidden" name="proposal_id" value="<?= (int) $proposal['id'] ?>">
                                                        <button type="submit" class="btn-secondary" style="padding: 4px 10px; font-size: 11px; color: #f97373;">
                                                            Delete
                                                        </button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5">
                                            <div style="padding: 24px; text-align: center;">
                                                <div style="width: 48px; height: 48px; border-radius: 8px; margin: 0 auto 12px; display: flex; align-items: center; justify-content: center; background: var(--bg-surface); border: 1px solid var(--border-default); color: var(--text-secondary);">
                                                    <svg style="width: 20px; height: 20px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                                    </svg>
                                                </div>
                                                <h3 style="font-size: 13px; font-weight: 500; color: var(--text-primary); margin-bottom: 4px;">No proposals found</h3>
                                                <p style="font-size: 11px; color: var(--text-secondary); margin: 0 0 12px; max-width: 360px; margin-left: auto; margin-right: auto;">Start by creating your first proposal to see it here. You can manage clients and templates to get started.</p>
                                                <a href="/generate.php<?= isset($_GET['workspace']) ? '?workspace=' . urlencode($_GET['workspace']) : '' ?>" class="btn-primary" style="font-size: 12px; padding: 6px 12px;">
                                                    <svg style="width: 14px; height: 14px; margin-right: 4px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                                    </svg>
                                                    Create your first proposal
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
            </section>
        </div>
    </div>
</div>

<script>
// Client data for search
const CLIENTS = <?= json_encode($clients) ?>;

// 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 + (client.company ? ` ${client.company}` : '');
            }
        }
        
        // Event listeners
        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();
            }
        });
        
        // Show dropdown when focusing input
        this.searchInput.addEventListener('focus', () => {
            this.showDropdown();
            if (!this.searchInput.value) {
                this.renderClients(this.clients.slice(0, 50));
            } else {
                this.handleSearch(this.searchInput.value);
            }
        });
    }
    
    showDropdown() {
        this.dropdown.classList.remove('hidden');
    }
    
    hideDropdown() {
        this.dropdown.classList.add('hidden');
    }
    
    handleSearch(query) {
        const filtered = this.clients.filter(client => 
            client.name.toLowerCase().includes(query.toLowerCase()) ||
            (client.company && client.company.toLowerCase().includes(query.toLowerCase()))
        );
        this.renderClients(filtered.slice(0, 50));
    }
    
    renderClients(clients) {
        this.clientList.innerHTML = '';
        
        if (clients.length === 0) {
            this.clientList.innerHTML = `
                <div class="px-2 py-1 text-sm text-slate-500">
                    No clients found
                </div>
            `;
            return;
        }
        
        clients.forEach(client => {
            const item = document.createElement('div');
            item.className = 'px-2 py-2 hover:bg-emerald-50 cursor-pointer rounded transition-colors duration-200';
            item.innerHTML = `
                <div class="flex items-center justify-between">
                    <div>
                        <div class="font-medium text-slate-900">${client.name}</div>
                        ${client.company ? `<div class="text-sm text-slate-500">${client.company}</div>` : ''}
                    </div>
                    <svg class="w-4 h-4 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                    </svg>
                </div>
            `;
            item.addEventListener('click', () => this.selectClient(client));
            this.clientList.appendChild(item);
        });
    }
    
    selectClient(client) {
        this.selectedClient = client;
        this.searchInput.value = client.name + (client.company ? ` ${client.company}` : '');
        this.hiddenInput.value = client.id;
        this.hideDropdown();
        updateFilters();
    }
    
    handleKeydown(e) {
        const items = this.clientList.querySelectorAll('[role="option"]');
        let currentIndex = -1;
        
        items.forEach((item, index) => {
            if (item.classList.contains('bg-emerald-50')) {
                currentIndex = index;
            }
        });
        
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (currentIndex < items.length - 1) {
                if (currentIndex >= 0) items[currentIndex].classList.remove('bg-emerald-50');
                items[currentIndex + 1].classList.add('bg-emerald-50');
                items[currentIndex + 1].scrollIntoView({ block: 'nearest' });
            }
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            if (currentIndex > 0) {
                items[currentIndex].classList.remove('bg-emerald-50');
                items[currentIndex - 1].classList.add('bg-emerald-50');
                items[currentIndex - 1].scrollIntoView({ block: 'nearest' });
            }
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (currentIndex >= 0 && items[currentIndex]) {
                items[currentIndex].click();
            }
        } else if (e.key === 'Escape') {
            this.hideDropdown();
        }
    }
}

// Filter functionality
document.getElementById('filterLabel').addEventListener('change', function() {
    updateFilters();
});

function updateFilters() {
    const client = document.getElementById('clientId').value;
    const label = document.getElementById('filterLabel').value;
    
    const params = new URLSearchParams(window.location.search);
    // Clear existing filter params
    params.delete('filter_client');
    params.delete('filter_label');
    params.delete('success');

    if (client) params.set('filter_client', client);
    if (label) params.set('filter_label', label);

    const url = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
    window.location.href = url;
}

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

    // Wire mobile menu button to app sidebar toggle from navigation.php
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', function () {
            window.openAppSidebar();
        });
    }
});
</script>
</body>
</html>
