<?php
/** @var array $run          Round run row + operator_username + template_name */
/** @var array $tenant       Tenant row */
/** @var array $stops        Enriched stop rows from Round::runStopsFor */
/** @var array $photosByStop Map: run_stop_id => [ attachments ] */

$companyName = \Core\Settings::get('company_name') ?: APP_NAME;

// Rollup for the header summary
$doneCount    = 0;
$flaggedCount = 0;
foreach ($stops as $s) {
    if (!empty($s['checked_at'])) $doneCount++;
    if (!empty($s['checked_at']) && empty($s['is_ok'])) $flaggedCount++;
}
?>
<style>
    body { font-family: sans-serif; color: #1e2d3d; font-size: 10pt; }
    .brand { color: #0b2545; font-weight: 800; font-size: 16pt; }
    .sub   { color: #6b7a8d; font-size: 9pt; text-transform: uppercase; letter-spacing: 1.5px; }
    h1 { font-size: 18pt; margin: 8mm 0 2mm; color: #0b2545; }
    h2 { font-size: 12pt; margin: 6mm 0 2mm; color: #1a4d8c; border-bottom: 1px solid #d1d5db; padding-bottom: 1mm; }

    table.def { width: 100%; border-collapse: collapse; margin: 2mm 0 4mm; }
    table.def td { padding: 1mm 2mm; vertical-align: top; }
    table.def td.k { color: #6b7a8d; width: 20%; text-transform: uppercase; font-size: 8pt; letter-spacing: .5px; }
    table.def td.v { color: #1e2d3d; font-weight: 600; }

    /* Summary tiles */
    .tiles { width: 100%; margin-top: 2mm; }
    .tile  { background: #f7f9fc; padding: 3mm; border-radius: 3mm; text-align: center; }
    .tile .n { font-size: 16pt; font-weight: 800; color: #0b2545; }
    .tile .l { font-size: 8pt; color: #6b7a8d; text-transform: uppercase; letter-spacing: .5px; }

    /* Stops */
    .stop { border: 1px solid #e2e8f0; border-left: 4px solid #cbd5e1; border-radius: 2mm; padding: 3mm; margin-bottom: 3mm; page-break-inside: avoid; }
    .stop.ok      { border-left-color: #22c55e; }
    .stop.flagged { border-left-color: #ef4444; }
    .stop-head    { }
    .stop-title   { font-weight: 700; color: #0b2545; font-size: 11pt; }
    .stop-hint    { color: #6b7a8d; font-size: 9pt; margin-top: 1mm; }
    .stop-reading { margin-top: 2mm; font-size: 10pt; }
    .stop-reading strong { color: #0b2545; font-size: 12pt; }
    .stop-meta    { color: #6b7a8d; font-size: 8pt; margin-top: 1mm; }

    .pill { display: inline-block; padding: 0.5mm 2mm; border-radius: 3mm; font-size: 8pt; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: .5px; }
    .pill.ok   { background: #22c55e; }
    .pill.flag { background: #ef4444; }

    /* Photo strip inside a stop */
    .photos { margin-top: 3mm; }
    .ph     { display: inline-block; vertical-align: top; margin-right: 2mm; margin-bottom: 2mm; width: 40mm; }
    .ph img { width: 100%; height: 28mm; object-fit: cover; border-radius: 1mm; border: 1px solid #e2e8f0; }
    .ph .cap  { color: #1e2d3d; font-size: 8pt; font-weight: 600; margin-top: 1mm; }
    .ph .time { color: #6b7a8d; font-size: 7pt; }

    .sig-row { margin-top: 8mm; }
    .sig { border-top: 1px solid #1e2d3d; padding-top: 2mm; font-size: 8pt; color: #6b7a8d; display: inline-block; width: 45%; margin-right: 8%; }
    .foot { margin-top: 12mm; color: #94a3b8; font-size: 7pt; text-align: center; }
</style>

<div>
    <div class="brand"><?= e($companyName) ?></div>
    <div class="sub"><?= e($tenant['name'] ?? '') ?> · Operator Round Report</div>
</div>

<h1>Run #<?= (int) $run['run_id'] ?> · <?= e($run['template_name']) ?></h1>

<table class="def">
    <tr><td class="k">Operator</td>  <td class="v"><?= e($run['operator_username'] ?? '—') ?></td>
        <td class="k">Started</td>   <td class="v"><?= e($run['started_at'] ?? '—') ?></td></tr>
    <tr><td class="k">Status</td>    <td class="v"><?= e(strtoupper($run['status'])) ?></td>
        <td class="k">Finished</td>  <td class="v"><?= e($run['finished_at'] ?? '—') ?></td></tr>
    <?php if (!empty($run['notes'])): ?>
    <tr><td class="k">Notes</td>     <td class="v" colspan="3"><?= nl2br(e($run['notes'])) ?></td></tr>
    <?php endif; ?>
</table>

<h2>Summary</h2>
<table class="tiles"><tr>
    <td class="tile"><div class="n"><?= count($stops) ?></div><div class="l">Total stops</div></td>
    <td width="4mm"></td>
    <td class="tile"><div class="n"><?= $doneCount ?></div><div class="l">Completed</div></td>
    <td width="4mm"></td>
    <td class="tile"><div class="n" style="color:#ef4444;"><?= $flaggedCount ?></div><div class="l">Flagged</div></td>
    <td width="4mm"></td>
    <td class="tile"><div class="n"><?= count($stops) - $doneCount ?></div><div class="l">Not checked</div></td>
</tr></table>

<h2>Stops</h2>
<?php foreach ($stops as $s):
    $checked  = !empty($s['checked_at']);
    $isOk     = $checked && !empty($s['is_ok']);
    $cls      = $checked ? ($isOk ? 'ok' : 'flagged') : '';
    $ph       = $photosByStop[(int) $s['run_stop_id']] ?? [];
?>
    <div class="stop <?= $cls ?>">
        <div class="stop-head">
            <span class="stop-title">#<?= (int) $s['sort_order'] ?> · <?= e($s['asset_name']) ?></span>
            <?php if ($checked): ?>
                <span class="pill <?= $isOk ? 'ok' : 'flag' ?>"><?= $isOk ? 'OK' : 'FLAG' ?></span>
            <?php endif; ?>
        </div>
        <?php if (!empty($s['instruction'])): ?>
            <div class="stop-hint"><?= e($s['instruction']) ?></div>
        <?php endif; ?>
        <?php if (!empty($s['reading_key'])): ?>
            <div class="stop-hint">
                Expected <strong><?= e($s['reading_key']) ?></strong>
                <?php if ($s['min_ok'] !== null || $s['max_ok'] !== null): ?>
                    in range [<?= $s['min_ok'] ?? '−∞' ?>, <?= $s['max_ok'] ?? '+∞' ?>]
                <?php endif; ?>
                <?= e($s['reading_unit'] ?? '') ?>
            </div>
        <?php endif; ?>

        <?php if ($checked): ?>
            <div class="stop-reading">
                <?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; ?>
            </div>
            <?php if (!empty($s['note'])): ?>
                <div class="stop-meta"><strong>Note:</strong> <?= e($s['note']) ?></div>
            <?php endif; ?>
            <div class="stop-meta">Checked at <?= e($s['checked_at']) ?></div>
        <?php else: ?>
            <div class="stop-meta"><em>Not checked.</em></div>
        <?php endif; ?>

        <?php if (!empty($ph)): ?>
            <div class="photos">
                <?php foreach ($ph as $p):
                    $abs = \App\Models\Attachment::absolutePath($p['file_name']);
                    $isImg = in_array($p['file_ext'] ?? '', ['jpg','jpeg','png','gif','webp'], true) && is_file($abs);
                ?>
                    <div class="ph">
                        <?php if ($isImg): ?>
                            <img src="<?= e($abs) ?>" alt="">
                        <?php endif; ?>
                        <div class="cap"><?= e($p['caption'] ?? $p['original_name']) ?></div>
                        <div class="time"><?= e(substr((string) $p['created_at'], 0, 16)) ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
<?php endforeach; ?>

<div class="sig-row">
    <div class="sig">Operator signature &nbsp; · &nbsp; Date</div>
    <div class="sig">Supervisor signature &nbsp; · &nbsp; Date</div>
</div>

<div class="foot">
    Generated <?= date('Y-m-d H:i') ?> · <?= e($companyName) ?>
</div>
