<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="fw-bold mb-0"><i class="fas fa-calendar-check me-2 text-primary"></i><?= e($template['name']) ?></h5>
    <div class="d-flex gap-2">
        <a class="btn btn-sm btn-outline-primary" href="<?= url('/PmTemplates/edit/' . (int) $template['template_id']) ?>"><i class="fas fa-pen me-1"></i>Edit</a>
        <a class="btn btn-sm btn-outline-secondary" href="<?= url('/PmTemplates') ?>"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<?php if (!empty($flash)): ?><div class="alert alert-info py-2 small"><?= e($flash) ?></div><?php endif; ?>

<div class="rs-card p-3 mb-3">
    <dl class="rs-def row g-2 mb-0">
        <div class="col-md-3"><dt>Interval</dt><dd><?= (int) $template['interval_days'] ?> days</dd></div>
        <div class="col-md-3"><dt>Lead time</dt><dd><?= (int) $template['lead_days'] ?> days</dd></div>
        <div class="col-md-3"><dt>Priority</dt><dd><span class="badge bg-secondary text-uppercase"><?= e($template['priority']) ?></span></dd></div>
        <div class="col-md-3"><dt>Status</dt><dd><span class="badge <?= $template['is_active'] ? 'bg-success' : 'bg-secondary' ?> text-uppercase"><?= $template['is_active'] ? 'active' : 'inactive' ?></span></dd></div>
        <?php if (!empty($template['description'])): ?><div class="col-12"><dt>Description</dt><dd><?= nl2br(e($template['description'])) ?></dd></div><?php endif; ?>
    </dl>
</div>

<div class="rs-card p-3 mb-3">
    <h6 class="fw-bold mb-2">Tasks (will be created on every generated WO)</h6>
    <?php if (empty($tasks)): ?>
        <p class="text-muted small">No tasks defined yet.</p>
    <?php else: ?>
        <table class="table table-sm table-hover mb-3 align-middle">
            <thead><tr>
                <th style="width:14px;">#</th>
                <th>Title</th>
                <th>Type</th>
                <th>Options</th>
                <th class="text-center">Req</th>
                <th class="text-center">Photo</th>
                <th style="width:170px;" class="text-end">Actions</th>
            </tr></thead>
            <tbody>
                <?php
                $lastIdx = count($tasks) - 1;
                foreach ($tasks as $i => $t):
                    $opts = !empty($t['options_json']) ? (json_decode($t['options_json'], true) ?: []) : [];
                    $photoReq = $t['photo_requirement'] ?? 'n_a';
                    $photoBadge = [
                        'required' => ['bg-danger',    'Required'],
                        'optional' => ['bg-info',      'Optional'],
                        'n_a'      => ['bg-light text-muted border', 'N/A'],
                    ][$photoReq] ?? ['bg-light text-muted border', 'N/A'];
                ?>
                    <tr>
                        <td class="small text-muted"><?= (int) $t['sort_order'] ?></td>
                        <td>
                            <strong><?= e($t['title']) ?></strong>
                            <?php if (!empty($t['description'])): ?><div class="text-muted small"><?= nl2br(e($t['description'])) ?></div><?php endif; ?>
                        </td>
                        <td><span class="badge bg-secondary text-uppercase"><?= e($t['input_type'] ?? 'checkbox') ?></span></td>
                        <td class="small">
                            <?php if ($opts): ?>
                                <?php foreach ($opts as $o): ?><code class="small me-1"><?= e((string) $o) ?></code><?php endforeach; ?>
                            <?php else: ?>—<?php endif; ?>
                        </td>
                        <td class="text-center"><?= !empty($t['is_required']) ? '<i class="fas fa-check text-danger"></i>' : '' ?></td>
                        <td class="text-center"><span class="badge <?= $photoBadge[0] ?> text-uppercase" style="font-size:.6rem;"><?= e($photoBadge[1]) ?></span></td>
                        <td class="text-end">
                            <div class="btn-group btn-group-sm" role="group">
                                <a class="btn btn-outline-secondary <?= $i === 0 ? 'disabled' : '' ?>" title="Move up"
                                   href="<?= $i === 0 ? '#' : url('/PmTemplates/moveTask/' . (int) $t['template_task_id'] . '/up') ?>">
                                    <i class="fas fa-arrow-up"></i>
                                </a>
                                <a class="btn btn-outline-secondary <?= $i === $lastIdx ? 'disabled' : '' ?>" title="Move down"
                                   href="<?= $i === $lastIdx ? '#' : url('/PmTemplates/moveTask/' . (int) $t['template_task_id'] . '/down') ?>">
                                    <i class="fas fa-arrow-down"></i>
                                </a>
                                <a class="btn btn-outline-primary" title="Edit"
                                   href="<?= url('/PmTemplates/editTask/' . (int) $t['template_task_id']) ?>">
                                    <i class="fas fa-pen"></i>
                                </a>
                            </div>
                            <form method="post" action="<?= url('/PmTemplates/deleteTask/' . (int) $t['template_task_id']) ?>"
                                  class="d-inline rs-confirm-submit ms-1"
                                  data-confirm-title="Delete task?"
                                  data-confirm-body="Delete <strong><?= e($t['title']) ?></strong> from this template? Existing work-order tasks are not affected."
                                  data-confirm-ok="Delete">
                                <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
                                <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete"><i class="fas fa-times"></i></button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <form method="post" action="<?= url('/PmTemplates/addTask/' . (int) $template['template_id']) ?>" class="mt-2">
        <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
        <div class="row g-2">
            <div class="col-md-4"><label class="form-label">Title *</label><input type="text" class="form-control form-control-sm" name="title" required placeholder="e.g. Check oil level"></div>
            <div class="col-md-2"><label class="form-label">Input type</label>
                <select name="input_type" class="form-select form-select-sm">
                    <option value="checkbox">checkbox</option>
                    <option value="options">options (dropdown)</option>
                    <option value="number">number</option>
                    <option value="text">text</option>
                    <option value="photo">photo</option>
                </select>
            </div>
            <div class="col-md-3"><label class="form-label">Options (comma-separated, for OPTIONS type)</label><input type="text" class="form-control form-control-sm" name="options_json" placeholder="OK,HIGH,LOW"></div>
            <div class="col-md-2"><label class="form-label">Photo</label>
                <select name="photo_requirement" class="form-select form-select-sm">
                    <option value="n_a">N / A</option>
                    <option value="optional">Optional</option>
                    <option value="required">Required</option>
                </select>
            </div>
            <div class="col-md-1"><label class="form-label">Order</label><input type="number" class="form-control form-control-sm" name="sort_order" value="0"></div>
            <div class="col-md-2 d-flex align-items-end pt-3"><div class="form-check"><input type="checkbox" class="form-check-input" name="is_required" value="1" id="pmReq"><label for="pmReq" class="form-check-label small">Required</label></div></div>
            <div class="col-md-8"><label class="form-label">Description (optional)</label><input type="text" class="form-control form-control-sm" name="description"></div>
            <div class="col-md-2 d-flex align-items-end"><button type="submit" class="btn btn-sm btn-primary w-100"><i class="fas fa-plus me-1"></i>Add task</button></div>
        </div>
    </form>
</div>

<div class="rs-card p-3">
    <h6 class="fw-bold mb-2">Schedules (per-asset)</h6>
    <p class="text-muted small">Each schedule generates a WO for its asset — either when <code>next_due_at</code> is within the lead time (<em>calendar</em>) or when the latest reading crosses <em>last_meter_reading + meter_interval</em> (<em>meter-based</em>).</p>
    <?php if (empty($schedules)): ?>
        <p class="text-muted small">No schedules attached yet.</p>
    <?php else: ?>
        <table class="table table-sm table-hover mb-3 align-middle">
            <thead><tr><th>Asset</th><th>Trigger</th><th>Assigned</th><th>Next due / meter</th><th>Last generated</th><th>Status</th><th></th></tr></thead>
            <tbody>
                <?php foreach ($schedules as $s):
                    $trig    = $s['trigger_type'] ?? 'calendar';
                    $trigLbl = ['calendar' => 'CAL', 'running_hours' => 'HRS', 'reading_value' => 'READ'][$trig] ?? strtoupper($trig);
                    $trigCls = ['calendar' => 'bg-info text-dark', 'running_hours' => 'bg-warning text-dark', 'reading_value' => 'bg-primary'][$trig] ?? 'bg-secondary';
                ?>
                    <tr>
                        <td><?= e($s['asset_name']) ?></td>
                        <td><span class="badge <?= $trigCls ?>" style="font-size:.6rem;"><?= $trigLbl ?></span></td>
                        <td class="small text-muted"><?= e($s['assigned_username'] ?? '—') ?></td>
                        <td class="small">
                            <?php if ($trig === 'calendar'): ?>
                                <?= e($s['next_due_at'] ?? '—') ?>
                            <?php else: ?>
                                Every <strong><?= e(rtrim(rtrim(number_format((float) ($s['meter_interval'] ?? 0), 3), '0'), '.')) ?></strong>
                                of <code><?= e($s['meter_key'] ?? '—') ?></code>
                                <div class="small text-muted">last @ <?= $s['last_meter_reading'] !== null ? e($s['last_meter_reading']) : '—' ?></div>
                            <?php endif; ?>
                        </td>
                        <td class="small text-muted"><?= e($s['last_generated_at'] ?? '—') ?></td>
                        <td><span class="badge <?= $s['is_active'] ? 'bg-success' : 'bg-secondary' ?> text-uppercase"><?= $s['is_active'] ? 'active' : 'inactive' ?></span></td>
                        <td class="text-end">
                            <form method="post" action="<?= url('/PmTemplates/deleteSchedule/' . (int) $s['schedule_id']) ?>"
                                  class="d-inline rs-confirm-submit"
                                  data-confirm-title="Remove schedule?"
                                  data-confirm-body="Stop auto-generating WOs for <strong><?= e($s['asset_name']) ?></strong> on this template?"
                                  data-confirm-ok="Remove">
                                <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
                                <button type="submit" class="btn btn-sm btn-link text-danger p-0"><i class="fas fa-times"></i></button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <form method="post" action="<?= url('/PmTemplates/addSchedule/' . (int) $template['template_id']) ?>" id="schedForm">
        <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
        <div class="row g-2 align-items-end">
            <div class="col-md-3"><label class="form-label">Asset *</label>
                <select name="asset_id" class="form-select form-select-sm" required>
                    <option value="">— pick asset —</option>
                    <?php foreach ($assets as $a): ?><option value="<?= (int) $a['asset_id'] ?>"><?= e($a['name']) ?></option><?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3"><label class="form-label">Trigger</label>
                <select name="trigger_type" class="form-select form-select-sm" id="trigSel" onchange="document.getElementById('schedForm').classList.toggle('trig-meter', this.value !== 'calendar')">
                    <?php foreach (\App\Models\PmTemplate::TRIGGER_TYPES as $val => $lbl): ?>
                        <option value="<?= e($val) ?>"><?= e($lbl) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2"><label class="form-label">Assign to</label>
                <select name="assigned_to" class="form-select form-select-sm">
                    <option value="">— unassigned —</option>
                    <?php foreach ($users as $u): ?><option value="<?= (int) $u['user_id'] ?>"><?= e($u['username']) ?></option><?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 trig-cal"><label class="form-label">Next due (calendar)</label><input type="datetime-local" class="form-control form-control-sm" name="next_due_at"></div>
            <div class="col-md-1 trig-cal"><button type="submit" class="btn btn-sm btn-primary w-100"><i class="fas fa-plus me-1"></i>Add</button></div>

            <!-- Meter fields — hidden by default, revealed when trigger != calendar -->
            <div class="col-md-2 trig-meter d-none"><label class="form-label">Meter key</label>
                <input type="text" class="form-control form-control-sm" name="meter_key" placeholder="running_hours">
            </div>
            <div class="col-md-2 trig-meter d-none"><label class="form-label">Interval</label>
                <input type="number" step="0.001" class="form-control form-control-sm" name="meter_interval" placeholder="250">
            </div>
            <div class="col-md-2 trig-meter d-none"><label class="form-label">Current reading</label>
                <input type="number" step="0.001" class="form-control form-control-sm" name="last_meter_reading" placeholder="0">
            </div>
            <div class="col-md-1 trig-meter d-none"><button type="submit" class="btn btn-sm btn-primary w-100"><i class="fas fa-plus me-1"></i>Add</button></div>
        </div>
    </form>
</div>

<style>
    /* Swap the visible field group based on trigger selector — no page reload. */
    #schedForm:not(.trig-meter) .trig-meter { display: none !important; }
    #schedForm.trig-meter .trig-cal { display: none !important; }
    #schedForm.trig-meter .trig-meter { display: block !important; }
</style>
