<?php $this->start('body');
    $p      = $this->data['project'];
    $tasks  = $this->data['tasks']        ?? [];
    $slots  = $this->data['slot_options'] ?? [];

    $slotLabel = [
        'PROJECT_MANAGER'      => 'Project Manager',
        'PROJECTS_COORDINATOR' => 'Projects Coordinator',
        'PROCUREMENT'          => 'Procurement',
        'ACCOUNTANT'           => 'Accountant',
        'FIELD_SUPERVISOR'     => 'Field Supervisor',
        'FINANCE_MANAGER'      => 'Finance Manager',
        'EXECUTIVE'            => 'Executive',
        'STORES'               => 'Stores',
        'CRM'                  => 'CRM',
    ];
    $statusPill = [
        'OPEN'    => '<span class="badge" style="background:#f59e0b;color:#fff;">Open</span>',
        'DONE'    => '<span class="badge" style="background:#22c55e;color:#fff;">Done</span>',
        'SKIPPED' => '<span class="badge" style="background:#94a3b8;color:#fff;">Skipped</span>',
    ];

    $doneCount   = 0; $openCount = 0; $skipCount = 0;
    foreach ($tasks as $t) {
        if ($t['status'] === 'DONE') $doneCount++;
        elseif ($t['status'] === 'SKIPPED') $skipCount++;
        else $openCount++;
    }
    $total = count($tasks);
    $progressPct = $total ? round(($doneCount + $skipCount) * 100 / $total) : 0;
?>

<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-list-check me-1 text-muted"></i>
            <?= htmlspecialchars($p['project_no']); ?> · <?= htmlspecialchars($p['project_name']); ?>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($p['project_customer']); ?> ·
            <span style="text-transform:capitalize;"><?= htmlspecialchars($p['project_type']); ?></span> ·
            <?= htmlspecialchars($p['currency']); ?> <?= number_format((float)$p['contract_value']); ?>
        </div>
    </div>
    <a href="<?= PROOT; ?>Projects/view/<?= (int)$p['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Project</a>
</div>

<!-- Progress + seats -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3">
        <div class="d-flex align-items-center mb-2">
            <div class="me-3" style="min-width:140px;">
                <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.62rem;">Progress</div>
                <div><strong><?= $doneCount + $skipCount; ?></strong> / <?= $total; ?> tasks</div>
            </div>
            <div class="flex-grow-1">
                <div class="progress" style="height:10px;background:#e2e8f0;">
                    <div class="progress-bar" role="progressbar" style="width:<?= $progressPct; ?>%;background:#22c55e;" aria-valuenow="<?= $progressPct; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            </div>
            <div class="ms-3 text-muted small" style="text-transform:capitalize;"><?= $progressPct; ?>% complete</div>
        </div>
        <div class="row g-2 mt-2">
            <div class="col-md-3 col-lg-2"><div class="text-muted small">Project Manager</div><div><?= htmlspecialchars($p['project_manager_name'] ?: '—'); ?></div></div>
            <div class="col-md-3 col-lg-2"><div class="text-muted small">Projects Coordinator</div><div><?= htmlspecialchars($p['pc_name'] ?: '—'); ?></div></div>
            <div class="col-md-3 col-lg-2"><div class="text-muted small">Field Supervisor</div><div><?= htmlspecialchars(($p['fs_name'] ?? '') ?: '—'); ?></div></div>
            <div class="col-md-3 col-lg-3"><div class="text-muted small">Accountant</div><div><?= htmlspecialchars($p['accountant_name'] ?: '—'); ?></div></div>
            <div class="col-md-3 col-lg-3"><div class="text-muted small">Procurement</div><div><?= htmlspecialchars($p['procurement_name'] ?: '—'); ?></div></div>
        </div>
    </div>
</div>

<!-- Checklist -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong>Onboarding checklist</strong></div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:40px;">#</th>
                    <th>Task</th>
                    <th>Owner</th>
                    <th style="width:110px;">Due</th>
                    <th style="width:90px;">Status</th>
                    <th style="width:220px;" class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($tasks as $i => $t):
                    $users = $slots[$t['owner_slot']] ?? [];
                    $link  = str_replace('{project_id}', (string)(int)$t['project_id'], (string)$t['target_url_template']);
                ?>
                    <tr data-task="<?= (int)$t['c0d']; ?>">
                        <td class="text-muted"><?= (int)($t['sequence'] / 10); ?></td>
                        <td>
                            <div><strong><?= htmlspecialchars($t['task_label']); ?></strong></div>
                            <div class="text-muted small"><?= htmlspecialchars($t['task_description']); ?></div>
                            <div class="small mt-1">
                                <span class="badge bg-light text-dark" style="text-transform:capitalize;">
                                    <?= htmlspecialchars($slotLabel[$t['owner_slot']] ?? strtolower(str_replace('_',' ',$t['owner_slot']))); ?>
                                </span>
                                <a class="ms-1" href="<?= PROOT . htmlspecialchars($link); ?>"><i class="fas fa-external-link-alt"></i> open</a>
                            </div>
                        </td>
                        <td>
                            <?php if ($t['status'] === 'OPEN'): ?>
                                <select class="form-select form-select-sm rs-owner-select" style="min-width:180px;" data-task="<?= (int)$t['c0d']; ?>">
                                    <option value="">— Pick a user —</option>
                                    <?php foreach ($users as $u): ?>
                                        <option value="<?= (int)$u['c0d']; ?>" data-name="<?= htmlspecialchars($u['full_name']); ?>" <?= ((int)$u['c0d'] === (int)$t['owner_user_id']) ? 'selected' : ''; ?>>
                                            <?= htmlspecialchars($u['full_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            <?php else: ?>
                                <span class="text-muted small"><?= htmlspecialchars($t['owner_user_name'] ?: '—'); ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-muted small"><?= htmlspecialchars($t['due_date'] ?? ''); ?></td>
                        <td><?= $statusPill[$t['status']] ?? htmlspecialchars($t['status']); ?></td>
                        <td class="text-end">
                            <?php if ($t['status'] === 'OPEN'): ?>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="psSkip(<?= (int)$t['c0d']; ?>)"><i class="fas fa-forward"></i> Skip</button>
                                <button type="button" class="btn btn-sm btn-success" onclick="psComplete(<?= (int)$t['c0d']; ?>)"><i class="fas fa-check"></i> Done</button>
                            <?php else: ?>
                                <div class="text-muted small">
                                    <?= htmlspecialchars($t['status'] === 'DONE' ? 'By ' : 'Skipped by '); ?><?= htmlspecialchars($t['completed_by_name'] ?: '—'); ?>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-warning" onclick="psReopen(<?= (int)$t['c0d']; ?>)"><i class="fas fa-undo"></i> Reopen</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($tasks)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">No starter tasks — project may pre-date the onboarding checklist.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.querySelectorAll('.rs-owner-select').forEach(sel => {
    sel.addEventListener('change', () => {
        const tid = sel.getAttribute('data-task');
        const uid = sel.value;
        if (!uid) return;
        const name = sel.options[sel.selectedIndex].getAttribute('data-name') || '';
        psPost('assignOwnerAj', 'task_id=' + tid + '&user_id=' + encodeURIComponent(uid) + '&user_name=' + encodeURIComponent(name));
    });
});
function psComplete(tid) {
    const n = prompt('Optional notes (leave blank to skip):', '');
    if (n === null) return;
    psPost('completeAj', 'task_id=' + tid + '&notes=' + encodeURIComponent(n));
}
function psSkip(tid) {
    const r = prompt('Reason for skipping (required):', '');
    if (!r || !r.trim()) { alert('A reason is required.'); return; }
    psPost('skipAj', 'task_id=' + tid + '&reason=' + encodeURIComponent(r.trim()));
}
function psReopen(tid) {
    if (!confirm('Reopen this task?')) return;
    psPost('reopenAj', 'task_id=' + tid);
}
function psPost(action, body) {
    fetch('<?= PROOT; ?>ProjectStarter/' + action, {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: body
    }).then(r => r.json()).then(j => {
        alert(j.msg || (j.ok?'Done':'Failed'));
        if (j.ok) location.reload();
    }).catch(() => alert('Network error'));
}
</script>
<?php $this->end(); ?>
