<?= $this->extend('layouts/enterprise') ?>

<?= $this->section('content') ?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Sales & CRM',
    'workspaceCrumbCurrent' => 'Lead Conversion',
    'workspaceTitle'        => 'Lead Conversion Tracker',
    'workspaceDesc'         => 'Convert qualified leads to customers or opportunities and review conversion history.',
]) ?>

<div class="row g-4 mb-4">
    <div class="col-lg-5">
        <article class="enterprise-settings-card">
            <div class="enterprise-settings-card__head">
                <i class="fa-solid fa-arrow-right-arrow-left"></i>
                <h2 class="enterprise-settings-card__title">Convert a Lead</h2>
            </div>

            <?php if (session()->getFlashdata('errors')): ?>
                <div class="alert alert-danger py-2 small">
                    <ul class="mb-0 ps-3">
                        <?php foreach ((array) session()->getFlashdata('errors') as $err): ?>
                            <li><?= esc(is_array($err) ? implode(', ', $err) : $err) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <?php if (count($convertibleLeads) === 0): ?>
                <p class="text-muted small mb-0">No leads available for conversion. All active leads may already be converted or unqualified.</p>
            <?php else: ?>
                <form id="convert-form" action="" method="post" novalidate>
                    <?= csrf_field() ?>
                    <div class="enterprise-settings-fields enterprise-settings-fields--single">
                        <div class="enterprise-field">
                            <label class="enterprise-field-label">Lead <span class="text-danger">*</span></label>
                            <select name="lead_id" id="convert-lead-id" class="form-select" required>
                                <option value="">— Select lead —</option>
                                <?php foreach ($convertibleLeads as $l): ?>
                                    <option value="<?= $l['id'] ?>" data-action="<?= base_url('sale/lead-conversion/' . $l['id'] . '/convert') ?>">
                                        <?= esc(trim($l['first_name'] . ' ' . $l['last_name'])) ?>
                                        <?= $l['company_name'] ? ' · ' . esc($l['company_name']) : '' ?>
                                        (Score: <?= (int) $l['score'] ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="enterprise-field">
                            <label class="enterprise-field-label">Conversion Type <span class="text-danger">*</span></label>
                            <select name="conversion_type" class="form-select" required>
                                <option value="customer">Customer</option>
                                <option value="opportunity">Opportunity</option>
                            </select>
                        </div>
                        <div class="enterprise-field">
                            <label class="enterprise-field-label">Notes</label>
                            <textarea name="notes" class="form-control" rows="3" placeholder="Optional conversion notes"></textarea>
                        </div>
                    </div>
                    <div class="enterprise-settings-card__footer px-0 pb-0">
                        <button type="submit" class="btn btn-primary" id="convert-submit" disabled>Convert Lead</button>
                    </div>
                </form>
            <?php endif; ?>
        </article>
    </div>
</div>

<div class="enterprise-data-panel">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Conversion History</h2>
        <p class="enterprise-data-panel__subtitle">Record of leads converted to customers or opportunities.</p>
    </div>

    <div class="enterprise-data-panel__toolbar">
        <form action="<?= base_url('sale/lead-conversion') ?>" method="get">
            <div class="enterprise-filter-grid">
                <div>
                    <label class="enterprise-field-label">Search</label>
                    <input type="text" name="q" class="form-control form-control-sm" placeholder="Lead name"
                           value="<?= esc($filters['search']) ?>">
                </div>
                <div>
                    <label class="enterprise-field-label">Type</label>
                    <select name="type" class="form-select form-select-sm">
                        <option value="">Any</option>
                        <?php foreach (['customer', 'opportunity'] as $t): ?>
                            <option value="<?= $t ?>" <?= $filters['type'] === $t ? 'selected' : '' ?>><?= ucfirst($t) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="enterprise-filter-actions">
                    <button type="submit" class="btn btn-sm btn-primary">Apply Filters</button>
                    <a href="<?= base_url('sale/leads') ?>" class="btn btn-sm btn-outline-secondary">All Leads</a>
                </div>
            </div>
        </form>
    </div>

    <div class="enterprise-data-panel__body">
        <div class="table-responsive">
            <table class="enterprise-data-table">
                <thead>
                    <tr>
                        <th>Lead</th>
                        <th>Type</th>
                        <th>Converted By</th>
                        <th>Converted At</th>
                        <th>Notes</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($conversions as $c): ?>
                        <tr>
                            <td>
                                <a href="<?= base_url('sale/leads/' . $c['lead_id']) ?>" class="enterprise-data-table__primary text-decoration-none">
                                    <?= esc($leadMap[$c['lead_id']] ?? 'Lead #' . $c['lead_id']) ?>
                                </a>
                            </td>
                            <td><span class="badge bg-primary-subtle text-primary"><?= esc(ucfirst($c['conversion_type'])) ?></span></td>
                            <td><?= esc($userMap[$c['converted_by']] ?? '—') ?></td>
                            <td><?= esc($c['converted_at']) ?></td>
                            <td class="text-muted small"><?= esc($c['notes'] ?: '—') ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (count($conversions) === 0): ?>
                        <tr><td colspan="5" class="text-center text-muted py-5">No conversions recorded yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.getElementById('convert-lead-id')?.addEventListener('change', function () {
    const form = document.getElementById('convert-form');
    const submit = document.getElementById('convert-submit');
    const option = this.options[this.selectedIndex];
    if (option.value) {
        form.action = option.dataset.action;
        submit.disabled = false;
    } else {
        form.action = '';
        submit.disabled = true;
    }
});
</script>

<?= $this->endSection() ?>
