<?php $this->start('body');
    $plan      = $this->data['plan'];
    $project   = $this->data['project'] ?? [];
    $items     = $this->data['items']    ?? [];
    $assets    = $this->data['assets']   ?? [];
    $templates = $this->data['templates']?? [];

    $statusPill = [
        'PLANNED'   => ['#f59e0b', 'Planned'],
        'ACTIVE'    => ['#22c55e', 'Active'],
        'CLOSED'    => ['#94a3b8', 'Closed'],
        'CANCELLED' => ['#dc2626', 'Cancelled'],
    ];
    $sp = $statusPill[$plan['status']] ?? ['#94a3b8', $plan['status']];
    $canEdit = in_array($plan['status'], ['PLANNED','ACTIVE'], true);
?>
<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-calendar-check me-1 text-muted"></i>
            <?= htmlspecialchars($plan['title']); ?>
            <span class="badge ms-2" style="background:<?= $sp[0]; ?>;color:#fff;"><?= htmlspecialchars($sp[1]); ?></span>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            Project: <?= htmlspecialchars($project['project_no'] ?? '?'); ?> ·
            planned: <?= htmlspecialchars($plan['planned_start'] ?? '—'); ?> → <?= htmlspecialchars($plan['planned_end'] ?? '—'); ?>
        </div>
    </div>
    <div class="d-flex gap-2">
        <?php if ($plan['status'] === 'PLANNED'): ?>
            <button type="button" class="btn btn-sm btn-success" onclick="pmpAct('activate')"><i class="fas fa-play me-1"></i> Activate</button>
        <?php endif; ?>
        <a href="<?= PROOT; ?>ServicePmPlans/create/<?= (int)$plan['project_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
    </div>
</div>

<?php if ($canEdit && !empty($assets) && !empty($templates)): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Add asset × template mapping</strong></div>
    <div class="card-body p-3" style="background:#F8FAFC;">
        <div class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="form-label" style="font-size:.78rem;">Asset</label>
                <select id="ai_asset" class="form-select form-select-sm">
                    <option value="">— Pick —</option>
                    <?php foreach ($assets as $a): ?>
                        <option value="<?= (int)$a['c0d']; ?>"><?= htmlspecialchars($a['asset_no']); ?> · <?= htmlspecialchars($a['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="font-size:.78rem;">Template</label>
                <select id="ai_tpl" class="form-select form-select-sm">
                    <option value="">— Pick —</option>
                    <?php foreach ($templates as $t): ?>
                        <option value="<?= (int)$t['c0d']; ?>"><?= htmlspecialchars($t['code']); ?> · <?= htmlspecialchars($t['title']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Cadence</label>
                <select id="ai_cad" class="form-select form-select-sm">
                    <option value="DAILY">Daily</option>
                    <option value="WEEKLY">Weekly</option>
                    <option value="FORTNIGHTLY">Fortnightly</option>
                    <option value="MONTHLY" selected>Monthly</option>
                    <option value="QUARTERLY">Quarterly</option>
                    <option value="HALFYEARLY">Half-yearly</option>
                    <option value="YEARLY">Yearly</option>
                    <option value="ON_DEMAND">On demand</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">First due</label>
                <input type="date" id="ai_start" class="form-control form-control-sm" value="<?= date('Y-m-d'); ?>">
            </div>
            <div class="col-md-1 text-end">
                <button type="button" class="btn btn-sm btn-primary" onclick="pmpAddItem()"><i class="fas fa-plus"></i></button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong>Plan items · <?= count($items); ?></strong>
        <?php if ($plan['status'] === 'ACTIVE' && !empty($items)): ?>
            <div class="d-flex align-items-center gap-2">
                <input type="number" id="pmp_horizon" min="1" max="365" value="30" class="form-control form-control-sm" style="width:90px;" title="Horizon (days)">
                <button type="button" class="btn btn-sm btn-warning" onclick="pmpGenerate()"><i class="fas fa-cog me-1"></i> Generate work orders</button>
            </div>
        <?php endif; ?>
    </div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Asset</th>
                    <th>Template</th>
                    <th>Cadence</th>
                    <th>Next due</th>
                    <th>Assignee (default)</th>
                    <th>Last generated</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $i): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars($i['asset_no']); ?></strong> · <?= htmlspecialchars($i['asset_name']); ?></td>
                        <td><?= htmlspecialchars($i['template_code']); ?> <span class="text-muted small">v<?= (int)$i['template_version']; ?></span><br><span class="text-muted small"><?= htmlspecialchars($i['template_title']); ?></span></td>
                        <td class="small" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$i['cadence']))); ?></td>
                        <td class="small"><?= htmlspecialchars($i['next_due'] ?? '—'); ?></td>
                        <td class="small text-muted"><?= htmlspecialchars($i['default_assignee_name'] ?: '(pool)'); ?></td>
                        <td class="small text-muted"><?= htmlspecialchars($i['last_generated_on'] ?? '—'); ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($items)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-4">No items yet. Add an asset × template mapping above.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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

<?php $this->start('section_js'); ?>
<script>
const PL_ID = <?= (int)$plan['c0d']; ?>;
function pmpAct(action) {
    if (action !== 'activate' && !confirm('Are you sure?')) return;
    $.post('<?= PROOT; ?>ServicePmPlans/' + action + 'Aj', { plan_id: PL_ID }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function pmpAddItem() {
    var payload = {
        plan_id:     PL_ID,
        asset_id:    $('#ai_asset').val(),
        template_id: $('#ai_tpl').val(),
        cadence:     $('#ai_cad').val(),
        start_date:  $('#ai_start').val(),
    };
    if (!payload.asset_id || !payload.template_id) { rsToast('Pick asset + template.', 'error'); return; }
    $.post('<?= PROOT; ?>ServicePmPlans/addItemAj', payload, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function pmpGenerate() {
    var horizon = parseInt($('#pmp_horizon').val() || 30, 10);
    $.post('<?= PROOT; ?>ServicePmPlans/generateAj', { plan_id: PL_ID, horizon_days: horizon }, 'json')
        .done(function (r) {
            if (r && r.ok) {
                rsToast(r.created + ' work order(s) generated.', 'success');
                setTimeout(function () { location.reload(); }, 800);
            } else rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
        });
}
</script>
<?php $this->end(); ?>
