<?php
$graphDate = $daily['date'] ?? date('Y-m-d');
$dayStart = strtotime((string)($daily['start_at'] ?? ($graphDate . ' 00:00:00')));
$rowY = ['off_duty'=>20,'sleeper_berth'=>55,'driving'=>90,'on_duty'=>125];
$pathParts = [];
$previousY = null;
foreach (($daily['segments'] ?? []) as $segment) {
    $startMinute = max(0, min(1440, (strtotime($segment['start']) - $dayStart) / 60));
    $endMinute = max(0, min(1440, (strtotime($segment['end']) - $dayStart) / 60));
    $x1 = 70 + (900 * ($startMinute / 1440));
    $x2 = 70 + (900 * ($endMinute / 1440));
    $y = $rowY[$segment['duty_status']] ?? 20;
    if ($previousY !== null && abs($previousY - $y) > .1) $pathParts[] = 'L ' . number_format($x1,2,'.','') . ' ' . $y;
    else $pathParts[] = ($pathParts ? 'L ' : 'M ') . number_format($x1,2,'.','') . ' ' . $y;
    $pathParts[] = 'L ' . number_format($x2,2,'.','') . ' ' . $y;
    $previousY = $y;
}
?>
<div class="hos-graph-wrap" role="img" aria-label="24 hour driver duty status graph for <?= e($graphDate) ?>">
<svg class="hos-graph" viewBox="0 0 990 160" preserveAspectRatio="none">
    <rect x="70" y="4" width="900" height="136" rx="10" fill="#fff" stroke="#dbe3ef"/>
    <?php foreach([20=>'Off Duty',55=>'Sleeper',90=>'Driving',125=>'On Duty'] as $y=>$label): ?>
        <text x="5" y="<?= $y+4 ?>" class="hos-graph-label"><?= e($label) ?></text>
        <line x1="70" y1="<?= $y ?>" x2="970" y2="<?= $y ?>" class="hos-grid-line"/>
    <?php endforeach; ?>
    <?php for($hour=0;$hour<=24;$hour++): $x=70+(900/24)*$hour; ?>
        <line x1="<?= $x ?>" y1="4" x2="<?= $x ?>" y2="140" class="hos-hour-line <?= $hour%6===0?'major':'' ?>"/>
        <?php if($hour<24 && $hour%2===0): ?><text x="<?= $x+2 ?>" y="155" class="hos-hour-label"><?= str_pad((string)$hour,2,'0',STR_PAD_LEFT) ?></text><?php endif; ?>
    <?php endfor; ?>
    <?php if($pathParts): ?><path d="<?= e(implode(' ', $pathParts)) ?>" class="hos-duty-path"/><?php endif; ?>
</svg>
</div>
