<?php
$log = $daily['log'];
$isManager = can('hos.manage');
$exceptions = json_decode((string)($log['exceptions'] ?? ''), true) ?: [];
$returnQuery = $isOwnDriver ? '' : '?driver_id='.(int)$driverId;
?>
<div class="page-heading hos-log-heading">
    <div><p class="eyebrow">Driver Logbook</p><h1><?= e($profile['driver_name']) ?></h1><p><?= e(hos_rule_label((string)$clocks['rule_set'])) ?> · <?= e($clocks['cycle_label']) ?> · Terminal time <?= e($profile['home_terminal_timezone']) ?></p></div>
    <div class="page-actions">
        <?php if(!$isOwnDriver): ?><a class="btn btn-light" href="<?= url('/hos') ?>">All Drivers</a><?php endif; ?>
        <?php if($isManager): ?><a class="btn btn-light" href="<?= url('/hos/profile?driver_id='.(int)$driverId) ?>">HOS Profile</a><?php endif; ?>
        <a class="btn btn-light" href="<?= url('/hos/inspection'.($isOwnDriver?'':'?driver_id='.(int)$driverId)) ?>">Inspection View</a>
        <a class="btn btn-primary" href="<?= url('/hos/pdf?driver_id='.(int)$driverId.'&date='.urlencode($date)) ?>">Daily PDF</a>
    </div>
</div>

<div class="notice notice-warning hos-compliance-notice"><strong>Operational logbook:</strong> These clocks are calculated from FleetLume duty events. Use a registered/certified ELD when required and verify exceptions, sleeper splits, deferrals, and special operations with your safety team.</div>

<?php if($clocks['violations']): ?><div class="hos-violation-banner"><strong>HOS warning</strong><div><?php foreach($clocks['violations'] as $warning): ?><span><?= e($warning) ?></span><?php endforeach; ?></div></div><?php endif; ?>

<div class="hos-clock-grid">
    <article class="hos-clock-card <?= $clocks['drive_remaining']<=60?'danger':($clocks['drive_remaining']<=120?'warning':'') ?>"><span>Driving</span><strong><?= hos_minutes($clocks['drive_remaining']) ?></strong><small><?= hos_minutes($clocks['drive_used']) ?> used of <?= hos_minutes($clocks['drive_limit']) ?></small><div class="hos-clock-progress"><i style="width:<?= min(100,($clocks['drive_used']/max(1,$clocks['drive_limit']))*100) ?>%"></i></div></article>
    <article class="hos-clock-card <?= $clocks['shift_remaining']<=60?'danger':($clocks['shift_remaining']<=120?'warning':'') ?>"><span><?= str_starts_with($clocks['rule_set'],'canada')?'On-Duty Limit':'14-Hour Window' ?></span><strong><?= hos_minutes($clocks['shift_remaining']) ?></strong><small><?= hos_minutes($clocks['shift_used']) ?> used of <?= hos_minutes($clocks['shift_limit']) ?></small><div class="hos-clock-progress"><i style="width:<?= min(100,($clocks['shift_used']/max(1,$clocks['shift_limit']))*100) ?>%"></i></div></article>
    <?php if($clocks['rule_set']==='us_property'): ?><article class="hos-clock-card <?= $clocks['break_remaining']<=30?'warning':'' ?>"><span>Break Clock</span><strong><?= hos_minutes($clocks['break_remaining']) ?></strong><small>Driving time before break requirement</small><div class="hos-clock-progress"><i style="width:<?= min(100,($clocks['break_used']/max(1,$clocks['break_limit']))*100) ?>%"></i></div></article><?php else: ?><article class="hos-clock-card <?= $clocks['daily_off_remaining']>0?'warning':'' ?>"><span>Daily Off-Duty Needed</span><strong><?= hos_minutes($clocks['daily_off_remaining']) ?></strong><small>Target includes qualifying off-duty and sleeper time</small><div class="hos-clock-progress"><i style="width:<?= min(100,((600-$clocks['daily_off_remaining'])/600)*100) ?>%"></i></div></article><?php endif; ?>
    <article class="hos-clock-card <?= $clocks['cycle_remaining']<=180?'danger':($clocks['cycle_remaining']<=300?'warning':'') ?>"><span>Cycle</span><strong><?= hos_minutes($clocks['cycle_remaining']) ?></strong><small><?= hos_minutes($clocks['cycle_used']) ?> used · <?= e($clocks['cycle_label']) ?></small><div class="hos-clock-progress"><i style="width:<?= min(100,($clocks['cycle_used']/max(1,$clocks['cycle_limit']))*100) ?>%"></i></div></article>
</div>

<div class="hos-main-grid">
<section class="panel hos-status-panel">
    <div class="panel-header"><div><h2>Current Duty Status</h2><p>Last change: <?= e($current ? datetime_display($current['event_at']) : 'No status recorded') ?></p></div><span class="hos-duty-pill duty-<?= e($clocks['current_status']) ?>"><?= e(hos_status_label((string)$clocks['current_status'],(string)($clocks['special_status']??''))) ?></span></div>
    <form method="post" action="<?= url('/hos/events/store') ?>" class="form-stack hos-status-form" data-hos-location-form>
        <?= csrf_field() ?><input type="hidden" name="driver_id" value="<?= (int)$driverId ?>"><input type="hidden" name="log_date" value="<?= e($date) ?>"><input type="hidden" name="latitude" data-hos-latitude><input type="hidden" name="longitude" data-hos-longitude>
        <div class="hos-status-buttons">
            <button class="hos-status-button off" name="duty_status" value="off_duty"><b>OFF</b><span>Off Duty</span></button>
            <button class="hos-status-button sleeper" name="duty_status" value="sleeper_berth"><b>SB</b><span>Sleeper Berth</span></button>
            <button class="hos-status-button driving" name="duty_status" value="driving"><b>D</b><span>Driving</span></button>
            <button class="hos-status-button on" name="duty_status" value="on_duty"><b>ON</b><span>On Duty</span></button>
        </div>
        <div class="form-grid two">
            <label><span>Rule Set at This Location</span><select name="rule_set"><option value="us_property" <?= $clocks['rule_set']==='us_property'?'selected':'' ?>>US Property-Carrying</option><option value="canada_south" <?= $clocks['rule_set']==='canada_south'?'selected':'' ?>>Canada South of 60°N</option><option value="canada_north" <?= $clocks['rule_set']==='canada_north'?'selected':'' ?>>Canada North of 60°N</option></select></label>
            <label><span>Event Time</span><input type="datetime-local" name="event_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
            <label><span>Load / Equipment</span><select name="load_id"><option value="">Current assigned equipment</option><?php foreach($assignments as $assignment): ?><option value="<?= (int)$assignment['id'] ?>"><?= e($assignment['load_number']) ?><?= $assignment['unit_number']?' · '.e($assignment['unit_number']):'' ?><?= $assignment['trailer_number']?' / '.e($assignment['trailer_number']):'' ?></option><?php endforeach; ?></select></label>
            <label><span>Location</span><div class="input-action"><input name="location_address" data-hos-location-address placeholder="City, state/province"><button class="btn btn-light btn-sm" type="button" data-hos-capture-location>Use GPS</button></div></label>
            <label><span>Odometer</span><input type="number" min="0" name="odometer"></label>
            <label><span>Engine Hours</span><input type="number" step="0.1" min="0" name="engine_hours"></label>
        </div>
        <label><span>Annotation</span><input name="annotation" placeholder="Fueling, loading, inspection, border queue, rest location…"></label>
        <div class="hos-special-actions">
            <?php if(!empty($profile['personal_conveyance_allowed'])): ?><button class="btn btn-light" name="special_status" value="personal_conveyance">Start Personal Conveyance</button><?php endif; ?>
            <?php if(!empty($profile['yard_move_allowed'])): ?><button class="btn btn-light" name="special_status" value="yard_move">Start Yard Move</button><?php endif; ?>
        </div>
    </form>
</section>

<section class="panel hos-day-panel">
    <div class="panel-header"><div><h2>Daily Log</h2><p><?= e(date('l, F j, Y', strtotime($date))) ?></p></div><form method="get" class="hos-date-filter"><?php if(!$isOwnDriver): ?><input type="hidden" name="driver_id" value="<?= (int)$driverId ?>"><?php endif; ?><input type="date" name="date" value="<?= e($date) ?>" onchange="this.form.submit()"></form></div>
    <?php require app_path('Views/hos/_graph.php'); ?>
    <div class="hos-total-row"><div><span>Off Duty</span><strong><?= hos_minutes($daily['totals']['off_duty']) ?></strong></div><div><span>Sleeper</span><strong><?= hos_minutes($daily['totals']['sleeper_berth']) ?></strong></div><div><span>Driving</span><strong><?= hos_minutes($daily['totals']['driving']) ?></strong></div><div><span>On Duty</span><strong><?= hos_minutes($daily['totals']['on_duty']) ?></strong></div></div>
    <div class="hos-cert-status"><span>Certification</span><strong class="badge badge-<?= status_class((string)$log['status']) ?>"><?= e(readable_status((string)$log['status'])) ?></strong><?php if(!empty($log['certified_at'])): ?><small><?= e(datetime_display($log['certified_at'])) ?> by <?= e($log['certification_name'] ?: 'Driver') ?></small><?php endif; ?></div>
</section>
</div>

<div class="content-grid hos-detail-grid">
<section class="panel">
    <div class="panel-header"><div><h2>Daily Details & Declarations</h2><p>Vehicle, shipment references, exceptions, and notes for this record.</p></div></div>
    <form method="post" action="<?= url('/hos/log/update') ?>" class="form-stack"><?= csrf_field() ?><input type="hidden" name="driver_id" value="<?= (int)$driverId ?>"><input type="hidden" name="log_date" value="<?= e($date) ?>">
        <div class="form-grid two"><label><span>Rule Set</span><select name="rule_set"><option value="us_property" <?= $log['rule_set']==='us_property'?'selected':'' ?>>US Property-Carrying</option><option value="canada_south" <?= $log['rule_set']==='canada_south'?'selected':'' ?>>Canada South of 60°N</option><option value="canada_north" <?= $log['rule_set']==='canada_north'?'selected':'' ?>>Canada North of 60°N</option></select></label><label><span>Vehicle Number(s)</span><input name="vehicle_numbers" value="<?= e($log['vehicle_numbers']) ?>"></label><label><span>Trailer Number(s)</span><input name="trailer_numbers" value="<?= e($log['trailer_numbers']) ?>"></label><label><span>Shipping Document / Load IDs</span><input name="shipping_documents" value="<?= e($log['shipping_documents']) ?>"></label><label><span>Start Odometer</span><input type="number" name="start_odometer" value="<?= e((string)$log['start_odometer']) ?>"></label><label><span>End Odometer</span><input type="number" name="end_odometer" value="<?= e((string)$log['end_odometer']) ?>"></label></div>
        <div><span class="field-title">Exceptions / Declarations</span><div class="permission-grid hos-option-grid"><?php foreach(['adverse_driving'=>'Adverse Driving Conditions','short_haul'=>'Short-Haul Exception','split_sleeper'=>'Sleeper Berth Split','off_duty_deferral_day1'=>'Canada Off-Duty Deferral · Day 1','off_duty_deferral_day2'=>'Canada Off-Duty Deferral · Day 2','ferry'=>'Ferry Provision','oilfield_waiting'=>'Oilfield Waiting Time','emergency'=>'Emergency Conditions'] as $key=>$label): ?><label class="permission-option"><input type="checkbox" name="<?= e($key) ?>" value="1" <?= in_array($key,$exceptions,true)?'checked':'' ?>><span><?= e($label) ?></span></label><?php endforeach; ?></div></div>
        <label><span>Daily Notes</span><textarea name="notes" rows="3"><?= e($log['notes']) ?></textarea></label>
        <div class="form-actions"><button class="btn btn-primary">Save Daily Details</button></div>
    </form>
    <?php if($isOwnDriver): ?><div class="hos-certify-box"><h3>Driver Certification</h3><p>I certify that this record is true and correct. Any later correction will require recertification.</p><form method="post" action="<?= url('/hos/certify') ?>" class="inline-form"><?= csrf_field() ?><input type="hidden" name="driver_id" value="<?= (int)$driverId ?>"><input type="hidden" name="log_date" value="<?= e($date) ?>"><input name="certification_name" value="<?= e($profile['driver_name']) ?>" required><button class="btn btn-primary">Certify <?= e($date) ?></button></form></div><?php endif; ?>
</section>

<section class="panel">
    <div class="panel-header"><div><h2>Duty Events</h2><p>Events remain auditable. Corrections are submitted for review rather than overwriting the original.</p></div></div>
    <div class="hos-event-list">
        <?php foreach($events as $event): ?>
        <article class="hos-event-card"><div class="hos-event-time"><strong><?= e(date('H:i',strtotime($event['event_at']))) ?></strong><span><?= e(date('M j',strtotime($event['event_at']))) ?></span></div><div class="hos-event-body"><div><strong><?= e(hos_status_label($event['duty_status'],$event['special_status'])) ?></strong><span><?= e($event['location_address'] ?: 'Location not entered') ?></span></div><p><?= e($event['annotation'] ?: ($event['load_number']?'Load '.$event['load_number']:'No annotation')) ?></p><small><?= e(readable_status($event['origin'])) ?> entry<?= $event['unit_number']?' · Unit '.e($event['unit_number']):'' ?></small>
            <?php if($isOwnDriver || $isManager): ?><details class="hos-edit-details"><summary>Request correction</summary><form method="post" action="<?= url('/hos/events/edit-request') ?>" class="form-stack"><?= csrf_field() ?><input type="hidden" name="driver_id" value="<?= (int)$driverId ?>"><input type="hidden" name="event_id" value="<?= (int)$event['id'] ?>"><div class="form-grid two"><label><span>Correct Time</span><input type="datetime-local" name="proposed_event_at" value="<?= e(date('Y-m-d\TH:i',strtotime($event['event_at']))) ?>"></label><label><span>Correct Status</span><select name="proposed_duty_status"><?php foreach(['off_duty','sleeper_berth','driving','on_duty'] as $status): ?><option value="<?= e($status) ?>" <?= $event['duty_status']===$status?'selected':'' ?>><?= e(hos_status_label($status)) ?></option><?php endforeach; ?></select></label><label><span>Special Status</span><select name="proposed_special_status"><option value="">None</option><option value="personal_conveyance" <?= $event['special_status']==='personal_conveyance'?'selected':'' ?>>Personal Conveyance</option><option value="yard_move" <?= $event['special_status']==='yard_move'?'selected':'' ?>>Yard Move</option></select></label><label><span>Correct Location</span><input name="proposed_location_address" value="<?= e($event['location_address']) ?>"></label></div><label><span>Correct Annotation</span><input name="proposed_annotation" value="<?= e($event['annotation']) ?>"></label><label><span>Reason for Correction *</span><textarea name="reason" rows="2" required></textarea></label><button class="btn btn-light btn-sm">Submit Edit Request</button></form></details><?php endif; ?>
        </div></article>
        <?php endforeach; ?>
        <?php if(!$events): ?><p class="empty">No duty status changes recorded for this date.</p><?php endif; ?>
    </div>
</section>
</div>

<?php if($pendingEdits): ?><section class="panel"><div class="panel-header"><div><h2>Pending Corrections</h2><p>These requests are awaiting a safety or dispatcher review.</p></div></div><div class="hos-edit-list"><?php foreach($pendingEdits as $request): ?><article class="hos-edit-card"><div><strong><?= e(hos_status_label($request['original_duty_status'],$request['original_special_status'])) ?> → <?= e(hos_status_label($request['proposed_duty_status'],$request['proposed_special_status'])) ?></strong><span><?= e(datetime_display($request['original_event_at'])) ?> → <?= e(datetime_display($request['proposed_event_at'])) ?></span><p><?= e($request['reason']) ?></p></div><?php if($isManager): ?><form method="post" action="<?= url('/hos/edits/review') ?>" class="hos-review-form"><?= csrf_field() ?><input type="hidden" name="request_id" value="<?= (int)$request['id'] ?>"><button class="btn btn-primary btn-sm" name="decision" value="approved">Approve</button><button class="btn btn-light btn-sm" name="decision" value="rejected">Reject</button></form><?php endif; ?></article><?php endforeach; ?></div></section><?php endif; ?>

<section class="panel">
<div class="panel-header"><div><h2>Recent Daily Logs</h2><p><?= $clocks['rule_set']==='us_property'?'Current day plus previous 7 days':'Current day plus previous 14 days' ?> for roadside review.</p></div></div>
<div class="hos-log-history">
<?php foreach($logs as $history): $s=$history['summary']; ?><a class="hos-log-history-card <?= $history['log_date']===$date?'active':'' ?>" href="<?= url('/hos/driver?'.($isOwnDriver?'':'driver_id='.(int)$driverId.'&').'date='.$history['log_date']) ?>"><span><?= e(date('D',strtotime($history['log_date']))) ?></span><strong><?= e(date('M j',strtotime($history['log_date']))) ?></strong><small>D <?= hos_minutes($s['totals']['driving']) ?> · ON <?= hos_minutes($s['totals']['on_duty']) ?></small><i class="badge badge-<?= status_class((string)$history['status']) ?>"><?= e(readable_status((string)$history['status'])) ?></i><?php if($s['violations']): ?><b><?= count($s['violations']) ?> warning<?= count($s['violations'])===1?'':'s' ?></b><?php endif; ?></a><?php endforeach; ?>
</div>
</section>
