<?php $this->start('body');
    $t = $this->data['tender'] ?? [];
    $catLabel = ['G'=>'Goods','W'=>'Works','S'=>'Services','N'=>'Non-Consulting'];
    $statusColor = ['active'=>'#7A9E7E','pursuing'=>'#D4A574','awarded'=>'#166534','cancelled'=>'#C48579','complete'=>'#94A3B8','withdrawn'=>'#94A3B8'];
    $col = $statusColor[strtolower((string)$t['tender_status'])] ?? '#94A3B8';
    $isConvertable = !in_array(strtolower((string)$t['tender_status']), ['awarded','cancelled','withdrawn','complete'], true);
    $canConvertLead   = $isConvertable && UserGroups::can('NestTenders','convertToLeadAj');
    $canConvertTender = $isConvertable && UserGroups::can('Tenders','add') && empty($t['linked_tender_id']);
    $prefillQ = http_build_query([
        'source_type'     => 'NEST_PUBLIC',
        'source_ref'      => $t['ocid'] ?? '',
        'source_url'      => $t['tender_url'] ?? '',
        'tender_title'    => $t['tender_title'] ?? '',
        'buyer_name'      => $t['buyer_name'] ?? '',
        'description'     => substr((string)($t['description'] ?? $t['tender_title'] ?? ''), 0, 400),
        'estimated_value' => (float)($t['amount'] ?? 0),
        'region'          => $t['region'] ?? '',
        'project_type'    => match (strtoupper((string)($t['category_acronym'] ?? ''))) { 'G'=>'goods','W'=>'works','S'=>'services','N'=>'services', default=>'goods' },
        'deadline_date'   => $t['tender_end'] ? date('Y-m-d', strtotime($t['tender_end'])) : '',
    ]);
?>

<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-file-signature me-2" style="color:#7A8BA1;"></i><?= htmlspecialchars((string)$t['tender_title']); ?></h5>
        <div class="text-muted small mt-1" style="color:#64748B;">OCID <?= htmlspecialchars((string)$t['ocid']); ?> · <?= htmlspecialchars((string)$t['buyer_name']); ?></div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <span class="badge" style="background:<?= $col; ?>;color:#fff;font-size:.72rem;padding:.35rem .7rem;text-transform:capitalize;"><?= htmlspecialchars((string)$t['tender_status']); ?></span>
        <?php if ($canConvertTender): ?><a href="<?= PROOT; ?>Tenders/add?<?= $prefillQ; ?>" class="btn btn-sm" style="background:#166534;border-color:#166534;color:#fff;font-weight:600;"><i class="fas fa-file-signature me-1"></i>Convert to tender</a><?php endif; ?>
        <?php if ($canConvertLead):   ?><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-address-book me-1"></i>Convert to lead</button><?php endif; ?>
        <a href="<?= PROOT; ?>NestTenders" 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($t['linked_tender_id']) || !empty($t['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>
    <?php if (!empty($t['internal_tender_no'])): ?><strong>Tracked as tender <?= htmlspecialchars($t['internal_tender_no']); ?></strong><?php endif; ?>
    <?php if (!empty($t['project_no'])): ?> · linked to project <?= htmlspecialchars($t['project_no']); ?><?php endif; ?>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm" style="background:#F8FAFC;">
    <div class="card-body p-3">
        <dl class="row mb-0" style="color:#334155;">
            <dt class="col-md-3" style="color:#64748B;">Amount</dt><dd class="col-md-9"><?= htmlspecialchars((string)($t['currency'] ?? 'TZS')); ?> <?= $t['amount'] !== null ? number_format((float)$t['amount']) : '—'; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Tender ref</dt><dd class="col-md-9"><?= htmlspecialchars((string)$t['tender_ref']) ?: '—'; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Category</dt><dd class="col-md-9"><?= htmlspecialchars($catLabel[$t['category_acronym']] ?? $t['category_acronym'] ?? '—'); ?><?php if (!empty($t['sub_category_acronym'])): ?> · <?= htmlspecialchars($t['sub_category_acronym']); ?><?php endif; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Financial year</dt><dd class="col-md-9"><?= htmlspecialchars((string)$t['financial_year']) ?: '—'; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Region</dt><dd class="col-md-9"><?= htmlspecialchars((string)$t['region']) ?: '—'; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Procurement method</dt><dd class="col-md-9"><?= htmlspecialchars((string)$t['procurement_method']); ?><?php if (!empty($t['procurement_method_cat'])): ?> · <?= htmlspecialchars($t['procurement_method_cat']); ?><?php endif; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Tender period</dt><dd class="col-md-9"><?= $t['tender_start'] ? htmlspecialchars($t['tender_start']) : '—'; ?> → <?= $t['tender_end'] ? htmlspecialchars($t['tender_end']) : '—'; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Bid opening</dt><dd class="col-md-9"><?= $t['bid_opening'] ? htmlspecialchars($t['bid_opening']) : '—'; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Release date</dt><dd class="col-md-9"><?= $t['release_date'] ? htmlspecialchars($t['release_date']) : '—'; ?></dd>
            <dt class="col-md-3" style="color:#64748B;">URL</dt><dd class="col-md-9"><?php if (!empty($t['tender_url'])): ?><a href="<?= htmlspecialchars($t['tender_url']); ?>" target="_blank" style="color:#7A8BA1;">Open in PPRA portal</a><?php else: ?>—<?php endif; ?></dd>
            <?php if (!empty($t['description'])): ?><dt class="col-md-3" style="color:#64748B;">Description</dt><dd class="col-md-9"><?= nl2br(htmlspecialchars((string)$t['description'])); ?></dd><?php endif; ?>
            <dt class="col-md-3" style="color:#64748B;">First seen</dt><dd class="col-md-9"><?= htmlspecialchars((string)$t['first_seen_at']); ?></dd>
            <dt class="col-md-3" style="color:#64748B;">Last synced</dt><dd class="col-md-9"><?= htmlspecialchars((string)$t['last_synced_at']); ?></dd>
        </dl>
    </div>
</div>

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

<?php $this->start('section_js'); ?>
<script>
$('#btn_convert').on('click', function () {
    $.confirm({
        title: 'Convert this tender to a business lead?',
        content: 'A new lead is created with source = NEST, stage = QUALIFYING, and a next-action date matching the closing date.',
        type: 'green',
        buttons: {
            yes: { text: 'Convert', btnClass: 'btn-success', action: function () {
                $.post('<?= PROOT; ?>NestTenders/convertToLeadAj', { tender_id: <?= (int)$t['c0d']; ?> }, 'json')
                    .done(function (res) {
                        if (res && res.ok) { rsToast('Lead #' + res.lead_id + ' created.', 'success'); setTimeout(function () { location.href = '<?= PROOT; ?>BusinessLeads/view/' + res.lead_id; }, 800); }
                        else                { rsToast('Convert failed: ' + (res.msg || 'unknown'), 'error'); }
                    });
            }},
            cancel: { text: 'Cancel', btnClass: 'btn-light' }
        }
    });
});
</script>
<?php $this->end(); ?>
