<?php $this->start('body');
    $co     = $this->data['co'];
    $parts  = $this->data['parts']  ?? [];
    $catalog= $this->data['parts_catalog'] ?? [];
    $canDis = !empty($this->data['can_dispatch']);
    $canArr = !empty($this->data['can_arrive']);
    $canRes = !empty($this->data['can_resolve']);
    $canFin = !empty($this->data['can_findings']);       // Slice 8Z-z-G
    $canAcc = !empty($this->data['can_accept']);
    $canCls = !empty($this->data['can_close']);
    $photos = $this->data['photos'] ?? [];
    $linkedRequests = $this->data['linked_requests'] ?? [];
    $canUploadPhoto = $canDis || $canArr || $canRes || in_array($co['status'], ['RESOLVED','CLIENT_ACCEPTED','ON_SITE','DISPATCHED'], true);
    $chip = [
        'OPEN'            => ['#F5EAE1','#C48579','Open'],
        'DISPATCHED'      => ['#FEF3E7','#8B6914','Dispatched'],
        'ON_SITE'         => ['#EEF2F6','#7A8BA1','On site'],
        'RESOLVED'        => ['#EAF2E8','#3F5C43','Resolved'],
        'CLIENT_ACCEPTED' => ['#EAF2E8','#3F5C43','Client accepted'],
        'CLOSED'          => ['#F1F5F9','#334155','Closed'],
        'CANCELLED'       => ['#F5EAE1','#C48579','Cancelled'],
    ];
    $sc = $chip[$co['status']] ?? ['#F1F5F9','#334155',$co['status']];
?>
<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-ambulance me-2 text-muted"></i><?= htmlspecialchars($co['callout_no']); ?>
            <?php if ((int)$co['is_emergency'] === 1): ?><span class="badge bg-danger ms-2" style="font-size:.6rem;">EMERGENCY</span><?php endif; ?>
        </h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <?= htmlspecialchars((string)$co['contract_no']); ?> · <?= htmlspecialchars((string)$co['customer_name']); ?>
            <?php if (!empty($co['site_name'])): ?> · <?= htmlspecialchars((string)$co['site_name']); ?><?php endif; ?>
            <?php if (!empty($co['asset_no'])): ?> · <strong><?= htmlspecialchars((string)$co['asset_no']); ?></strong><?php endif; ?>
            · reported <?= htmlspecialchars((string)$co['reported_at']); ?>
        </div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <span class="badge" style="background:<?= $sc[0]; ?>;color:<?= $sc[1]; ?>;border:1px solid <?= $sc[1]; ?>;font-weight:600;text-transform:capitalize;padding:.4rem .55rem;font-size:.7rem;"><?= htmlspecialchars($sc[2]); ?></span>
        <a href="<?= PROOT; ?>Callouts" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-6">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-2"><strong style="font-weight:600;font-size:.85rem;">Description</strong></div>
            <div class="card-body p-3 small"><?= nl2br(htmlspecialchars((string)($co['description'] ?? '—'))); ?>
                <?php if (!empty($co['reported_by_name'])): ?>
                    <div class="text-muted mt-2" style="font-size:.65rem;">Reported by <?= htmlspecialchars((string)$co['reported_by_name']); ?><?php if (!empty($co['reported_by_phone'])): ?> · <?= htmlspecialchars((string)$co['reported_by_phone']); ?><?php endif; ?></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-2"><strong style="font-weight:600;font-size:.85rem;">SLA · <span style="color:<?= htmlspecialchars((string)$co['color_hex']); ?>;"><?= htmlspecialchars((string)$co['cat_code']); ?></span></strong></div>
            <div class="card-body p-3 small">
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Response target</span><span><strong><?= (int)$co['cat_response_hrs']; ?>h</strong></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Restore target</span><span><strong><?= (int)$co['cat_restoration_hrs']; ?>h</strong></span></div>
                <?php if ($co['dispatched_at']): ?>
                    <div class="d-flex justify-content-between mb-1"><span class="text-muted">Dispatched</span><span><?= htmlspecialchars((string)$co['dispatched_at']); ?></span></div>
                <?php endif; ?>
                <?php if ($co['arrived_at']): ?>
                    <div class="d-flex justify-content-between mb-1"><span class="text-muted">Arrived</span><span><?= htmlspecialchars((string)$co['arrived_at']); ?></span></div>
                <?php endif; ?>
                <?php if ($co['resolved_at']): ?>
                    <div class="d-flex justify-content-between mb-1"><span class="text-muted">Resolved</span><span><?= htmlspecialchars((string)$co['resolved_at']); ?></span></div>
                <?php endif; ?>
                <?php if ((float)$co['sla_response_breached_hrs'] > 0 || (float)$co['sla_restore_breached_hrs'] > 0): ?>
                    <hr class="my-2">
                    <div class="d-flex justify-content-between mb-1"><span class="text-muted">Response breach</span><span style="color:#C48579;font-weight:600;"><?= number_format((float)$co['sla_response_breached_hrs'], 2); ?>h</span></div>
                    <div class="d-flex justify-content-between mb-1"><span class="text-muted">Restore breach</span><span style="color:#C48579;font-weight:600;"><?= number_format((float)$co['sla_restore_breached_hrs'], 2); ?>h</span></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- 8Z-z-G · Site investigation & findings -->
<div class="card border-0 shadow-sm mb-3" style="border-left:3px solid #7A8BA1 !important;">
    <div class="card-header bg-white py-2" style="border-bottom:1px solid #E2E8F0;">
        <strong style="font-weight:600;color:#334155;font-size:.85rem;"><i class="fas fa-magnifying-glass me-1" style="color:#7A8BA1;"></i>Site investigation &amp; findings</strong>
        <span class="text-muted small ms-2" style="font-size:.7rem;">What FS discovered on site · root cause · outstanding snags</span>
    </div>
    <div class="card-body p-3">
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label small text-muted" style="font-size:.66rem;text-transform:uppercase;letter-spacing:.3px;font-weight:600;">Issue found (diagnosis) *</label>
                <textarea id="fn_inv" rows="4" class="form-control form-control-sm" <?= $canFin ? '' : 'disabled'; ?> placeholder="Genset failed AVR — no output on load test; smell of burnt insulation on transfer switch."><?= htmlspecialchars((string)($co['investigation_notes'] ?? '')); ?></textarea>
            </div>
            <div class="col-md-6">
                <label class="form-label small text-muted" style="font-size:.66rem;text-transform:uppercase;letter-spacing:.3px;font-weight:600;">Root cause (RCA)</label>
                <textarea id="fn_rca" rows="4" class="form-control form-control-sm" <?= $canFin ? '' : 'disabled'; ?> placeholder="AVR module burnt due to voltage surge from grid switching; existing surge protector under-rated."><?= htmlspecialchars((string)($co['root_cause'] ?? '')); ?></textarea>
            </div>
            <div class="col-md-12">
                <label class="form-label small text-muted" style="font-size:.66rem;text-transform:uppercase;letter-spacing:.3px;font-weight:600;">Snags (outstanding items · to be addressed later)</label>
                <textarea id="fn_snags" rows="2" class="form-control form-control-sm" <?= $canFin ? '' : 'disabled'; ?> placeholder="Genset air filter also worn — recommend replacement at next PM. Client to procure larger surge protector."><?= htmlspecialchars((string)($co['snags'] ?? '')); ?></textarea>
            </div>
        </div>
        <?php if ($canFin): ?>
        <div class="mt-3 d-flex justify-content-end">
            <button type="button" id="btn_save_findings" class="btn btn-sm" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;font-weight:600;"><i class="fas fa-save me-1"></i>Save findings</button>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if (!empty($co['resolution_description']) || $co['resolved_at']): ?>
<div class="card border-0 shadow-sm mb-3" style="border-left:3px solid #7A9E7E !important;">
    <div class="card-header bg-white py-2 d-flex align-items-center justify-content-between" style="border-bottom:1px solid #E2E8F0;">
        <strong style="font-weight:600;font-size:.85rem;"><i class="fas fa-check-circle me-1 text-success"></i>Resolution</strong>
        <span class="text-muted small" style="font-size:.7rem;"><?= htmlspecialchars((string)($co['resolved_at'] ?? '—')); ?></span>
    </div>
    <div class="card-body p-3 small">
        <?= nl2br(htmlspecialchars((string)$co['resolution_description'])); ?>
        <div class="row g-2 mt-2 small text-muted">
            <?php if ($co['labour_hrs'] !== null): ?><div class="col-4">Labour: <strong><?= number_format((float)$co['labour_hrs'], 2); ?>h</strong></div><?php endif; ?>
            <?php if ($co['mileage_km'] !== null): ?><div class="col-4">Mileage: <strong><?= number_format((float)$co['mileage_km'], 1); ?>km</strong></div><?php endif; ?>
            <?php if (!empty($co['client_accepted_by_name'])): ?><div class="col-4">Client accepted by: <strong><?= htmlspecialchars((string)$co['client_accepted_by_name']); ?></strong></div><?php endif; ?>
            <?php if (!empty($co['closed_at'])): ?><div class="col-4">Closed: <strong><?= htmlspecialchars((string)$co['closed_at']); ?></strong> by <?= htmlspecialchars((string)($co['closed_by_name'] ?? '')); ?></div><?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header py-2 d-flex justify-content-between align-items-center" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;">
        <strong style="font-weight:600;color:#334155;font-size:.85rem;"><i class="fas fa-cogs me-1 text-muted"></i>Parts used</strong>
        <?php if ($canRes || $canArr): ?><button type="button" class="btn btn-sm" id="btn_add_part" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;"><i class="fas fa-plus me-1"></i>Add part</button><?php endif; ?>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light"><tr><th>SKU</th><th>Part</th><th class="text-end">Qty</th><th>Source</th><th class="text-end">Unit cost</th><th>Notes</th></tr></thead>
            <tbody>
                <?php foreach ($parts as $p): ?>
                    <tr>
                        <td class="small"><code><?= htmlspecialchars((string)$p['sku']); ?></code></td>
                        <td class="small"><?= htmlspecialchars((string)$p['part_name']); ?></td>
                        <td class="text-end small"><?= number_format((float)$p['qty'], (fmod((float)$p['qty'],1)==0?0:2)); ?></td>
                        <td class="small text-muted" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ', (string)$p['source']))); ?></td>
                        <td class="text-end small text-muted"><?= $p['unit_cost_at_use'] !== null ? number_format((float)$p['unit_cost_at_use']) : '—'; ?></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)($p['notes'] ?? '')); ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($parts)): ?><tr><td colspan="6" class="text-center text-muted py-3 small">No parts logged.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Slice 8S-7 · Photo evidence -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header py-2 d-flex justify-content-between align-items-center" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;">
        <strong style="font-weight:600;color:#334155;font-size:.85rem;"><i class="fas fa-camera me-1 text-muted"></i>Photo evidence
            <span class="text-muted small ms-2" style="font-weight:400;font-size:.65rem;"><?= count($photos); ?> photo<?= count($photos) === 1 ? '' : 's'; ?></span>
        </strong>
        <?php if ($canUploadPhoto): ?><button type="button" id="btn_add_photo" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-plus me-1"></i>Upload photo</button><?php endif; ?>
    </div>
    <div class="card-body p-3">
        <?php if (empty($photos)): ?>
            <div class="text-muted small">No photos uploaded yet.</div>
        <?php else: ?>
            <div class="d-flex flex-wrap gap-2">
                <?php foreach ($photos as $ph): ?>
                    <div style="position:relative;width:120px;">
                        <a href="<?= PROOT; ?>Callouts/photoDownload/<?= (int)$ph['c0d']; ?>" target="_blank" title="<?= htmlspecialchars((string)($ph['caption'] ?: $ph['original_name'])); ?>">
                            <?php if (strpos((string)$ph['mime'], 'image/') === 0): ?>
                                <img src="<?= PROOT; ?>Callouts/photoDownload/<?= (int)$ph['c0d']; ?>" style="width:120px;height:120px;object-fit:cover;border-radius:6px;border:1px solid #E2E8F0;">
                            <?php else: ?>
                                <div style="width:120px;height:120px;background:#F1F5F9;border:1px solid #E2E8F0;border-radius:6px;display:flex;align-items:center;justify-content:center;flex-direction:column;">
                                    <i class="fas fa-file-pdf" style="font-size:2rem;color:#C48579;"></i>
                                    <div class="small text-muted mt-1" style="font-size:.6rem;"><?= htmlspecialchars(mb_strimwidth((string)$ph['original_name'], 0, 18, '…')); ?></div>
                                </div>
                            <?php endif; ?>
                        </a>
                        <div class="text-center" style="font-size:.6rem;">
                            <span class="badge bg-light text-muted" style="text-transform:capitalize;font-size:.55rem;"><?= htmlspecialchars(strtolower((string)$ph['kind'])); ?></span>
                        </div>
                        <?php if ($canUploadPhoto): ?>
                            <button type="button" class="btn btn-sm btn-link p-0 photo_del text-danger" data-photo-id="<?= (int)$ph['c0d']; ?>" style="position:absolute;top:2px;right:2px;background:#fff;border-radius:50%;padding:0 3px !important;font-size:.7rem;line-height:1;box-shadow:0 1px 3px rgba(0,0,0,.2);"><i class="fas fa-times"></i></button>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- 8Z-z-G · Related spare-part requests raised from this callout -->
<div class="card border-0 shadow-sm mb-3" style="border-left:3px solid #D4A574 !important;">
    <div class="card-header py-2 d-flex justify-content-between align-items-center" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;">
        <div>
            <strong style="font-weight:600;color:#334155;font-size:.85rem;"><i class="fas fa-hand-holding-medical me-1" style="color:#D4A574;"></i>Related spare-part requests</strong>
            <span class="text-muted small ms-2" style="font-size:.7rem;"><?= count($linkedRequests); ?> raised from this callout</span>
        </div>
        <?php if (!empty($co['site_id']) && ($canFin || $canRes)): ?>
            <a href="<?= PROOT; ?>Projects/site/<?= (int)$co['site_id']; ?>#sr" class="btn btn-sm" style="background:#D4A574;border-color:#D4A574;color:#fff;font-weight:600;"><i class="fas fa-plus me-1"></i>Request spare change</a>
        <?php endif; ?>
    </div>
    <div class="card-body p-0">
        <?php if (empty($linkedRequests)): ?>
            <div class="p-3 text-center small text-muted" style="font-size:.78rem;">
                No spare requests linked to this callout yet.
                <?php if (!empty($co['site_id']) && ($canFin || $canRes)): ?>
                    Use <strong>Request spare change</strong> to raise one — the request will inherit this callout's site and reason.
                <?php endif; ?>
            </div>
        <?php else: ?>
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light" style="font-size:.68rem;color:#64748B;text-transform:uppercase;letter-spacing:.3px;">
                <tr><th>Request no</th><th>Urgency</th><th>Who pays</th><th>Items</th><th>Status</th><th>Reason</th></tr>
            </thead>
            <tbody>
                <?php $sColor = ['DRAFT'=>'#94A3B8','AWAITING_POC'=>'#D4A574','POC_APPROVED'=>'#7A9E7E','POC_DECLINED'=>'#C48579','AWAITING_PM'=>'#D4A574','PM_APPROVED'=>'#7A9E7E','PM_DECLINED'=>'#C48579','WITH_PROCUREMENT'=>'#5B7A9E','STOCK_ISSUED'=>'#7A9E7E','SOURCING'=>'#5B7A9E','ORDERED'=>'#5B7A9E','DELIVERED'=>'#7A8BA1','INSTALLED'=>'#7A9E7E','CLOSED'=>'#64748B','CANCELLED'=>'#C48579'];
                      $uColor = ['EMERGENCY'=>'#C48579','URGENT'=>'#D4A574','ROUTINE'=>'#94A3B8']; ?>
                <?php foreach ($linkedRequests as $lr): ?>
                    <tr>
                        <td class="small"><code style="color:#7A8BA1;font-size:.72rem;background:#EEF2F6;padding:.1rem .35rem;border-radius:2px;"><?= htmlspecialchars((string)$lr['request_no']); ?></code></td>
                        <td><span class="badge" style="background:<?= $uColor[$lr['urgency']] ?? '#64748B'; ?>;color:#fff;font-size:.6rem;font-weight:600;padding:.15rem .4rem;text-transform:capitalize;"><?= htmlspecialchars((string)$lr['urgency']); ?></span></td>
                        <td class="small text-muted" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower((string)$lr['who_pays'])); ?></td>
                        <td class="small text-muted"><?= (int)$lr['item_count']; ?></td>
                        <td><span class="badge" style="background:<?= $sColor[$lr['status']] ?? '#64748B'; ?>;color:#fff;font-size:.58rem;font-weight:600;padding:.2rem .5rem;"><?= htmlspecialchars((string)$lr['status']); ?></span></td>
                        <td class="small text-muted" style="max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?= htmlspecialchars((string)$lr['reason']); ?>"><?= htmlspecialchars((string)$lr['reason']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body p-3 d-flex gap-2 justify-content-end flex-wrap">
        <?php if (in_array($co['status'], ['DISPATCHED','ON_SITE','RESOLVED'], true) && ($canDis || $canArr || $canRes)): ?>
            <button type="button" class="btn btn-sm btn-outline-warning" id="btn_cash_request"><i class="fas fa-hand-holding-usd me-1"></i>Raise cash request (adhoc spare)</button>
        <?php endif; ?>
        <?php if ($canDis): ?><button type="button" class="btn btn-sm" id="btn_dispatch" style="background:#8B6914;border-color:#8B6914;color:#fff;font-weight:600;"><i class="fas fa-paper-plane me-1"></i>Dispatch</button><?php endif; ?>
        <?php if ($canArr): ?><button type="button" class="btn btn-sm" id="btn_arrive" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-map-marker-alt me-1"></i>Arrived on site</button><?php endif; ?>
        <?php if ($canRes): ?><button type="button" class="btn btn-sm" id="btn_resolve" style="background:#3F5C43;border-color:#3F5C43;color:#fff;font-weight:600;"><i class="fas fa-check me-1"></i>Resolve</button><?php endif; ?>
        <?php if ($canAcc): ?><button type="button" class="btn btn-sm" id="btn_accept" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-signature me-1"></i>Client accepted</button><?php endif; ?>
        <?php if ($canCls): ?><button type="button" class="btn btn-sm" id="btn_close" style="background:#334155;border-color:#334155;color:#fff;font-weight:600;"><i class="fas fa-times-circle me-1"></i>Close callout</button><?php endif; ?>
        <?php if (!$canDis && !$canArr && !$canRes && !$canAcc && !$canCls): ?><span class="text-muted small">No actions available at this status.</span><?php endif; ?>
    </div>
</div>

<script>
(function () {
    var CO_ID = <?= (int)$co['c0d']; ?>;
    var PROOT = '<?= PROOT; ?>';
    var PARTS = <?= json_encode(array_map(fn($p) => ['c0d'=>(int)$p['c0d'],'sku'=>$p['sku'],'name'=>$p['name']], $catalog)); ?>;
    function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]); }); }

    var b1 = document.getElementById('btn_dispatch');
    if (b1) b1.addEventListener('click', function () {
        $.confirm({ title:'Dispatch to which tech?', columnClass:'col-md-5', type:'orange', content: '<form id="ds_form"><div class="mb-2"><label class="form-label small">Tech name</label><input name="tech_name" class="form-control form-control-sm" required></div></form>', buttons: {
            yes: { text:'Dispatch', btnClass:'btn-warning', action: function () {
                var f = document.getElementById('ds_form');
                $.post(PROOT + 'Callouts/dispatchAj', { co_id: CO_ID, tech_name: f.tech_name.value }, function (r) {
                    if (r && r.ok) { rsToast('Dispatched.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });

    var b2 = document.getElementById('btn_arrive');
    if (b2) b2.addEventListener('click', function () {
        $.confirm({ title:'Confirm arrival on site?', type:'green', buttons: {
            yes: { text:'Confirm', btnClass:'btn-success', action: function () {
                $.post(PROOT + 'Callouts/arriveAj', { co_id: CO_ID }, function (r) {
                    if (r && r.ok) { rsToast('On site.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });

    var b3 = document.getElementById('btn_resolve');
    if (b3) b3.addEventListener('click', function () {
        // Prefill from what PC/FS already typed in the Findings card (if the card exists).
        var invPrefill  = (document.getElementById('fn_inv')   || {}).value || '';
        var rcaPrefill  = (document.getElementById('fn_rca')   || {}).value || '';
        var snagPrefill = (document.getElementById('fn_snags') || {}).value || '';
        $.confirm({ title:'Resolve callout', columnClass:'col-md-8', type:'green', content:
            '<form id="rs_form">' +
              '<div class="row g-2 mb-2">' +
                '<div class="col-12"><label class="form-label small">Resolution description *</label><textarea name="resolution_description" rows="2" class="form-control form-control-sm" placeholder="e.g. Replaced AVR module; load-tested at 40kW for 15 minutes; system stable." required></textarea></div>' +
              '</div>' +
              '<div class="row g-2 mb-2">' +
                '<div class="col-6"><label class="form-label small">Issue found (diagnosis)</label><textarea name="investigation_notes" rows="3" class="form-control form-control-sm">' + esc(invPrefill) + '</textarea></div>' +
                '<div class="col-6"><label class="form-label small">Root cause (RCA)</label><textarea name="root_cause" rows="3" class="form-control form-control-sm">' + esc(rcaPrefill) + '</textarea></div>' +
              '</div>' +
              '<div class="mb-2"><label class="form-label small">Snags (outstanding)</label><textarea name="snags" rows="2" class="form-control form-control-sm">' + esc(snagPrefill) + '</textarea></div>' +
              '<div class="row g-2 mb-2">' +
                '<div class="col-6"><label class="form-label small">Labour hrs</label><input name="labour_hrs" type="number" step="0.01" min="0" class="form-control form-control-sm"></div>' +
                '<div class="col-6"><label class="form-label small">Mileage km</label><input name="mileage_km" type="number" step="0.01" min="0" class="form-control form-control-sm"></div>' +
              '</div>' +
            '</form>',
            buttons: {
                yes: { text:'Resolve', btnClass:'btn-success', action: function () {
                    var f = document.getElementById('rs_form');
                    var p = {
                        co_id: CO_ID,
                        resolution_description: f.resolution_description.value,
                        investigation_notes:    f.investigation_notes.value,
                        root_cause:             f.root_cause.value,
                        snags:                  f.snags.value,
                        labour_hrs:             f.labour_hrs.value,
                        mileage_km:             f.mileage_km.value
                    };
                    $.post(PROOT + 'Callouts/resolveAj', p, function (r) {
                        if (r && r.ok) { rsToast('Resolved.','success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }
        });
    });

    /* ── Slice 8Z-z-G · Save findings mid-flow (no status change) ─────── */
    var bFin = document.getElementById('btn_save_findings');
    if (bFin) bFin.addEventListener('click', function () {
        var p = {
            co_id: CO_ID,
            investigation_notes: (document.getElementById('fn_inv')   || {}).value || '',
            root_cause:          (document.getElementById('fn_rca')   || {}).value || '',
            snags:               (document.getElementById('fn_snags') || {}).value || ''
        };
        $.post(PROOT + 'Callouts/saveFindingsAj', p, function (r) {
            if (r && r.ok) rsToast('Findings saved.','success');
            else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
        }, 'json');
    });

    /* ── Slice 8Z-z-G · Client accepted ───────────────────────────────── */
    var bAcc = document.getElementById('btn_accept');
    if (bAcc) bAcc.addEventListener('click', function () {
        $.confirm({
            title: 'Client accepted the resolution', columnClass: 'col-md-6', type: 'green',
            content:
                '<form id="ac_form" enctype="multipart/form-data">' +
                    '<div class="mb-2"><label class="form-label small">Client representative name *</label><input name="client_name" class="form-control form-control-sm" required></div>' +
                    '<div class="mb-2"><label class="form-label small">Signature / acceptance photo (optional)</label><input type="file" name="signature" accept="image/*,.pdf" class="form-control form-control-sm"></div>' +
                    '<div class="small text-muted" style="font-size:.68rem;">Signed slip / photo of email agreement / WhatsApp screenshot all work. Uploaded as photo evidence with kind=CLIENT_SIGNATURE.</div>' +
                '</form>',
            buttons: {
                yes: { text: 'Confirm acceptance', btnClass: 'btn-success', action: function () {
                    var form = document.getElementById('ac_form');
                    if (!form.client_name.value.trim()) { $.alert({title:'Client name required', type:'orange'}); return false; }
                    var fd = new FormData(form);
                    fd.append('co_id', CO_ID);
                    $.ajax({ url: PROOT + 'Callouts/clientAcceptAj', method:'POST', data: fd, processData: false, contentType: false, dataType:'json' })
                        .done(function (r) {
                            if (r && r.ok) { rsToast('Client acceptance recorded.','success'); setTimeout(function(){location.reload();}, 500); }
                            else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                        }).fail(function () { $.alert({title:'Network error', type:'red'}); });
                    return false;
                }}, cancel: function () {}
            }
        });
    });

    /* ── Slice 8Z-z-G · Close callout ─────────────────────────────────── */
    var bCls = document.getElementById('btn_close');
    if (bCls) bCls.addEventListener('click', function () {
        $.confirm({
            title: 'Close this callout?', type: 'dark',
            content: 'Final terminal state. Ensure findings, parts used, photos and (if applicable) client acceptance are all in place before closing — it cannot be re-opened.',
            buttons: {
                yes: { text: 'Close callout', btnClass: 'btn-dark', action: function () {
                    $.post(PROOT + 'Callouts/closeAj', { co_id: CO_ID }, function (r) {
                        if (r && r.ok) { rsToast('Closed.','success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }
        });
    });

    // Slice 8S-7 · Photo evidence
    var phB = document.getElementById('btn_add_photo');
    if (phB) phB.addEventListener('click', function () {
        $.confirm({
            title:'Upload photo', columnClass:'col-md-6', type:'green',
            content: '<form id="ph_form" enctype="multipart/form-data">' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-4"><label class="form-label small">Kind</label><select name="kind" class="form-select form-select-sm"><option value="SITE">Site</option><option value="ARRIVAL">Arrival</option><option value="FAULT">Fault</option><option value="RESOLUTION" selected>Resolution</option><option value="CLIENT_SIGNATURE">Client signature</option><option value="OTHER">Other</option></select></div>' +
                  '<div class="col-8"><label class="form-label small">Caption</label><input name="caption" class="form-control form-control-sm"></div>' +
                '</div>' +
                '<div class="mb-2"><label class="form-label small">File (JPG/PNG/WEBP/PDF, max 10MB)</label><input type="file" name="photo" accept="image/*,.pdf" class="form-control form-control-sm" required></div>' +
            '</form>',
            buttons: {
                save: { text:'Upload', btnClass:'btn-success', action: function () {
                    var form = document.getElementById('ph_form');
                    var fd = new FormData(form);
                    fd.append('co_id', CO_ID);
                    if (!fd.get('photo') || !fd.get('photo').name) { $.alert({title:'Pick a file first', type:'orange'}); return false; }
                    $.ajax({
                        url: PROOT + 'Callouts/addPhotoAj',
                        method:'POST', data: fd, processData: false, contentType: false, dataType:'json'
                    }).done(function (r) {
                        if (r && r.ok) { rsToast('Uploaded.','success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }).fail(function () { $.alert({title:'Network error', type:'red'}); });
                    return false;
                }}, cancel: function () {}
            }
        });
    });
    document.querySelectorAll('.photo_del').forEach(function (b) {
        b.addEventListener('click', function (e) {
            e.stopPropagation();
            var pid = b.getAttribute('data-photo-id');
            $.confirm({ title:'Remove photo?', type:'red', buttons: {
                yes: { text:'Remove', btnClass:'btn-danger', action: function () {
                    $.post(PROOT + 'Callouts/removePhotoAj', { photo_id: pid }, function (r) {
                        if (r && r.ok) { rsToast('Removed.','success'); setTimeout(function(){location.reload();}, 300); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }});
        });
    });

    // Slice 8S-6 · Raise adhoc cash request
    var crB = document.getElementById('btn_cash_request');
    if (crB) crB.addEventListener('click', function () {
        $.confirm({
            title:'Raise adhoc cash request', columnClass:'col-md-6', type:'orange',
            content:
                '<div class="small mb-2 text-muted" style="font-size:.65rem;">Creates an IMPREST LPO pre-filled with this callout as the reason. Follows the normal cash-out chain (PC → Accountant disburse → your retirement).</div>' +
                '<form id="cr_form">' +
                '  <div class="row g-2 mb-2">' +
                '    <div class="col-6"><label class="form-label small">Amount (TZS) *</label><input name="amount" type="number" step="0.01" min="0" class="form-control form-control-sm" required></div>' +
                '    <div class="col-6 pt-4"><div class="text-muted small" style="font-size:.62rem;">Currency: TZS</div></div>' +
                '  </div>' +
                '  <div class="mb-2"><label class="form-label small">Reason / what to buy *</label><textarea name="reason" rows="2" class="form-control form-control-sm" placeholder="e.g. Injector pump replacement" required></textarea></div>' +
                '</form>',
            buttons: {
                yes: { text:'Raise LPO', btnClass:'btn-warning', action: function () {
                    var f = document.getElementById('cr_form');
                    var p = { co_id: CO_ID, amount: f.amount.value, reason: f.reason.value };
                    $.post(PROOT + 'Callouts/raiseCashRequestAj', p, function (r) {
                        if (r && r.ok) { rsToast('LPO ' + (r.lpo_no || '') + ' raised.','success'); setTimeout(function(){window.location.href = PROOT + 'Lpos/view/' + r.id;}, 700); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }
        });
    });

    var pB = document.getElementById('btn_add_part');
    if (pB) pB.addEventListener('click', function () {
        var partOpts = PARTS.map(function (p) { return '<option value="' + p.c0d + '">' + esc(p.sku + ' · ' + p.name) + '</option>'; }).join('');
        $.confirm({ title:'Add part used', columnClass:'col-md-6', type:'green', content: '<form id="pt_form"><div class="mb-2"><label class="form-label small">Part *</label><select name="part_id" class="form-select form-select-sm" required>' + partOpts + '</select></div><div class="row g-2 mb-2"><div class="col-4"><label class="form-label small">Qty *</label><input name="qty" type="number" step="0.01" min="0" class="form-control form-control-sm" value="1" required></div><div class="col-8"><label class="form-label small">Source</label><select name="source" class="form-select form-select-sm"><option value="STOCK">Stock</option><option value="PROCURED">Procured</option><option value="CLIENT_SUPPLIED">Client supplied</option><option value="ADHOC">Adhoc</option></select></div></div><div class="mb-2"><label class="form-label small">Notes</label><input name="notes" class="form-control form-control-sm"></div></form>', buttons: {
            save: { text:'Add', btnClass:'btn-success', action: function () {
                var f = document.getElementById('pt_form');
                var p = { co_id: CO_ID, part_id: f.part_id.value, qty: f.qty.value, source: f.source.value, notes: f.notes.value };
                $.post(PROOT + 'Callouts/addPartAj', p, function (r) {
                    if (r && r.ok) { rsToast('Added.','success'); setTimeout(function(){location.reload();}, 300); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });
})();
</script>
<?php $this->end(); ?>
