<?php
// Resources/views/pages/leads/index.php
?>
<div class="dashboard-container">
    <!-- Header -->
    <header class="dashboard-header">
        <div class="header-content">
            <div class="welcome-section">
                <h1>Leads Overview</h1>
                <p>Track, score, and nurture your leads with AI assistance.</p>
            </div>
            <div class="header-actions">
                <a href="/lead-management/public/app/leads/create"
                    class="btn-primary"
                    style="padding: 0.75rem 1.5rem; background: var(--primary); color: white; border-radius: var(--radius); font-weight: 600; text-decoration:none; border:none; display:inline-flex; align-items:center; gap:.5rem;">
                    <i class="fas fa-plus"></i> New Lead
                </a>
            </div>
        </div>

        <!-- Quick Stats -->
        <div class="quick-stats">
            <div class="stat-card">
                <div class="stat-number">
                    <?= (int)($stats['total_leads'] ?? 0) ?>
                </div>
                <div class="stat-label">Total Leads</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">
                    <?= (int)($stats['leads_today'] ?? 0) ?>
                </div>
                <div class="stat-label">New Today</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">
                    <?= (int)($stats['high_priority_leads'] ?? 0) ?>
                </div>
                <div class="stat-label">High Priority (AI ≥ 80)</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">
                    <?= (int)($stats['converted_leads'] ?? 0) ?>
                </div>
                <div class="stat-label">Converted</div>
            </div>
        </div>
    </header>

    <!-- Filters + Search -->
    <section class="tasks-section" style="margin-top: 0;">
        <div class="section-header" style="margin-bottom:1rem;">
            <h2><i class="fas fa-filter"></i> Filters</h2>
        </div>
        <form
            action="/lead-management/public/app/leads"
            method="GET"
            class="filters-form"
            style="display:flex; flex-wrap:wrap; gap:1rem; align-items:flex-end;">
            <!-- Status Filter -->
            <div style="display:flex; flex-direction:column; min-width:180px;">
                <label for="status" style="font-size:.85rem; font-weight:600; color:var(--sky-700); margin-bottom:.25rem;">
                    Status
                </label>
                <select
                    id="status"
                    name="status"
                    style="padding:.6rem .8rem; border-radius:8px; border:1px solid var(--sky-200); background:#fff;">
                    <?php
                    $currentStatus = $filters['status'] ?? 'all';
                    $statuses = [
                        'all'       => 'All',
                        'new'       => 'New',
                        'active'    => 'Active',
                        'converted' => 'Converted',
                        'lost'      => 'Lost',
                    ];
                    foreach ($statuses as $value => $label): ?>
                        <option value="<?= htmlspecialchars($value) ?>"
                            <?= $currentStatus === $value ? 'selected' : '' ?>>
                            <?= htmlspecialchars($label) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Search -->
            <div style="flex:1; min-width:220px; display:flex; flex-direction:column;">
                <label for="q" style="font-size:.85rem; font-weight:600; color:var(--sky-700); margin-bottom:.25rem;">
                    Search (name, email, company)
                </label>
                <div style="position:relative;">
                    <input
                        type="text"
                        id="q"
                        name="q"
                        value="<?= htmlspecialchars($filters['q'] ?? '') ?>"
                        placeholder="Search leads..."
                        style="width:100%; padding:.6rem .9rem .6rem 2.1rem; border-radius:8px; border:1px solid var(--sky-200); background:#fff;">
                    <i class="fas fa-search"
                        style="position:absolute; left:.7rem; top:50%; transform:translateY(-50%); color:var(--sky-500); font-size:.9rem;"></i>
                </div>
            </div>

            <!-- Submit -->
            <div>
                <button type="submit"
                    class="btn-primary"
                    style="padding:.65rem 1.4rem; background:var(--primary); color:#fff; border:none; border-radius:var(--radius); font-weight:600; cursor:pointer;">
                    Apply
                </button>
            </div>
        </form>
    </section>

    <!-- Leads Table & AI Email Output -->
    <div class="dashboard-grid" style="margin-top:1rem;">
        <div class="left-column">
            <section class="reports-section" style="margin-bottom:1.5rem;">
                <div class="section-header">
                    <h2><i class="fas fa-users"></i> Leads</h2>
                </div>

                <?php if (empty($leads)): ?>
                    <p>No leads found. Try adjusting filters or create a new lead.</p>
                <?php else: ?>
                    <div class="table-wrapper" style="overflow-x:auto;">
                        <table class="leads-table"
                            style="width:100%; border-collapse:collapse; font-size:.9rem;">
                            <thead>
                                <tr style="border-bottom:1px solid var(--sky-200); color:var(--sky-700); text-align:left;">
                                    <th style="padding:.75rem;">Lead</th>
                                    <th style="padding:.75rem;">Company</th>
                                    <th style="padding:.75rem;">Source</th>
                                    <th style="padding:.75rem;">Status</th>
                                    <th style="padding:.75rem;">AI Score</th>
                                    <th style="padding:.75rem;">Created</th>
                                    <th style="padding:.75rem; text-align:right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($leads as $lead): ?>
                                    <?php
                                    $status = $lead['status'] ?? 'new';
                                    $score  = $lead['ai_score'] ?? null;
                                    $scoreCategory = $lead['ai_score_category'] ?? null;

                                    // Status badge color
                                    $statusClass = 'status-pill';
                                    switch ($status) {
                                        case 'converted':
                                            $statusClass .= ' status-converted';
                                            break;
                                        case 'active':
                                            $statusClass .= ' status-active';
                                            break;
                                        case 'lost':
                                            $statusClass .= ' status-lost';
                                            break;
                                        default:
                                            $statusClass .= ' status-new';
                                    }

                                    // Score chip color
                                    $scoreClass = 'score-pill score-none';
                                    if ($score !== null) {
                                        if ($score >= 80) {
                                            $scoreClass = 'score-pill score-high';
                                        } elseif ($score >= 50) {
                                            $scoreClass = 'score-pill score-medium';
                                        } else {
                                            $scoreClass = 'score-pill score-low';
                                        }
                                    }
                                    ?>
                                    <tr style="border-bottom:1px solid var(--sky-100);">
                                        <!-- Lead / contact -->
                                        <td style="padding:.75rem; vertical-align:top;">
                                            <div style="font-weight:600; color:var(--sky-800);">
                                                <?= htmlspecialchars($lead['full_name'] ?: $lead['first_name'] ?? 'Unknown') ?>
                                            </div>
                                            <?php if (!empty($lead['email'])): ?>
                                                <div style="color:var(--sky-700); font-size:.8rem;">
                                                    <i class="fas fa-envelope"></i>
                                                    <?= htmlspecialchars($lead['email']) ?>
                                                </div>
                                            <?php endif; ?>
                                            <?php if (!empty($lead['phone'])): ?>
                                                <div style="color:var(--sky-700); font-size:.8rem;">
                                                    <i class="fas fa-phone"></i>
                                                    <?= htmlspecialchars($lead['phone']) ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>

                                        <!-- Company -->
                                        <td style="padding:.75rem; vertical-align:top;">
                                            <?php if (!empty($lead['company'])): ?>
                                                <div style="font-weight:500;">
                                                    <?= htmlspecialchars($lead['company']) ?>
                                                </div>
                                            <?php else: ?>
                                                <span style="color:var(--sky-600); font-size:.8rem;">—</span>
                                            <?php endif; ?>
                                            <?php if (!empty($lead['industry'])): ?>
                                                <div style="color:var(--sky-700); font-size:.8rem;">
                                                    <?= htmlspecialchars($lead['industry']) ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>

                                        <!-- Source -->
                                        <td style="padding:.75rem; vertical-align:top;">
                                            <?php if (!empty($lead['form_name'])): ?>
                                                <div style="font-size:.8rem; color:var(--sky-700);">
                                                    <i class="fas fa-file-alt"></i>
                                                    <?= htmlspecialchars($lead['form_name']) ?>
                                                </div>
                                            <?php endif; ?>
                                            <div style="font-size:.8rem; color:var(--sky-600);">
                                                <?= htmlspecialchars($lead['source'] ?? 'manual') ?>
                                            </div>
                                        </td>

                                        <!-- Status -->
                                        <td style="padding:.75rem; vertical-align:top;">
                                            <span class="<?= $statusClass ?>"
                                                style="display:inline-flex; align-items:center; padding:.2rem .6rem; border-radius:999px; font-size:.75rem; font-weight:600;">
                                                <?= htmlspecialchars(ucfirst($status)) ?>
                                            </span>
                                        </td>

                                        <!-- AI score -->
                                        <td style="padding:.75rem; vertical-align:top;">
                                            <span class="<?= $scoreClass ?>"
                                                data-score-pill="<?= (int)$lead['id'] ?>"
                                                style="display:inline-flex; flex-direction:column; align-items:flex-start; gap:2px; padding:.25rem .6rem; border-radius:999px; font-size:.75rem; font-weight:600;">
                                                <?php if ($score !== null): ?>
                                                    <span><?= (int)$score ?>/100</span>
                                                    <?php if ($scoreCategory): ?>
                                                        <span style="font-size:.7rem; opacity:.8;">
                                                            <?= htmlspecialchars($scoreCategory) ?>
                                                        </span>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span>No score</span>
                                                <?php endif; ?>
                                            </span>
                                        </td>

                                        <!-- Created -->
                                        <td style="padding:.75rem; font-size:.8rem; color:var(--sky-700); vertical-align:top;">
                                            <?= htmlspecialchars(
                                                isset($lead['created_at'])
                                                    ? date('M d, Y', strtotime($lead['created_at']))
                                                    : '—'
                                            ) ?>
                                        </td>

                                        <!-- Actions -->
                                        <td style="padding:.75rem; text-align:right; white-space:nowrap; vertical-align:top;">
                                            <a href="/lead-management/public/app/leads/<?= (int)$lead['id'] ?>"
                                                title="View"
                                                style="margin-right:.25rem; text-decoration:none; font-size:.9rem; color:var(--primary);">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="/lead-management/public/app/leads/<?= (int)$lead['id'] ?>/edit"
                                                title="Edit"
                                                style="margin-right:.25rem; text-decoration:none; font-size:.9rem; color:var(--sky-700);">
                                                <i class="fas fa-pen"></i>
                                            </a>
                                            <a href="/lead-management/public/app/leads/<?= (int)$lead['id'] ?>/delete"
                                                title="Delete"
                                                onclick="return confirm('Delete this lead?');"
                                                style="margin-right:.5rem; text-decoration:none; font-size:.9rem; color:var(--danger);">
                                                <i class="fas fa-trash"></i>
                                            </a>

                                            <!-- AI actions -->
                                            <button type="button"
                                                class="btn-ai-score"
                                                data-lead-id="<?= (int)$lead['id'] ?>"
                                                style="border:none; background:rgba(59,130,246,0.08); color:var(--primary); padding:.25rem .55rem; border-radius:999px; font-size:.75rem; font-weight:600; cursor:pointer; margin-right:.25rem;">
                                                Score
                                            </button>
                                            <button type="button"
                                                class="btn-ai-email"
                                                data-lead-id="<?= (int)$lead['id'] ?>"
                                                style="border:none; background:rgba(14,165,233,0.08); color:var(--sky-700); padding:.25rem .55rem; border-radius:999px; font-size:.75rem; font-weight:600; cursor:pointer;">
                                                Email
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>
        </div>

        <!-- Right column: AI email output -->
        <div class="right-column">
            <section class="quick-actions-section" id="ai-email-panel" style="display:none;">
                <div class="section-header">
                    <h2><i class="fas fa-envelope-open-text"></i> AI Email Draft</h2>
                </div>
                <div id="ai-email-meta"
                    style="font-size:.85rem; color:var(--sky-700); margin-bottom:.75rem;"></div>
                <textarea id="ai-email-content"
                    style="width:100%; min-height:220px; border-radius:12px; border:1px solid var(--sky-200); padding:.75rem; font-size:.9rem; resize:vertical;"></textarea>
                <p style="margin-top:.5rem; font-size:.8rem; color:var(--sky-600);">
                    This is a draft generated by your configured AI provider. Review and tweak before sending from your email client or CRM.
                </p>
            </section>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const baseUrl = '/lead-management/public';

        // Helper: update score pill UI
        function updateScorePill(leadId, scoreData) {
            const pill = document.querySelector('[data-score-pill="' + leadId + '"]');
            if (!pill) return;

            let score = scoreData.score ?? scoreData?.data?.score ?? null;
            let category = scoreData.category ?? scoreData?.data?.category ?? null;

            if (typeof score === 'object' && score.score !== undefined) {
                // just in case AIService returns nested
                category = score.category;
                score = score.score;
            }

            pill.textContent = '';

            if (score !== null && !isNaN(score)) {
                const s = document.createElement('span');
                s.textContent = Math.round(score) + '/100';
                pill.appendChild(s);

                if (category) {
                    const c = document.createElement('span');
                    c.textContent = category;
                    c.style.fontSize = '.7rem';
                    c.style.opacity = '0.8';
                    pill.appendChild(c);
                }
            } else {
                pill.textContent = 'No score';
            }

            // reset class
            pill.className = 'score-pill';
            score = Number(score);

            if (isNaN(score)) {
                pill.classList.add('score-none');
            } else if (score >= 80) {
                pill.classList.add('score-high');
            } else if (score >= 50) {
                pill.classList.add('score-medium');
            } else {
                pill.classList.add('score-low');
            }
        }

        // AI Score buttons
        document.querySelectorAll('.btn-ai-score').forEach(btn => {
            btn.addEventListener('click', async () => {
                const leadId = btn.getAttribute('data-lead-id');
                if (!leadId) return;

                btn.disabled = true;
                const original = btn.textContent;
                btn.textContent = 'Scoring…';

                try {
                    const res = await fetch(`${baseUrl}/app/leads/${leadId}/score`, {
                        method: 'POST'
                    });
                    const data = await res.json();

                    if (data.success && data.score) {
                        updateScorePill(leadId, data.score);
                    } else {
                        alert(data.error || 'Failed to score lead');
                    }
                } catch (e) {
                    alert('Error scoring lead');
                } finally {
                    btn.disabled = false;
                    btn.textContent = original;
                }
            });
        });

        // AI Email buttons
        const emailPanel = document.getElementById('ai-email-panel');
        const emailMeta = document.getElementById('ai-email-meta');
        const emailText = document.getElementById('ai-email-content');

        document.querySelectorAll('.btn-ai-email').forEach(btn => {
            btn.addEventListener('click', async () => {
                const leadId = btn.getAttribute('data-lead-id');
                if (!leadId) return;

                btn.disabled = true;
                const original = btn.textContent;
                btn.textContent = 'Generating…';

                try {
                    const res = await fetch(`${baseUrl}/app/leads/${leadId}/generate-email`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            email_type: 'follow_up'
                        })
                    });
                    const data = await res.json();

                    if (!data.success) {
                        alert(data.error || 'Failed to generate email');
                    } else {
                        const content = data.email_content || {};
                        const subject = content.subject || 'Follow-up';
                        const body = content.body || JSON.stringify(content, null, 2);

                        emailMeta.textContent = `Lead #${leadId} – ${subject}`;
                        emailText.value = body;
                        emailPanel.style.display = 'block';
                        emailPanel.scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        });
                    }
                } catch (e) {
                    alert('Error generating email');
                } finally {
                    btn.disabled = false;
                    btn.textContent = original;
                }
            });
        });
    });
</script>

<style>
    /* Small helpers for pills on this page */
    .status-pill {
        background: var(--sky-100);
        color: var(--sky-700);
    }

    .status-new {
        background: rgba(59, 130, 246, 0.1);
        color: var(--primary);
    }

    .status-active {
        background: rgba(14, 165, 233, 0.12);
        color: var(--sky-700);
    }

    .status-converted {
        background: rgba(16, 185, 129, 0.12);
        color: var(--success);
    }

    .status-lost {
        background: rgba(239, 68, 68, 0.12);
        color: var(--danger);
    }

    .score-pill {
        background: var(--sky-100);
        color: var(--sky-700);
    }

    .score-high {
        background: rgba(16, 185, 129, 0.1);
        color: var(--success);
    }

    .score-medium {
        background: rgba(245, 158, 11, 0.1);
        color: var(--warning);
    }

    .score-low {
        background: rgba(239, 68, 68, 0.1);
        color: var(--danger);
    }

    .score-none {
        background: var(--sky-100);
        color: var(--sky-600);
    }
</style>