<?php
$daysToDue = $schedule['next_due_at']
    ? (int) floor((strtotime((string) $schedule['next_due_at']) - strtotime(date('Y-m-d'))) / 86400)
    : null;
if ($daysToDue === null)            { $dueBadge = ['bg-secondary', 'no due date']; }
elseif ($daysToDue < 0)             { $dueBadge = ['bg-danger', 'overdue ' . abs($daysToDue) . ' days']; }
elseif ($daysToDue <= 30)           { $dueBadge = ['bg-warning text-dark', 'due in ' . $daysToDue . ' days']; }
else                                { $dueBadge = ['bg-success', 'ok · ' . $daysToDue . ' days']; }
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="fw-bold mb-0"><i class="fas fa-ruler-combined me-2 text-primary"></i><?= e($schedule['name']) ?></h5>
    <div class="d-flex gap-2">
        <?php if ($canManage): ?><a class="btn btn-sm btn-outline-primary" href="<?= url('/Calibration/edit/' . (int) $schedule['cal_schedule_id']) ?>"><i class="fas fa-pen me-1"></i>Edit</a><?php endif; ?>
        <a class="btn btn-sm btn-outline-secondary" href="<?= url('/Calibration') ?>"><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>Asset</dt><dd><a href="<?= url('/Assets/show/' . (int) $schedule['asset_id']) ?>"><?= e($schedule['asset_name']) ?></a></dd></div>
        <div class="col-md-3"><dt>Standard</dt><dd><?= e($schedule['standard'] ?? '—') ?></dd></div>
        <div class="col-md-3"><dt>Interval</dt><dd><?= (int) $schedule['interval_days'] ?> days</dd></div>
        <div class="col-md-3"><dt>Tolerance</dt><dd><?= e($schedule['tolerance'] ?? '—') ?> <?= e($schedule['unit'] ?? '') ?></dd></div>
        <div class="col-md-3"><dt>Last calibrated</dt><dd><?= e($schedule['last_calibrated_at'] ?? '—') ?></dd></div>
        <div class="col-md-3"><dt>Next due</dt><dd><?= e($schedule['next_due_at'] ?? '—') ?></dd></div>
        <div class="col-md-3"><dt>Status</dt><dd><span class="badge <?= $dueBadge[0] ?> text-uppercase"><?= e($dueBadge[1]) ?></span></dd></div>
        <div class="col-md-3"><dt>Active</dt><dd><span class="badge <?= $schedule['is_active'] ? 'bg-success' : 'bg-secondary' ?>"><?= $schedule['is_active'] ? 'active' : 'inactive' ?></span></dd></div>
        <?php if (!empty($schedule['notes'])): ?><div class="col-12"><dt>Notes</dt><dd><?= nl2br(e($schedule['notes'])) ?></dd></div><?php endif; ?>
    </dl>
</div>

<div class="rs-card p-3 mb-3">
    <h6 class="fw-bold mb-2"><i class="fas fa-clipboard-check me-1"></i>Log a calibration event</h6>
    <p class="text-muted small mb-2">Logging an event advances <em>Next due</em> by <?= (int) $schedule['interval_days'] ?> days from the performed date.</p>
    <form method="post" action="<?= url('/Calibration/record/' . (int) $schedule['cal_schedule_id']) ?>">
        <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
        <div class="row g-2">
            <div class="col-md-3"><label class="form-label">Performed at</label>
                <input type="datetime-local" class="form-control form-control-sm" name="performed_at" value="<?= e(date('Y-m-d\\TH:i')) ?>">
            </div>
            <div class="col-md-3"><label class="form-label">Technician</label>
                <input type="text" class="form-control form-control-sm" name="technician_name" placeholder="Name / external lab">
            </div>
            <div class="col-md-2"><label class="form-label">As found</label>
                <input type="text" class="form-control form-control-sm" name="as_found" placeholder="e.g. +0.3 bar">
            </div>
            <div class="col-md-2"><label class="form-label">As left</label>
                <input type="text" class="form-control form-control-sm" name="as_left" placeholder="e.g. ±0.05 bar">
            </div>
            <div class="col-md-2"><label class="form-label">Result</label>
                <select name="result" class="form-select form-select-sm">
                    <?php foreach (\App\Models\Calibration::RESULTS as $r): ?>
                        <option value="<?= $r ?>"><?= $r ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4"><label class="form-label">Certificate #</label>
                <input type="text" class="form-control form-control-sm" name="certificate_number">
            </div>
            <div class="col-md-8"><label class="form-label">Notes</label>
                <input type="text" class="form-control form-control-sm" name="notes">
            </div>
        </div>
        <div class="mt-3"><button type="submit" class="btn btn-sm btn-success"><i class="fas fa-check me-1"></i>Log calibration &amp; roll forward</button></div>
    </form>
</div>

<div class="rs-card p-3">
    <h6 class="fw-bold mb-2"><i class="fas fa-clock-rotate-left me-1"></i>History</h6>
    <?php if (empty($records)): ?>
        <p class="text-muted small mb-0">No calibration events logged yet.</p>
    <?php else: ?>
        <table class="table table-sm table-hover mb-0 align-middle">
            <thead><tr><th>Performed at</th><th>By</th><th>As found → left</th><th class="text-center">Result</th><th>Certificate</th><th>Notes</th></tr></thead>
            <tbody>
                <?php foreach ($records as $r):
                    $resBadge = ['pass' => 'bg-success', 'fail' => 'bg-danger', 'adjusted' => 'bg-warning text-dark'][$r['result']] ?? 'bg-secondary';
                ?>
                    <tr>
                        <td class="small"><?= e(substr((string) $r['performed_at'], 0, 16)) ?></td>
                        <td class="small"><?= e($r['performed_username'] ?? $r['technician_name'] ?? '—') ?></td>
                        <td class="small"><?= e($r['as_found'] ?? '—') ?> → <?= e($r['as_left'] ?? '—') ?></td>
                        <td class="text-center"><span class="badge <?= $resBadge ?> text-uppercase" style="font-size:.6rem;"><?= e($r['result']) ?></span></td>
                        <td class="small"><?= e($r['certificate_number'] ?? '—') ?></td>
                        <td class="small text-muted"><?= e($r['notes'] ?? '') ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
