<?php $this->start('body');
    $inst    = $this->data['inst'];
    $items   = $this->data['items']   ?? [];
    $results = $this->data['results'] ?? [];
    $canSave    = !empty($this->data['can_save']);
    $canSubmit  = !empty($this->data['can_submit']);
    $canReview  = !empty($this->data['can_review']);
    $canReopen  = !empty($this->data['can_reopen']);
    $canClaim   = !empty($this->data['can_claim']);

    $statusPill = [
        'DRAFT'     => ['#f59e0b','In progress'],
        'SUBMITTED' => ['#0ea5e9','Submitted'],
        'APPROVED'  => ['#22c55e','Approved'],
        'REJECTED'  => ['#dc2626','Rejected'],
        'CANCELLED' => ['#94a3b8','Cancelled'],
    ];
    $sp = $statusPill[$inst['status']] ?? ['#94a3b8', $inst['status']];

    // Group items by section for cleaner rendering
    $bySection = [];
    foreach ($items as $it) { $bySection[$it['section'] ?: 'General'][] = $it; }
?>
<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-clipboard-check me-1 text-muted"></i>
            <?= htmlspecialchars($inst['ref_label']); ?>
            <span class="badge ms-2" style="background:<?= $sp[0]; ?>;color:#fff;"><?= htmlspecialchars($sp[1]); ?></span>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($inst['template_title']); ?> · v<?= (int)$inst['template_version']; ?> ·
            target <?= htmlspecialchars($inst['target_entity_type']); ?> #<?= (int)$inst['target_entity_id']; ?>
            <?php if ($inst['assignee_name']): ?>· assignee: <?= htmlspecialchars($inst['assignee_name']); ?><?php endif; ?>
        </div>
    </div>
    <a href="<?= PROOT; ?>WorkInstances/myQueue" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Queue</a>
</div>

<?php if ($inst['status'] === 'REJECTED' && $inst['review_notes']): ?>
    <div class="alert py-2 mb-3" style="background:#FEE2E2;border:1px solid #dc2626;color:#7f1d1d;">
        <i class="fas fa-times-circle me-1"></i>
        <strong>Rejected by <?= htmlspecialchars($inst['reviewed_by_name']); ?></strong>
        · reason: <em><?= htmlspecialchars($inst['review_notes']); ?></em>
        <?php if ($canReopen): ?>
            <button type="button" class="btn btn-sm btn-outline-danger float-end" onclick="wiReopen()"><i class="fas fa-undo me-1"></i> Reopen for edit</button>
        <?php endif; ?>
    </div>
<?php elseif ($inst['status'] === 'APPROVED'): ?>
    <div class="alert py-2 mb-3" style="background:#DCFCE7;border:1px solid #22c55e;color:#166534;">
        <i class="fas fa-check-circle me-1"></i>
        <strong>Approved by <?= htmlspecialchars($inst['reviewed_by_name']); ?></strong>
        · <?= htmlspecialchars((string)$inst['reviewed_at']); ?>
        <?php if ($inst['review_notes']): ?>· notes: <em><?= htmlspecialchars($inst['review_notes']); ?></em><?php endif; ?>
    </div>
<?php endif; ?>

<?php if ($canClaim): ?>
    <div class="alert py-2 mb-3 d-flex align-items-center justify-content-between" style="background:#FEF3C7;border:1px solid #F59E0B;color:#78350F;">
        <div><i class="fas fa-user-plus me-1"></i> Unclaimed — the first person to claim owns it.</div>
        <button type="button" class="btn btn-sm btn-warning" onclick="wiClaim()"><i class="fas fa-hand-paper me-1"></i> Claim</button>
    </div>
<?php endif; ?>

<?php foreach ($bySection as $section => $secItems): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong><?= htmlspecialchars($section); ?></strong></div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <tbody>
                <?php foreach ($secItems as $it):
                    $r = $results[(int)$it['c0d']] ?? null;
                    $val = $r['value_text'] ?? ($r['value_number'] ?? ($r['value_date'] ?? ''));
                ?>
                    <tr data-item="<?= (int)$it['c0d']; ?>">
                        <td style="width:40px;" class="text-muted"><?= (int)$it['sort_order']; ?></td>
                        <td>
                            <div>
                                <?= htmlspecialchars($it['prompt']); ?>
                                <?php if ((int)$it['is_required'] === 1): ?><span class="text-danger">*</span><?php endif; ?>
                            </div>
                            <?php if (!empty($it['help_text'])): ?><div class="text-muted small"><?= htmlspecialchars($it['help_text']); ?></div><?php endif; ?>
                        </td>
                        <td style="width:280px;">
                            <?php if ($canSave): ?>
                                <?php if ($it['input_type'] === 'CHECK'): ?>
                                    <div class="btn-group btn-group-sm w-100 wi-check" role="group">
                                        <input type="radio" class="btn-check" name="ck_<?= (int)$it['c0d']; ?>" id="ck_<?= (int)$it['c0d']; ?>_ok" value="OK" <?= $val === 'OK' ? 'checked' : ''; ?>>
                                        <label class="btn btn-outline-success" for="ck_<?= (int)$it['c0d']; ?>_ok">OK</label>
                                        <input type="radio" class="btn-check" name="ck_<?= (int)$it['c0d']; ?>" id="ck_<?= (int)$it['c0d']; ?>_no" value="NOTOK" <?= $val === 'NOTOK' ? 'checked' : ''; ?>>
                                        <label class="btn btn-outline-danger" for="ck_<?= (int)$it['c0d']; ?>_no">Not OK</label>
                                        <input type="radio" class="btn-check" name="ck_<?= (int)$it['c0d']; ?>" id="ck_<?= (int)$it['c0d']; ?>_na" value="NA" <?= $val === 'NA' ? 'checked' : ''; ?>>
                                        <label class="btn btn-outline-secondary" for="ck_<?= (int)$it['c0d']; ?>_na">N/A</label>
                                    </div>
                                <?php elseif ($it['input_type'] === 'NUMBER'): ?>
                                    <div class="input-group input-group-sm">
                                        <input type="number" step="0.01" class="form-control form-control-sm wi-value" value="<?= htmlspecialchars((string)$val); ?>">
                                        <?php if ($it['numeric_unit']): ?><span class="input-group-text"><?= htmlspecialchars($it['numeric_unit']); ?></span><?php endif; ?>
                                    </div>
                                <?php elseif ($it['input_type'] === 'DATE'): ?>
                                    <input type="date" class="form-control form-control-sm wi-value" value="<?= htmlspecialchars((string)$val); ?>">
                                <?php elseif ($it['input_type'] === 'LONGTEXT'): ?>
                                    <textarea rows="2" class="form-control form-control-sm wi-value"><?= htmlspecialchars((string)$val); ?></textarea>
                                <?php else: ?>
                                    <input type="text" class="form-control form-control-sm wi-value" value="<?= htmlspecialchars((string)$val); ?>">
                                <?php endif; ?>
                                <input type="text" class="form-control form-control-sm mt-1 wi-note" placeholder="Note (optional)" value="<?= htmlspecialchars((string)($r['note'] ?? '')); ?>" style="font-size:.7rem;">
                            <?php else: ?>
                                <?php if ($val): ?>
                                    <span class="badge <?= $val === 'OK' ? 'bg-success' : ($val === 'NOTOK' ? 'bg-danger' : 'bg-secondary'); ?>"><?= htmlspecialchars((string)$val); ?></span>
                                    <?php if (!empty($r['note'])): ?><div class="text-muted small"><?= htmlspecialchars($r['note']); ?></div><?php endif; ?>
                                <?php else: ?>
                                    <span class="text-muted small">—</span>
                                <?php endif; ?>
                            <?php endif; ?>
                        </td>
                        <?php if ($canSave): ?>
                            <td class="text-end" style="width:50px;">
                                <button type="button" class="btn btn-sm btn-outline-primary wi-save"><i class="fas fa-save"></i></button>
                            </td>
                        <?php endif; ?>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endforeach; ?>

<div class="d-flex gap-2 justify-content-end mb-3">
    <?php if ($canSubmit): ?>
        <button type="button" class="btn btn-sm btn-success" onclick="wiSubmit()"><i class="fas fa-paper-plane me-1"></i> Submit</button>
    <?php endif; ?>
    <?php if ($canReview): ?>
        <button type="button" class="btn btn-sm btn-outline-danger" onclick="wiReject()"><i class="fas fa-times-circle me-1"></i> Reject</button>
        <button type="button" class="btn btn-sm btn-success" onclick="wiApprove()"><i class="fas fa-check me-1"></i> Approve</button>
    <?php endif; ?>
</div>

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

<?php $this->start('section_js'); ?>
<script>
const WI_ID = <?= (int)$inst['c0d']; ?>;

$('.wi-save').on('click', function () {
    const tr = $(this).closest('tr');
    const iid = tr.data('item');
    let value = tr.find('.wi-check input:checked').val();
    if (typeof value === 'undefined') value = tr.find('.wi-value').val() || '';
    const note = tr.find('.wi-note').val() || '';
    $.post('<?= PROOT; ?>WorkInstances/saveResultAj',
        { instance_id: WI_ID, item_id: iid, value: value, note: note }, 'json')
        .done(function (r) {
            if (r && r.ok) { if (typeof rsToast === 'function') rsToast('Saved.', 'success'); else console.log('saved'); }
            else rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
        });
});

function wiSubmit() {
    if (!confirm('Submit for review? You cannot edit after submitting unless the reviewer rejects.')) return;
    $.post('<?= PROOT; ?>WorkInstances/submitAj', { id: WI_ID }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function wiClaim() {
    $.post('<?= PROOT; ?>WorkInstances/claimAj', { id: WI_ID }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function wiApprove() {
    const n = prompt('Approval notes (optional):', '');
    if (n === null) return;
    $.post('<?= PROOT; ?>WorkInstances/approveAj', { id: WI_ID, notes: n }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function wiReject() {
    const n = prompt('Reason for rejecting (required):', '');
    if (!n || !n.trim()) { rsToast('Reason required.', 'error'); return; }
    $.post('<?= PROOT; ?>WorkInstances/rejectAj', { id: WI_ID, reason: n.trim() }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function wiReopen() {
    if (!confirm('Reopen for edit? Status goes back to In Progress.')) return;
    $.post('<?= PROOT; ?>WorkInstances/reopenAj', { id: WI_ID }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
</script>
<?php $this->end(); ?>
