<?php $this->start('body');
    $pm       = $this->data['pm'];
    $findings = $this->data['findings'] ?? [];
    $parts    = $this->data['parts']    ?? [];
    $catalog  = $this->data['parts_catalog'] ?? [];
    $canExec  = !empty($this->data['can_execute']);
    $canRev   = !empty($this->data['can_review']);
    $canAcc   = !empty($this->data['can_accept']);
    $photos   = $this->data['photos'] ?? [];
    $canUploadPhoto = $canExec || $canRev || $canAcc;
    $chip = [
        'DRAFT'           => ['#F1F5F9','#334155','Draft'],
        'IN_PROGRESS'     => ['#FEF3E7','#8B6914','In progress'],
        'DONE'            => ['#EEF2F6','#7A8BA1','Done'],
        'REVIEWED'        => ['#EAF2E8','#3F5C43','Reviewed'],
        'CLIENT_ACCEPTED' => ['#EAF2E8','#3F5C43','Client accepted'],
        'CANCELLED'       => ['#F5EAE1','#C48579','Cancelled'],
    ];
    $sc = $chip[$pm['status']] ?? ['#F1F5F9','#334155',$pm['status']];
    // Group findings by section
    $bySection = [];
    foreach ($findings as $f) { $bySection[$f['section'] ?: '(no section)'][] = $f; }
?>
<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-toolbox me-2 text-muted"></i><?= htmlspecialchars($pm['pm_no']); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <?= htmlspecialchars((string)$pm['site_name']); ?> · <strong><?= htmlspecialchars((string)$pm['asset_no']); ?></strong>
            &middot; <?php if (!empty($pm['asset_icon'])): ?><i class="fas <?= htmlspecialchars($pm['asset_icon']); ?>"></i> <?php endif; ?><?= htmlspecialchars((string)$pm['asset_type_name']); ?>
            &middot; Template <strong><?= htmlspecialchars((string)$pm['template_code']); ?></strong> v<?= (int)$pm['template_version']; ?>
        </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; ?>PmServices" 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">
    <div class="col-lg-8">
        <?php foreach ($bySection as $section => $rows): ?>
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;"><?= htmlspecialchars($section); ?></div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light"><tr><th style="width:38px;">#</th><th>Task</th><th style="width:200px;">Result</th><th>Remark</th></tr></thead>
                    <tbody>
                        <?php foreach ($rows as $f):
                            $done = !empty($f['c0d']) && ($f['result_check'] !== null || $f['result_number'] !== null || $f['result_text'] !== null || $f['result_photo_path'] !== null || $f['result_signature_path'] !== null);
                        ?>
                            <tr data-item-id="<?= (int)$f['c0d'] > 0 ? (int)$f['template_item_id'] : 0; ?>" data-input-type="<?= htmlspecialchars($f['input_type']); ?>" data-json='<?= htmlspecialchars(json_encode($f), ENT_QUOTES); ?>'>
                                <td class="text-muted small"><?= (int)$f['sort_order']; ?><?php if ((int)$f['is_required'] === 1): ?><span class="text-danger">*</span><?php endif; ?></td>
                                <td class="small"><?= htmlspecialchars($f['task']); ?><div class="text-muted" style="font-size:.6rem;"><?= htmlspecialchars(strtolower($f['input_type'])); ?><?php if (!empty($f['unit'])): ?> · <?= htmlspecialchars((string)$f['unit']); ?><?php endif; ?></div></td>
                                <td class="small">
                                    <?php if (!$done): ?>
                                        <span class="text-muted"><em>pending</em></span>
                                    <?php else:
                                        switch ($f['input_type']) {
                                            case 'CHECK':  echo (int)$f['result_check'] === 1 ? '<i class="fas fa-check-circle text-success"></i> yes' : '<i class="fas fa-times-circle text-danger"></i> no'; break;
                                            case 'NUMBER': echo '<strong>' . number_format((float)$f['result_number'], (fmod((float)$f['result_number'],1)==0?0:2)) . '</strong> ' . htmlspecialchars((string)($f['unit'] ?? '')); break;
                                            case 'TEXT':   echo htmlspecialchars((string)$f['result_text']); break;
                                            case 'PHOTO':  echo '<i class="fas fa-image text-muted"></i> ' . htmlspecialchars(basename((string)$f['result_photo_path'])); break;
                                            case 'SIGNATURE': echo '<i class="fas fa-signature text-muted"></i> captured'; break;
                                        }
                                        if (!empty($f['qty_replaced'])): ?>
                                            <div class="text-muted" style="font-size:.6rem;">qty replaced: <?= number_format((float)$f['qty_replaced'], (fmod((float)$f['qty_replaced'],1)==0?0:2)); ?></div>
                                        <?php endif;
                                    endif; ?>
                                </td>
                                <td class="small text-muted"><?= htmlspecialchars((string)($f['remark'] ?? '')); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if (!empty($parts) || $canExec): ?>
        <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 ($canExec): ?><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 yet.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <!-- 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; ?>PmServices/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; ?>PmServices/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>
    </div>

    <div class="col-lg-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;"><i class="fas fa-info-circle me-1"></i>Metadata</div>
            <div class="card-body p-3 small">
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Scheduled</span><span><?= htmlspecialchars((string)($pm['scheduled_for'] ?? '—')); ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Started</span><span><?= htmlspecialchars((string)($pm['started_at'] ?? '—')); ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Finished</span><span><?= htmlspecialchars((string)($pm['finished_at'] ?? '—')); ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">PPE confirmed</span><span><?= (int)$pm['ppe_confirmed'] === 1 ? '<i class="fas fa-check text-success"></i> yes' : '—'; ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Done by</span><span><?= htmlspecialchars((string)($pm['done_by_name'] ?? '—')); ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Reviewed by</span><span><?= htmlspecialchars((string)($pm['reviewed_by_name'] ?? '—')); ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Client decision</span><span><?= htmlspecialchars((string)($pm['client_decision'] ?? '—')); ?></span></div>
                <?php if (!empty($pm['client_decided_by_name'])): ?>
                    <div class="d-flex justify-content-between mb-1"><span class="text-muted">Client name</span><span><?= htmlspecialchars((string)$pm['client_decided_by_name']); ?></span></div>
                <?php endif; ?>
            </div>
        </div>

        <div class="card border-0 shadow-sm mt-3">
            <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;"><i class="fas fa-bolt me-1 text-muted"></i>Actions</div>
            <div class="card-body p-3 d-flex flex-column gap-2">
                <?php if ($canExec && $pm['status'] === 'DRAFT'): ?>
                    <button type="button" id="btn_start" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-play me-1"></i>Start PM</button>
                <?php endif; ?>
                <?php if ($canExec && $pm['status'] === 'IN_PROGRESS'): ?>
                    <button type="button" id="btn_finish" class="btn btn-sm" style="background:#3F5C43;border-color:#3F5C43;color:#fff;font-weight:600;"><i class="fas fa-check-square me-1"></i>Finish PM</button>
                <?php endif; ?>
                <?php if ($canRev): ?>
                    <button type="button" id="btn_review" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-clipboard-check me-1"></i>Review &amp; sign off</button>
                <?php endif; ?>
                <?php if ($canAcc): ?>
                    <button type="button" id="btn_accept" class="btn btn-sm btn-outline-warning"><i class="fas fa-user-check me-1"></i>Capture client acceptance</button>
                <?php endif; ?>
                <?php if ($canExec && in_array($pm['status'], ['IN_PROGRESS'], true)): ?>
                    <button type="button" id="btn_cash_request" class="btn btn-sm btn-outline-warning"><i class="fas fa-hand-holding-usd me-1"></i>Raise cash request (adhoc spare)</button>
                <?php endif; ?>
                <?php if (!$canExec && !$canRev && !$canAcc): ?>
                    <div class="text-muted small">No actions available.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    var PM_ID = <?= (int)$pm['c0d']; ?>;
    var PROOT = '<?= PROOT; ?>';
    var PARTS = <?= json_encode(array_map(fn($p) => ['c0d'=>(int)$p['c0d'],'sku'=>$p['sku'],'name'=>$p['name']], $catalog)); ?>;
    var CAN_EDIT_FINDINGS = <?= ($canExec ? 'true' : 'false'); ?>;

    function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]); }); }

    // Click row to record finding
    if (CAN_EDIT_FINDINGS) {
        document.querySelectorAll('tr[data-item-id]').forEach(function (tr) {
            tr.style.cursor = 'pointer';
            tr.addEventListener('click', function () {
                var itemId    = parseInt(tr.getAttribute('data-item-id'), 10);
                var inputType = tr.getAttribute('data-input-type');
                var data      = JSON.parse(tr.getAttribute('data-json'));
                if (itemId <= 0) return; // shouldn't happen — always the template_item_id
                // PHOTO / SIGNATURE input types now do a real file upload instead of text.
                if (inputType === 'PHOTO' || inputType === 'SIGNATURE') {
                    var isSig = (inputType === 'SIGNATURE');
                    var currentPath = isSig ? data.result_signature_path : data.result_photo_path;
                    var currentPreview = '';
                    if (currentPath) currentPreview = '<div class="mb-2 text-muted small" style="font-size:.65rem;">Current: <a href="' + PROOT + esc(currentPath) + '" target="_blank">' + esc(currentPath.split('/').pop()) + '</a></div>';
                    $.confirm({
                        title:'Upload ' + (isSig ? 'signature' : 'photo') + ' · ' + esc(data.task), columnClass:'col-md-6', type:'green',
                        content: currentPreview + '<form id="fd_upload_form" enctype="multipart/form-data">' +
                            '<input type="hidden" name="pm_id" value="' + PM_ID + '">' +
                            '<input type="hidden" name="template_item_id" value="' + itemId + '">' +
                            '<input type="hidden" name="is_signature" value="' + (isSig ? '1' : '0') + '">' +
                            '<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>' +
                            '<div class="mb-2"><label class="form-label small">Remark</label><input name="remark_hidden" class="form-control form-control-sm" value="' + esc(data.remark||'') + '"></div>' +
                        '</form>',
                        buttons: {
                            save: { text:'Upload', btnClass:'btn-success', action: function () {
                                var form = document.getElementById('fd_upload_form');
                                var fd = new FormData(form);
                                if (!fd.get('photo') || !fd.get('photo').name) { $.alert({title:'Pick a file first', type:'orange'}); return false; }
                                $.ajax({
                                    url: PROOT + 'PmServices/saveFindingPhotoAj',
                                    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 () {}
                        }
                    });
                    return;
                }
                var content = '<form id="fd_form"><input type="hidden" name="pm_id" value="' + PM_ID + '"><input type="hidden" name="template_item_id" value="' + itemId + '">';
                if (inputType === 'CHECK') {
                    content += '<label class="form-label small">Result</label><select name="result_check" class="form-select form-select-sm"><option value="1">Yes / pass</option><option value="0">No / fail</option></select>';
                } else if (inputType === 'NUMBER') {
                    content += '<label class="form-label small">Value</label><input name="result_number" type="number" step="0.01" class="form-control form-control-sm" value="' + (data.result_number || '') + '" required>';
                } else if (inputType === 'TEXT') {
                    content += '<label class="form-label small">Text</label><textarea name="result_text" rows="3" class="form-control form-control-sm">' + esc(data.result_text||'') + '</textarea>';
                }
                content += '<div class="row g-2 mt-2"><div class="col-6"><label class="form-label small">Qty replaced (if tracked)</label><input name="qty_replaced" type="number" step="0.01" min="0" class="form-control form-control-sm" value="' + (data.qty_replaced || '') + '"></div><div class="col-6"><label class="form-label small">Remark</label><input name="remark" class="form-control form-control-sm" value="' + esc(data.remark||'') + '"></div></div></form>';
                $.confirm({
                    title:'Record finding · ' + esc(data.task), columnClass:'col-md-6', type:'green', content: content,
                    buttons: {
                        save: { text:'Save', btnClass:'btn-success', action: function () {
                            var f = document.getElementById('fd_form');
                            var p = { pm_id: PM_ID, template_item_id: itemId };
                            ['result_check','result_number','result_text','qty_replaced','remark'].forEach(function (k) { if (f[k]) p[k] = f[k].value; });
                            $.post(PROOT + 'PmServices/saveFindingAj', p, function (r) {
                                if (r && r.ok) { rsToast('Saved.','success'); setTimeout(function(){location.reload();}, 300); }
                                else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                            }, 'json');
                        }}, cancel: function () {}
                    }
                });
            });
        });
    }

    // Start
    var b1 = document.getElementById('btn_start');
    if (b1) b1.addEventListener('click', function () {
        $.confirm({ title:'Start PM?', type:'green', content:'<form id="st_form"><div class="form-check mb-2"><input type="checkbox" name="ppe_confirmed" class="form-check-input" checked><label class="form-check-label small">PPE confirmed</label></div><div class="row g-2 mb-2"><div class="col-6"><label class="form-label small">GPS lat</label><input name="gps_lat" type="number" step="0.0000001" class="form-control form-control-sm"></div><div class="col-6"><label class="form-label small">GPS lng</label><input name="gps_lng" type="number" step="0.0000001" class="form-control form-control-sm"></div></div></form>', buttons: {
            yes: { text:'Start', btnClass:'btn-success', action: function () {
                var f = document.getElementById('st_form');
                var p = { pm_id: PM_ID, ppe_confirmed: f.ppe_confirmed.checked ? 1 : 0, gps_lat: f.gps_lat.value, gps_lng: f.gps_lng.value };
                $.post(PROOT + 'PmServices/startAj', p, function (r) {
                    if (r && r.ok) { rsToast('Started.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });

    // Add part
    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 = { pm_id: PM_ID, part_id: f.part_id.value, qty: f.qty.value, source: f.source.value, notes: f.notes.value };
                $.post(PROOT + 'PmServices/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 () {}
        }});
    });

    // Finish
    var fB = document.getElementById('btn_finish');
    if (fB) fB.addEventListener('click', function () {
        $.confirm({ title:'Finish PM?', type:'green', content:'<textarea id="fn_notes" rows="3" class="form-control form-control-sm" placeholder="Closing notes..."></textarea>', buttons: {
            yes: { text:'Finish', btnClass:'btn-success', action: function () {
                $.post(PROOT + 'PmServices/finishAj', { pm_id: PM_ID, notes: document.getElementById('fn_notes').value || '' }, function (r) {
                    if (r && r.ok) { rsToast('Finished.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });

    // Review
    var rB = document.getElementById('btn_review');
    if (rB) rB.addEventListener('click', function () {
        $.confirm({ title:'Review PM?', type:'green', content:'<textarea id="rv_notes" rows="3" class="form-control form-control-sm" placeholder="Reviewer notes..."></textarea>', buttons: {
            yes: { text:'Sign off', btnClass:'btn-success', action: function () {
                $.post(PROOT + 'PmServices/reviewAj', { pm_id: PM_ID, notes: document.getElementById('rv_notes').value || '' }, function (r) {
                    if (r && r.ok) { rsToast('Reviewed.','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 (general PM photos)
    var phB = document.getElementById('btn_add_photo');
    if (phB) phB.addEventListener('click', function () {
        $.confirm({
            title:'Upload PM 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="PPE">PPE</option><option value="FINDING">Finding</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('pm_id', PM_ID);
                    if (!fd.get('photo') || !fd.get('photo').name) { $.alert({title:'Pick a file first', type:'orange'}); return false; }
                    $.ajax({
                        url: PROOT + 'PmServices/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 + 'PmServices/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 from PM
    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 PM as the reason.</div>' +
                '<form id="cr_form">' +
                '  <div class="mb-2"><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="mb-2"><label class="form-label small">Reason / what to buy *</label><textarea name="reason" rows="2" class="form-control form-control-sm" required></textarea></div>' +
                '</form>',
            buttons: {
                yes: { text:'Raise LPO', btnClass:'btn-warning', action: function () {
                    var f = document.getElementById('cr_form');
                    var p = { pm_id: PM_ID, amount: f.amount.value, reason: f.reason.value };
                    $.post(PROOT + 'PmServices/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 () {}
            }
        });
    });

    // Client accept
    var aB = document.getElementById('btn_accept');
    if (aB) aB.addEventListener('click', function () {
        $.confirm({ title:'Client acceptance', type:'orange', columnClass:'col-md-5', content:'<form id="ac_form"><div class="mb-2"><label class="form-label small">Client name</label><input name="client_name" class="form-control form-control-sm" required></div><div class="mb-2"><label class="form-label small">Signature path (upload in later slice)</label><input name="signature_path" class="form-control form-control-sm"></div><div class="mb-2"><label class="form-label small">Decision</label><select name="decision" class="form-select form-select-sm"><option value="ACCEPTED">Accepted</option><option value="REJECTED">Rejected</option></select></div></form>', buttons: {
            save: { text:'Save', btnClass:'btn-warning', action: function () {
                var f = document.getElementById('ac_form');
                var p = { pm_id: PM_ID, client_name: f.client_name.value, signature_path: f.signature_path.value, decision: f.decision.value };
                $.post(PROOT + 'PmServices/clientAcceptAj', p, function (r) {
                    if (r && r.ok) { rsToast('Saved.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });
})();
</script>
<?php $this->end(); ?>
