<?php
require_once __DIR__ . '/auth-check.php';
require_once __DIR__ . '/../includes/functions.php';

$leads = getData('leads');
$statusFilter = $_GET['status'] ?? 'all';

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['lead_id']) && !empty($_POST['new_status'])) {
    $updated = false;
    foreach ($leads as &$lead) {
        if ($lead['id'] == $_POST['lead_id']) {
            $lead['status'] = $_POST['new_status'];
            $updated = true;
            break;
        }
    }
    if ($updated) {
        saveData('leads', $leads);
        setFlash('success', 'Status updated successfully');
        header('Location: leads.php?status=' . urlencode($statusFilter));
        exit;
    }
}

// Filter leads
if ($statusFilter !== 'all') {
    $leads = array_filter($leads, fn($l) => ($l['status'] ?? '') === $statusFilter);
}

// Sort by date descending
usort($leads, fn($a, $b) => strcmp($b['date'] ?? '', $a['date'] ?? ''));

$pageTitle = 'Enquiries';
include __DIR__ . '/sidebar.php';
?>

<div class="admin-header">
    <h1 class="admin-title">Enquiries</h1>
    <a href="#" class="btn-admin-outline" onclick="exportCSV();return false;" style="font-size:0.8rem;">Export CSV</a>
</div>

<!-- Filter -->
<div class="admin-card mb-3" style="padding:1rem;">
    <form method="GET" class="row g-2 align-items-end">
        <div class="col-auto">
            <label style="font-size:0.75rem;color:var(--muted);text-transform:uppercase;">Status</label>
            <select name="status" class="form-select form-select-sm" onchange="this.form.submit()" style="background:var(--bg2);color:var(--text);border-color:var(--border);font-size:0.85rem;">
                <option value="all" <?php echo $statusFilter === 'all' ? 'selected' : ''; ?>>All</option>
                <option value="New" <?php echo $statusFilter === 'New' ? 'selected' : ''; ?>>New</option>
                <option value="Contacted" <?php echo $statusFilter === 'Contacted' ? 'selected' : ''; ?>>Contacted</option>
                <option value="Replied" <?php echo $statusFilter === 'Replied' ? 'selected' : ''; ?>>Replied</option>
                <option value="Closed" <?php echo $statusFilter === 'Closed' ? 'selected' : ''; ?>>Closed</option>
            </select>
        </div>
    </form>
</div>

<div class="admin-card">
    <?php if (!empty($leads)): ?>
    <div class="table-responsive">
        <table class="admin-table" id="leadsTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name / Company</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Type</th>
                    <th>Date</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($leads as $lead):
                    $name = ($lead['form_type'] ?? '') === 'register'
                        ? e(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? ''))
                        : e($lead['name'] ?? '');
                    $company = e($lead['company_name'] ?? $lead['company'] ?? '');
                    $statusColors = [
                        'New' => 'badge-new',
                        'Contacted' => 'badge-contacted',
                        'Replied' => 'badge-replied',
                        'Closed' => 'badge-closed',
                    ];
                    $statusClass = $statusColors[$lead['status'] ?? 'New'] ?? 'badge-new';
                ?>
                <tr>
                    <td style="font-size:0.82rem;color:var(--muted);">#<?php echo e($lead['id']); ?></td>
                    <td>
                        <strong style="font-size:0.88rem;"><?php echo $name; ?></strong>
                        <?php if ($company): ?><br><small style="color:var(--muted);"><?php echo $company; ?></small><?php endif; ?>
                    </td>
                    <td><a href="mailto:<?php echo e($lead['email'] ?? ''); ?>" style="color:var(--green2);text-decoration:none;font-size:0.85rem;"><?php echo e($lead['email'] ?? ''); ?></a></td>
                    <td style="font-size:0.82rem;"><?php echo e($lead['phone'] ?? ''); ?></td>
                    <td>
                        <?php if (($lead['form_type'] ?? '') === 'register'): ?>
                        <span style="display:inline-block;background:rgba(46,125,50,0.2);color:#4ade80;font-size:0.7rem;padding:0.2rem 0.5rem;border-radius:4px;text-transform:uppercase;">Register</span>
                        <?php else: ?>
                        <span style="display:inline-block;background:rgba(96,165,250,0.2);color:#60a5fa;font-size:0.7rem;padding:0.2rem 0.5rem;border-radius:4px;text-transform:uppercase;">Contact</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-size:0.8rem;color:var(--muted);"><?php echo e($lead['date'] ?? ''); ?></td>
                    <td>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="lead_id" value="<?php echo e($lead['id']); ?>">
                            <select name="new_status" onchange="this.form.submit()" class="status-badge <?php echo $statusClass; ?>" style="cursor:pointer;font-size:0.72rem;border:none;background:transparent;">
                                <option value="New" <?php echo ($lead['status'] ?? '') === 'New' ? 'selected' : ''; ?>>New</option>
                                <option value="Contacted" <?php echo ($lead['status'] ?? '') === 'Contacted' ? 'selected' : ''; ?>>Contacted</option>
                                <option value="Replied" <?php echo ($lead['status'] ?? '') === 'Replied' ? 'selected' : ''; ?>>Replied</option>
                                <option value="Closed" <?php echo ($lead['status'] ?? '') === 'Closed' ? 'selected' : ''; ?>>Closed</option>
                            </select>
                        </form>
                    </td>
                    <td>
                        <a href="lead-detail.php?id=<?php echo e($lead['id']); ?>" class="btn-admin-outline" style="font-size:0.7rem;padding:0.3rem 0.6rem;">View</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <p style="color:var(--muted);text-align:center;padding:2rem;">No enquiries found.</p>
    <?php endif; ?>
</div>

<script>
function exportCSV() {
    const table = document.getElementById('leadsTable');
    if (!table) return;
    let csv = [];
    const rows = table.querySelectorAll('tr');
    rows.forEach(row => {
        let cols = row.querySelectorAll('td, th');
        let rowData = [];
        cols.forEach(col => rowData.push('"' + col.textContent.replace(/"/g, '""').trim() + '"'));
        csv.push(rowData.join(','));
    });
    const blob = new Blob([csv.join('\n')], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'leads-<?php echo date('Y-m-d'); ?>.csv';
    a.click();
    URL.revokeObjectURL(url);
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
