<?php $this->start('body');
    $t         = $this->data['tender'] ?? null;
    $isEdit    = $t !== null;
    $prefill   = $this->data['prefill'] ?? [];
    $customers = $this->data['customers'] ?? [];
    $sources   = $this->data['sources'] ?? [];
    $stages    = $this->data['stages'] ?? [];
    $sourceLabel = ['NEST_PUBLIC' => 'NeST · public', 'PRIVATE_CLIENT' => 'Private client', 'INVITATION' => 'Invitation', 'REFERRAL' => 'Referral', 'WALK_IN' => 'Walk-in'];
    $action    = $isEdit ? PROOT . 'Tenders/edit/' . (int)$t['c0d'] : PROOT . 'Tenders/add';
    $currentSource = $prefill['source_type'] ?? 'PRIVATE_CLIENT';
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <h5 class="mb-0" style="font-weight:600;color:#334155;"><i class="fas fa-<?= $isEdit ? 'edit' : 'plus-circle'; ?> me-2" style="color:#7A8BA1;"></i><?= $isEdit ? 'Edit tender' : 'Add tender'; ?></h5>
    <a href="<?= PROOT; ?>Tenders<?= $isEdit ? '/view/' . (int)$t['c0d'] : ''; ?>" 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>

<?php if (!$isEdit && $currentSource === 'NEST_PUBLIC' && !empty($prefill['source_ref'])): ?>
<div class="alert py-2 mb-3" style="background:#F1F5F9;border:1px solid #E2E8F0;color:#334155;font-size:.86rem;">
    <i class="fas fa-info-circle me-1" style="color:#7A8BA1;"></i>
    Prefilled from NeST feed &middot; OCID <strong><?= htmlspecialchars($prefill['source_ref']); ?></strong>. Complete the remaining fields to internalize this tender.
</div>
<?php endif; ?>

<form method="post" action="<?= $action; ?>" class="card border-0 shadow-sm" style="background:#F8FAFC;">
    <div class="card-body p-3">
        <!-- Source ── drives customer requirement + prefill behavior ── -->
        <div class="row g-2 mb-3">
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;">Source *</label>
                <?php if ($isEdit): ?>
                    <input type="text" value="<?= htmlspecialchars($sourceLabel[$t['source_type']] ?? $t['source_type']); ?>" class="form-control form-control-sm" disabled>
                <?php else: ?>
                <select name="source_type" id="source_type" required class="form-select form-select-sm">
                    <?php foreach ($sources as $s): ?>
                        <option value="<?= $s; ?>" <?= $currentSource === $s ? 'selected' : ''; ?>><?= $sourceLabel[$s] ?? $s; ?></option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
            </div>
            <div class="col-md-4" id="source_ref_wrap">
                <label class="form-label" style="color:#334155;">Source reference</label>
                <input type="text" name="source_ref" value="<?= htmlspecialchars((string)($prefill['source_ref'] ?? '')); ?>" placeholder="OCID / PPRA no / letter ref…" class="form-control form-control-sm">
            </div>
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;">Source URL</label>
                <input type="url" name="source_url" value="<?= htmlspecialchars((string)($prefill['source_url'] ?? '')); ?>" placeholder="https://…" class="form-control form-control-sm">
            </div>
        </div>

        <!-- Customer (private) vs Buyer (public) ── mutually exclusive path ── -->
        <div class="row g-2 mb-3">
            <div class="col-md-6" id="customer_wrap">
                <label class="form-label" style="color:#334155;">Private customer <span id="cust_req" style="color:#C48579;">*</span></label>
                <select name="customer_id" id="customer_id" class="form-select form-select-sm">
                    <option value="0">— choose customer —</option>
                    <?php foreach ($customers as $c): $n = trim(($c['fname'] ?? '') . ' ' . ($c['lname'] ?? '')) . (!empty($c['customer_no']) ? ' [' . $c['customer_no'] . ']' : ''); ?>
                        <option value="<?= (int)$c['c0d']; ?>" data-name="<?= htmlspecialchars($n); ?>" <?= $isEdit && (int)($t['customer_id'] ?? 0) === (int)$c['c0d'] ? 'selected' : ''; ?>><?= htmlspecialchars($n); ?></option>
                    <?php endforeach; ?>
                </select>
                <div class="small mt-1" style="color:#94A3B8;font-size:.7rem;">Required for Private client tenders. Optional for others.</div>
            </div>
            <div class="col-md-6">
                <label class="form-label" style="color:#334155;">Buyer / procuring entity *</label>
                <input type="text" name="buyer_name" id="buyer_name" required value="<?= htmlspecialchars((string)($prefill['buyer_name'] ?? '')); ?>" placeholder="Ministry / company name…" class="form-control form-control-sm">
            </div>
        </div>

        <!-- Core tender fields ── -->
        <div class="row g-2 mb-3">
            <div class="col-md-8">
                <label class="form-label" style="color:#334155;">Tender title *</label>
                <input type="text" name="tender_title" required value="<?= htmlspecialchars((string)($prefill['tender_title'] ?? '')); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;">Tender no</label>
                <input type="text" name="tender_no" value="<?= htmlspecialchars((string)($t['tender_no'] ?? '')); ?>" placeholder="auto if blank (T-YYYY-NNNN)" class="form-control form-control-sm">
            </div>

            <div class="col-md-12">
                <label class="form-label" style="color:#334155;">Description</label>
                <textarea name="tender_description" rows="2" class="form-control form-control-sm"><?= htmlspecialchars((string)($prefill['tender_description'] ?? '')); ?></textarea>
            </div>

            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Project type *</label>
                <select name="project_type" class="form-select form-select-sm">
                    <?php foreach (['goods','services','works','consultancy'] as $pt): ?>
                        <option value="<?= $pt; ?>" <?= (($prefill['project_type'] ?? 'goods') === $pt) ? 'selected' : ''; ?>><?= ucfirst($pt); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Industry</label>
                <input type="text" name="tender_industry" value="<?= htmlspecialchars((string)($t['tender_industry'] ?? '')); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Region</label>
                <input type="text" name="region" value="<?= htmlspecialchars((string)($prefill['region'] ?? '')); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">District</label>
                <input type="text" name="district" value="<?= htmlspecialchars((string)($t['district'] ?? '')); ?>" class="form-control form-control-sm">
            </div>

            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Date received *</label>
                <input type="date" name="date_received" required value="<?= htmlspecialchars((string)($t['date_received'] ?? date('Y-m-d'))); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Deadline date</label>
                <input type="date" name="deadline_date" value="<?= htmlspecialchars((string)($prefill['deadline_date'] ?? '')); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="color:#334155;">Deadline time</label>
                <input type="time" name="deadline_time" value="<?= htmlspecialchars((string)($t['deadline_time'] ?? '')); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="color:#334155;">Estimated value (TZS)</label>
                <input type="number" step="0.01" name="estimated_value" value="<?= (float)($prefill['estimated_value'] ?? 0); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="color:#334155;">Initial stage</label>
                <select name="tender_stage" class="form-select form-select-sm">
                    <?php foreach (['PREP','SUBMISSION'] as $s): ?>
                        <option value="<?= $s; ?>" <?= ($isEdit && $t['tender_stage'] === $s) || (!$isEdit && $s === 'PREP') ? 'selected' : ''; ?>><?= $s; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-6">
                <label class="form-label" style="color:#334155;">Submission method</label>
                <select name="submission_method" class="form-select form-select-sm">
                    <?php foreach (['','Physical / sealed envelope','Online / portal','Email','Courier','Hand-delivered'] as $sm): ?>
                        <option value="<?= htmlspecialchars($sm); ?>" <?= ($t['submission_method'] ?? '') === $sm ? 'selected' : ''; ?>><?= $sm === '' ? '—' : htmlspecialchars($sm); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
    </div>
    <div class="card-footer bg-white d-flex justify-content-end gap-2" style="border-top:1px solid #E2E8F0;">
        <a href="<?= PROOT; ?>Tenders" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;">Cancel</a>
        <button type="submit" class="btn btn-sm" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;font-weight:600;"><i class="fas fa-save me-1"></i><?= $isEdit ? 'Save changes' : 'Create tender'; ?></button>
    </div>
</form>

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

<?php $this->start('section_js'); ?>
<script>
$(function () {
    function applySource() {
        var s = $('#source_type').val() || 'PRIVATE_CLIENT';
        // customer required + shown for PRIVATE_CLIENT; hidden for NEST_PUBLIC
        if (s === 'PRIVATE_CLIENT') {
            $('#customer_wrap').show();
            $('#customer_id').prop('required', true);
            $('#cust_req').show();
        } else if (s === 'NEST_PUBLIC') {
            $('#customer_wrap').hide();
            $('#customer_id').val(0).prop('required', false);
            $('#cust_req').hide();
        } else {
            $('#customer_wrap').show();
            $('#customer_id').prop('required', false);
            $('#cust_req').hide();
        }
    }
    $('#source_type').on('change', applySource);
    applySource();

    // Auto-fill buyer_name from customer
    $('#customer_id').on('change', function () {
        var name = $(this).find('option:selected').data('name');
        if (parseInt($(this).val(), 10) > 0 && name && !$('#buyer_name').val()) {
            $('#buyer_name').val(name);
        }
    });
});
</script>
<?php $this->end(); ?>
