<?php
$done       = array_filter($stops, fn($s) => $s['checked_at'] !== null);
$flagged    = array_filter($done, fn($s) => (int) $s['is_ok'] === 0);
$pending    = array_filter($stops, fn($s) => $s['checked_at'] === null);
$isActive   = $run['status'] === 'in_progress';
$badge      = ['in_progress' => 'bg-primary', 'completed' => 'bg-success', 'abandoned' => 'bg-secondary'][$run['status']] ?? 'bg-secondary';

// Total photo count across all stops — drives whether we show the ZIP button.
$totalPhotos = 0;
foreach (($photosByStop ?? []) as $arr) { $totalPhotos += count($arr); }
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="fw-bold mb-0"><i class="fas fa-route me-2 text-primary"></i>Run #<?= (int) $run['run_id'] ?> · <?= e($run['template_name']) ?></h5>
    <div class="d-flex gap-2">
        <a class="btn btn-sm btn-outline-secondary" href="<?= url('/Rounds/pdf/' . (int) $run['run_id']) ?>" target="_blank" title="Audit-ready report with readings + photos">
            <i class="fas fa-file-pdf me-1"></i>PDF report
        </a>
        <?php if ($totalPhotos > 0): ?>
            <a class="btn btn-sm btn-outline-secondary" href="<?= url('/Rounds/photosZip/' . (int) $run['run_id']) ?>" title="All <?= $totalPhotos ?> photo(s) as ZIP">
                <i class="fas fa-file-zipper me-1"></i>Photos.zip
            </a>
        <?php endif; ?>
        <a href="<?= url('/Rounds') ?>" class="btn btn-sm btn-outline-secondary"><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">
    <div class="row g-2">
        <div class="col-md-3"><span class="text-muted small">Operator</span><div><?= e($run['operator_username'] ?? '—') ?></div></div>
        <div class="col-md-3"><span class="text-muted small">Started</span><div><?= e($run['started_at']) ?></div></div>
        <div class="col-md-3"><span class="text-muted small">Progress</span><div><?= count($done) ?> / <?= count($stops) ?></div></div>
        <div class="col-md-3"><span class="text-muted small">Status</span><div><span class="badge <?= $badge ?> text-uppercase"><?= e($run['status']) ?></span></div></div>
    </div>
    <?php if (count($flagged) > 0): ?>
        <div class="alert alert-danger py-2 small mt-2 mb-0">
            <i class="fas fa-triangle-exclamation me-1"></i>
            <?= count($flagged) ?> stop<?= count($flagged) === 1 ? '' : 's' ?> flagged — review before completing.
        </div>
    <?php endif; ?>
</div>

<?php foreach ($stops as $s):
    $isChecked = $s['checked_at'] !== null;
    $rowClass  = $isChecked ? ((int) $s['is_ok'] ? 'border-success' : 'border-danger') : '';
    $stopPhotos = $photosByStop[(int) $s['run_stop_id']] ?? [];
?>
    <div class="rs-card p-3 mb-2 <?= $rowClass ?>">
        <div class="d-flex justify-content-between align-items-start mb-2">
            <div>
                <strong>#<?= (int) $s['sort_order'] ?> · <?= e($s['asset_name']) ?></strong>
                <?php if (!empty($s['instruction'])): ?><div class="small text-muted"><?= e($s['instruction']) ?></div><?php endif; ?>
                <?php if (!empty($s['reading_key'])): ?>
                    <div class="small text-muted">
                        Expected <strong><?= e($s['reading_key']) ?></strong>
                        <?php if ($s['min_ok'] !== null || $s['max_ok'] !== null): ?>
                            in range [<?= $s['min_ok'] !== null ? e($s['min_ok']) : '−∞' ?>, <?= $s['max_ok'] !== null ? e($s['max_ok']) : '+∞' ?>]
                        <?php endif; ?>
                        <?= e($s['reading_unit'] ?? '') ?>
                    </div>
                <?php endif; ?>
            </div>
            <div class="d-flex align-items-center gap-2">
                <?php if (count($stopPhotos) > 0): ?>
                    <span class="badge bg-light text-muted border" title="<?= count($stopPhotos) ?> photo(s) attached">
                        <i class="fas fa-camera me-1"></i><?= count($stopPhotos) ?>
                    </span>
                <?php endif; ?>
                <?php if ($isChecked): ?>
                    <span class="badge <?= (int) $s['is_ok'] ? 'bg-success' : 'bg-danger' ?>">
                        <?= (int) $s['is_ok'] ? 'OK' : 'FLAG' ?>
                    </span>
                <?php endif; ?>
            </div>
        </div>

        <?php if (!empty($stopPhotos)): ?>
            <div class="rs-photo-strip">
                <?php foreach ($stopPhotos as $p):
                    $isImg = in_array($p['file_ext'] ?? '', ['jpg','jpeg','png','gif','webp'], true);
                ?>
                    <a class="rs-photo-thumb" target="_blank"
                       href="<?= url('/Attachments/download/' . (int) $p['attachment_id']) ?>"
                       title="<?= e($p['caption'] ?? $p['original_name']) ?>">
                        <?php if ($isImg): ?>
                            <img src="<?= url('/Attachments/download/' . (int) $p['attachment_id']) ?>" alt="">
                        <?php else: ?>
                            <div class="rs-photo-file"><i class="fas fa-file"></i></div>
                        <?php endif; ?>
                        <div class="rs-photo-meta">
                            <div class="rs-photo-caption"><?= e($p['caption'] ?? $p['original_name']) ?></div>
                            <div class="rs-photo-time"><?= e(substr((string) $p['created_at'], 0, 16)) ?></div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($isChecked): ?>
            <div class="small">
                <?php if ($s['reading_value'] !== null): ?>
                    <strong><?= e($s['reading_value']) ?></strong> <?= e($s['reading_unit'] ?? '') ?>
                <?php endif; ?>
                <?php if (!empty($s['reading_text'])): ?> · <em><?= e($s['reading_text']) ?></em><?php endif; ?>
                <?php if (!empty($s['note'])): ?><div class="text-muted">Note: <?= e($s['note']) ?></div><?php endif; ?>
                <div class="text-muted small">Checked at <?= e($s['checked_at']) ?></div>
            </div>
        <?php elseif ($isActive): ?>
            <form method="post" action="<?= url('/Rounds/checkStop/' . (int) $s['run_stop_id']) ?>" class="row g-2 mt-1">
                <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
                <div class="col-md-3">
                    <input type="number" step="any" class="form-control form-control-sm" name="reading_value" placeholder="Reading value (numeric)">
                </div>
                <div class="col-md-3">
                    <input type="text" class="form-control form-control-sm" name="reading_text" placeholder="Or descriptive (OK / Leak / …)">
                </div>
                <div class="col-md-4">
                    <input type="text" class="form-control form-control-sm" name="note" placeholder="Note (optional)">
                </div>
                <div class="col-md-1 d-flex align-items-end">
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="is_ok" value="1" checked id="ok<?= (int) $s['run_stop_id'] ?>">
                        <label for="ok<?= (int) $s['run_stop_id'] ?>" class="form-check-label small">OK</label>
                    </div>
                </div>
                <div class="col-md-1 d-flex align-items-end">
                    <button type="submit" class="btn btn-sm btn-success w-100"><i class="fas fa-check"></i></button>
                </div>
            </form>
        <?php endif; ?>
    </div>
<?php endforeach; ?>

<?php if ($isActive): ?>
    <div class="rs-card p-3 mt-3">
        <div class="row g-2 align-items-end">
            <div class="col-md-6">
                <form method="post" action="<?= url('/Rounds/complete/' . (int) $run['run_id']) ?>" class="d-flex gap-2">
                    <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
                    <input type="text" class="form-control form-control-sm" name="notes" placeholder="Wrap-up notes (optional)">
                    <button type="submit" class="btn btn-sm btn-success"><i class="fas fa-flag-checkered me-1"></i>Complete Round</button>
                </form>
            </div>
            <div class="col-md-6 text-md-end">
                <form method="post" action="<?= url('/Rounds/abandon/' . (int) $run['run_id']) ?>"
                      class="d-inline rs-confirm-submit"
                      data-confirm-title="Abandon this round?"
                      data-confirm-body="Data collected so far will be kept, but the round will be marked as abandoned."
                      data-confirm-ok="Abandon">
                    <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
                    <button type="submit" class="btn btn-sm btn-outline-secondary"><i class="fas fa-times me-1"></i>Abandon</button>
                </form>
            </div>
        </div>
    </div>
<?php endif; ?>
