<?php $this->start('body');
    $l = $this->data['lead'] ?? [];
    $fus = $this->data['follow_ups'] ?? [];
    $stages = $this->data['stages'] ?? [];
    $stageChip = [
        'NEW' => '#E2E8F0', 'QUALIFYING' => '#F1F5F9', 'QUOTING' => '#FEF3C7',
        'SUBMITTED' => '#DBEAFE', 'WON' => '#DCFCE7', 'LOST' => '#F1F5F9',
    ];
    $chipBg = $stageChip[$l['status']] ?? '#F1F5F9';
    $chipInk = $l['status'] === 'WON' ? '#166534' : '#334155';
    $canConvert = ($l['status'] === 'WON') && empty($l['linked_project_id']);
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;color:#334155;"><i class="fas fa-user-tag me-2" style="color:#7A8BA1;"></i><?= htmlspecialchars($l['lead_name']); ?></h5>
        <div class="text-muted small mt-1" style="color:#64748B;"><?= htmlspecialchars((string)$l['customer_name']); ?> · <?= htmlspecialchars((string)$l['lead_source']); ?> · <?= htmlspecialchars((string)$l['project_type']); ?></div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <span class="badge" style="background:<?= $chipBg; ?>;color:<?= $chipInk; ?>;font-size:.72rem;padding:.35rem .7rem;"><?= $l['status']; ?></span>
        <?php if (UserGroups::can('BusinessLeads','edit')): ?>
            <a href="<?= PROOT; ?>BusinessLeads/edit/<?= (int)$l['c0d']; ?>" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-edit me-1" style="color:#7A8BA1;"></i>Edit</a>
        <?php endif; ?>
        <a href="<?= PROOT; ?>BusinessLeads" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<?php if (!empty($l['linked_project_id'])): ?>
<div class="alert py-2 mb-3" style="background:#DCFCE7;border:1px solid #86EFAC;color:#166534;font-size:.86rem;">
    <i class="fas fa-check-circle me-1"></i>
    <strong>Converted to project <?= htmlspecialchars((string)$l['project_no']); ?></strong>
    · CRM status: <?= htmlspecialchars((string)$l['crm_status']); ?>
    <?php if (($l['crm_status'] ?? '') === 'PENDING'): ?> · <a href="<?= PROOT; ?>Onboarding" style="color:#166534;font-weight:600;">Complete onboarding checklist →</a><?php endif; ?>
</div>
<?php endif; ?>

<div class="row g-3 mb-3">
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid #7A9E7E !important;background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Opportunity</div>
        <div style="font-weight:700;font-size:1.4rem;color:#334155;">TZS <?= number_format((float)$l['opportunity_value']); ?></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid #7A8BA1 !important;background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Next action</div>
        <div style="font-weight:600;font-size:1.05rem;color:#334155;"><?= htmlspecialchars((string)($l['next_action_date'] ?? '—')); ?></div>
        <div class="text-muted small mt-1" style="color:#64748B;font-size:.78rem;"><?= htmlspecialchars((string)$l['next_action_note']); ?></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Owner</div>
        <div style="font-weight:600;font-size:1.05rem;color:#334155;"><?= htmlspecialchars((string)$l['owner_name']); ?></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Follow-ups</div>
        <div style="font-weight:700;font-size:1.4rem;color:#334155;"><?= count($fus); ?></div>
    </div></div></div>
</div>

<!-- Stage quick-change + Convert -->
<?php if (UserGroups::can('BusinessLeads','setStageAj')): ?>
<div class="card border-0 shadow-sm mb-3" style="background:#F8FAFC;">
    <div class="card-body p-2 d-flex align-items-center gap-2 flex-wrap">
        <span style="color:#64748B;font-size:.82rem;">Advance stage:</span>
        <?php foreach ($stages as $s): if ($s === $l['status']) continue; ?>
            <button type="button" class="btn btn-sm btn-stage" data-stage="<?= $s; ?>" style="background:#F1F5F9;border:1px solid #E2E8F0;color:#334155;font-size:.75rem;"><?= $s; ?></button>
        <?php endforeach; ?>
        <?php if ($canConvert && UserGroups::can('BusinessLeads','convertAj')): ?>
            <span class="ms-auto"></span>
            <button type="button" id="btn_convert" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-arrow-right me-1"></i>Convert to project</button>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<div class="row g-3">
    <div class="col-md-5">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white" style="border-bottom:1px solid #E2E8F0;">
                <strong style="color:#334155;"><i class="fas fa-plus me-2" style="color:#7A8BA1;"></i>Log follow-up</strong>
            </div>
            <div class="card-body p-3">
                <div class="row g-2">
                    <div class="col-md-5">
                        <label class="form-label" style="color:#334155;font-size:.78rem;">Date</label>
                        <input type="date" id="fu_date" value="<?= date('Y-m-d'); ?>" class="form-control form-control-sm">
                    </div>
                    <div class="col-md-12">
                        <label class="form-label" style="color:#334155;font-size:.78rem;">Note *</label>
                        <textarea id="fu_note" rows="2" class="form-control form-control-sm" placeholder="Called procurement · asked for BOQ clarification…"></textarea>
                    </div>
                </div>
                <div class="text-end mt-2">
                    <button type="button" id="btn_add_fu" class="btn btn-sm" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;font-weight:600;"><i class="fas fa-save me-1"></i>Add follow-up</button>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-7">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex align-items-center justify-content-between" style="border-bottom:1px solid #E2E8F0;">
                <strong style="color:#334155;"><i class="fas fa-history me-2" style="color:#7A8BA1;"></i>Follow-up timeline</strong>
                <span class="text-muted small" style="color:#64748B;"><?= count($fus); ?> entry</span>
            </div>
            <div class="card-body p-2" style="max-height:420px;overflow:auto;">
                <?php foreach ($fus as $fu): ?>
                    <div class="mb-2 p-2" style="background:#F8FAFC;border-left:3px solid #7A8BA1;border-radius:2px;">
                        <div class="d-flex align-items-center justify-content-between">
                            <strong style="color:#334155;font-size:.82rem;"><?= htmlspecialchars($fu['follow_date']); ?></strong>
                            <span class="text-muted small" style="color:#94A3B8;font-size:.72rem;"><?= htmlspecialchars((string)($fu['creator_name'] ?? '')); ?></span>
                        </div>
                        <div class="small mt-1" style="color:#334155;white-space:pre-wrap;"><?= htmlspecialchars((string)$fu['follow_note']); ?></div>
                    </div>
                <?php endforeach; ?>
                <?php if (empty($fus)): ?><div class="text-center py-4" style="color:#94A3B8;">No follow-ups logged yet.</div><?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php $this->end(); ?>

<?php $this->start('section_js'); ?>
<script>
$(function () {
    var PROOT = '<?= PROOT; ?>';
    var LEAD_ID = <?= (int)$l['c0d']; ?>;

    $('#btn_add_fu').on('click', function () {
        var note = $('#fu_note').val().trim();
        if (!note) { rsToast('Enter a note first.', 'warning'); return; }
        $.post(PROOT + 'BusinessLeads/addFollowUpAj', { lead_id: LEAD_ID, follow_date: $('#fu_date').val(), follow_note: note }, 'json')
            .done(function (res) {
                if (res && res.ok) { rsToast('Follow-up saved. Reloading…', 'success'); setTimeout(function () { location.reload(); }, 500); }
                else                { rsToast('Failed: ' + (res.msg || 'unknown'), 'error'); }
            });
    });

    $('.btn-stage').on('click', function () {
        var stage = $(this).data('stage');
        $.post(PROOT + 'BusinessLeads/setStageAj', { lead_id: LEAD_ID, stage: stage }, 'json')
            .done(function (res) {
                if (res && res.ok) { rsToast('Stage set to ' + stage + '. Reloading…', 'success'); setTimeout(function () { location.reload(); }, 400); }
                else                { rsToast('Failed: ' + (res.msg || 'unknown'), 'error'); }
            });
    });

    $('#btn_convert').on('click', function () {
        $.confirm({
            title: 'Convert lead to project?',
            content: 'This creates a new project row with <code>crm_status = PENDING</code>. The Onboarding chain must complete before Ops can act on it.',
            type: 'green',
            buttons: {
                yes: { text: 'Convert', btnClass: 'btn-success', action: function () {
                    $.post(PROOT + 'BusinessLeads/convertAj', { lead_id: LEAD_ID }, 'json')
                        .done(function (res) {
                            if (res && res.ok) { rsToast('Project #' + res.project_id + ' created. Reloading…', 'success'); setTimeout(function () { location.reload(); }, 800); }
                            else                { rsToast('Convert failed: ' + (res.msg || 'unknown'), 'error', 5000); }
                        });
                }},
                cancel: { text: 'Cancel', btnClass: 'btn-light' }
            }
        });
    });
});
</script>
<?php $this->end(); ?>
