<?php
$pageTitle = 'Load ' . $load['load_number'];
$isReefer = !empty($load['temperature_controlled']);
$latestTemperature = $temperatureLogs[0] ?? null;
$temperatureOutsideRange = false;
if ($latestTemperature) {
    $reading = (float) $latestTemperature['temperature'];
    $temperatureOutsideRange = ($load['temperature_min'] !== null && $reading < (float) $load['temperature_min'])
        || ($load['temperature_max'] !== null && $reading > (float) $load['temperature_max']);
}
?>
<div class="driver-mobile-toolbar no-print">
    <a class="btn btn-light" href="<?= url('/driver/loads') ?>">Back to Loads</a>
    <?php if (!empty($load['current_latitude']) && !empty($load['current_longitude'])): ?>
        <a class="btn btn-light" target="_blank" rel="noopener" href="https://www.google.com/maps?q=<?= e((string) $load['current_latitude']) ?>,<?= e((string) $load['current_longitude']) ?>">Open Map</a>
    <?php endif; ?>
</div>

<div class="content-grid two-col driver-load-page">
    <div class="content-grid">
        <div class="panel driver-hero-card">
            <div class="panel-header">
                <div>
                    <p class="eyebrow">Assigned Load</p>
                    <h2><?= e($load['load_number']) ?></h2>
                    <p class="muted">Update location, complete stops, record reefer readings, and upload documents from your phone.</p>
                </div>
                <span class="badge badge-<?= status_class($load['status']) ?>"><?= e(readable_status($load['status'])) ?></span>
            </div>
            <div class="route-card">
                <div><small>Pickup</small><strong><?= e($load['pickup_location']) ?></strong><span><?= e(datetime_display($load['pickup_datetime'] ?? null)) ?></span></div>
                <div class="route-arrow">→</div>
                <div><small>Delivery</small><strong><?= e($load['delivery_location']) ?></strong><span><?= e(datetime_display($load['delivery_datetime'] ?? null)) ?></span></div>
            </div>
            <div class="detail-grid mobile-detail-grid">
                <div><small>Carrier</small><strong><?= e($load['carrier_name'] ?? '-') ?></strong></div>
                <div><small>Broker</small><strong><?= e($load['broker_name'] ?? '-') ?></strong></div>
                <div><small>Equipment</small><strong><?= e($load['truck_number'] ?? '-') ?> / <?= e($load['trailer_number'] ?? '-') ?></strong></div>
                <div><small>Miles</small><strong><?= e((string) $load['miles']) ?></strong></div>
                <div><small>Commodity</small><strong><?= e($load['commodity'] ?? '-') ?></strong></div>
                <div><small>Weight</small><strong><?= !empty($load['weight']) ? number_format((float) $load['weight']) . ' lb' : '-' ?></strong></div>
                <?php if (!empty($load['last_location_at'])): ?>
                    <div class="span-2"><small>Last Shared Location</small><strong><?= e(datetime_display($load['last_location_at'])) ?></strong><span><?= e($load['last_location_address'] ?: ($load['current_latitude'] . ', ' . $load['current_longitude'])) ?></span></div>
                <?php endif; ?>
            </div>
            <?php if (!empty($load['notes'])): ?><p><strong>Dispatch Notes:</strong> <?= e($load['notes']) ?></p><?php endif; ?>
        </div>

        <?php if ($isReefer): ?>
            <section class="panel reefer-monitor-card <?= $temperatureOutsideRange ? 'temperature-alert-card' : '' ?>">
                <div class="panel-header">
                    <div><p class="eyebrow">Cold Chain</p><h2>Reefer Requirements</h2></div>
                    <span class="reefer-badge"><?= e((string) $load['temperature_setpoint'] . ($load['temperature_unit'] ?? 'F')) ?> setpoint</span>
                </div>
                <div class="reefer-reading-grid">
                    <div><span>Allowed Range</span><strong><?= e((string) $load['temperature_min']) ?>–<?= e((string) $load['temperature_max']) ?><?= e($load['temperature_unit'] ?? 'F') ?></strong></div>
                    <div><span>Reefer Mode</span><strong><?= e(readable_status($load['reefer_mode'] ?? 'continuous')) ?></strong></div>
                    <div><span>Pre-cool</span><strong><?= !empty($load['precool_required']) ? 'Required' : 'Not required' ?></strong><?php if (!empty($load['precool_temperature'])): ?><small><?= e((string)$load['precool_temperature'] . ($load['temperature_unit'] ?? 'F')) ?></small><?php endif; ?></div>
                    <div><span>Latest Reading</span><strong><?= $latestTemperature ? e((string)$latestTemperature['temperature'] . $latestTemperature['temperature_unit']) : 'Not recorded' ?></strong><?php if ($latestTemperature): ?><small><?= e(datetime_display($latestTemperature['recorded_at'])) ?></small><?php endif; ?></div>
                </div>
                <div class="requirement-chips">
                    <?php if (!empty($load['pulp_temperature_required'])): ?><span>Pulp temperature required</span><?php endif; ?>
                    <?php if (!empty($load['washout_required'])): ?><span>Washout required</span><?php endif; ?>
                    <?php if (!empty($load['seal_required'])): ?><span>Seal required</span><?php endif; ?>
                </div>
                <?php if ($temperatureOutsideRange): ?><div class="inline-alert danger">The latest reading is outside the approved range. Dispatch has been alerted.</div><?php endif; ?>
                <?php if (!empty($load['temperature_instructions'])): ?><p class="reefer-instructions"><strong>Temperature instructions:</strong> <?= e($load['temperature_instructions']) ?></p><?php endif; ?>
            </section>
        <?php endif; ?>

        <div class="panel live-tracking-card no-print" data-live-tracking data-load-id="<?= e((string) $load['id']) ?>" data-ping-url="<?= url('/tracking/ping') ?>" data-stop-url="<?= url('/tracking/stop') ?>" data-csrf="<?= e(Csrf::token()) ?>" data-interval="<?= e(setting('tracking_interval_seconds','30') ?: '30') ?>">
            <div class="panel-header"><div><p class="eyebrow">Live GPS</p><h2>Trip Tracking</h2></div><span class="tracking-state" data-tracking-state>Not sharing</span></div>
            <p class="muted">Start tracking when the trip begins. Keep this page open for reliable browser-based updates.</p>
            <div class="button-row"><button class="btn btn-primary" type="button" data-start-tracking>Start Live Tracking</button><button class="btn btn-danger" type="button" data-stop-tracking disabled>Stop Tracking</button></div>
            <small data-tracking-message>Location is shared only after you start tracking.</small>
        </div>

        <?php if (!empty($borderCrossings)): ?>
            <div class="panel border-driver-card">
                <div class="panel-header"><div><p class="eyebrow">International Load</p><h2>Border Crossing</h2></div></div>
                <div class="mobile-card-list">
                    <?php foreach ($borderCrossings as $crossing): ?>
                        <a class="mobile-record-card" href="<?= url('/borders/show?id=' . $crossing['id']) ?>">
                            <div><strong><?= e($crossing['crossing_number'] . ' · ' . $crossing['crossing_name']) ?></strong><span><?= e($crossing['origin_country'] . ' → ' . $crossing['destination_country']) ?> · <?= e(datetime_display($crossing['planned_at'])) ?></span></div>
                            <span class="badge badge-<?= status_class($crossing['status']) ?>"><?= e(readable_status($crossing['status'])) ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php if (!empty($load['stops'])): ?>
            <div class="panel">
                <div class="panel-header"><div><p class="eyebrow">Stops</p><h2>Pickup & Delivery Stops</h2></div></div>
                <div class="driver-stops-list">
                    <?php foreach ($load['stops'] as $stop): ?>
                        <div class="driver-stop-card <?= !empty($stop['completed_at']) ? 'completed' : '' ?>">
                            <div class="stop-main">
                                <span class="stop-number"><?= e((string) $stop['sequence']) ?></span>
                                <div>
                                    <strong><?= e(readable_status($stop['stop_type'])) ?> · <?= e($stop['location']) ?></strong>
                                    <p><?= e(datetime_display($stop['scheduled_at'] ?? null)) ?> <?= $stop['contact_name'] ? '· ' . e($stop['contact_name']) : '' ?></p>
                                    <div class="stop-meta-row">
                                        <?php if ($stop['temperature_reading'] !== null): ?><span>Temp <?= e((string)$stop['temperature_reading'] . ($stop['temperature_unit'] ?: ($load['temperature_unit'] ?? 'F'))) ?></span><?php endif; ?>
                                        <?php if (!empty($stop['seal_number'])): ?><span>Seal <?= e($stop['seal_number']) ?></span><?php endif; ?>
                                    </div>
                                    <?php if (!empty($stop['completed_at'])): ?><small>Completed <?= e(datetime_display($stop['completed_at'])) ?></small><?php endif; ?>
                                </div>
                            </div>
                            <div class="stop-actions no-print">
                                <?php if (empty($stop['completed_at'])): ?>
                                    <form method="post" action="<?= url('/driver/loads/stop-complete') ?>" data-location-form class="inline-form">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="load_id" value="<?= e((string) $load['id']) ?>">
                                        <input type="hidden" name="stop_id" value="<?= e((string) $stop['id']) ?>">
                                        <input type="hidden" name="latitude" data-latitude>
                                        <input type="hidden" name="longitude" data-longitude>
                                        <button class="btn btn-primary btn-sm" type="submit">Complete Stop</button>
                                    </form>
                                <?php endif; ?>
                                <button class="btn btn-light btn-sm" type="button" data-fill-stop-upload="<?= e((string) $stop['id']) ?>" data-stop-label="<?= e($stop['sequence'] . ' - ' . $stop['location']) ?>">Upload Stop Image</button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="panel">
            <div class="panel-header"><div><p class="eyebrow">Photos & Documents</p><h2>Uploaded Files</h2></div></div>
            <div class="doc-gallery">
                <?php foreach ($documents as $document): ?>
                    <a class="doc-tile" href="<?= url('/documents/download?id=' . $document['id']) ?>">
                        <strong><?= e($document['document_type']) ?></strong>
                        <span><?= e($document['file_name']) ?></span>
                        <?php if (!empty($document['stop_location'])): ?><small>Stop <?= e((string) $document['stop_sequence']) ?> · <?= e($document['stop_location']) ?></small><?php endif; ?>
                        <?php if (!empty($document['location_address'])): ?><small><?= e($document['location_address']) ?></small><?php endif; ?>
                    </a>
                <?php endforeach; ?>
                <?php if (!$documents): ?><p class="empty">No files uploaded yet.</p><?php endif; ?>
            </div>
        </div>
    </div>

    <div class="content-grid driver-action-panel">
        <div class="panel sticky-mobile-card">
            <div class="panel-header"><div><p class="eyebrow">Quick Actions</p><h2>Update Trip</h2></div></div>
            <form method="post" action="<?= url('/driver/loads/status') ?>" class="form-stack" data-location-form>
                <?= csrf_field() ?><input type="hidden" name="id" value="<?= e((string) $load['id']) ?>">
                <input type="hidden" name="latitude" data-latitude><input type="hidden" name="longitude" data-longitude><input type="hidden" name="accuracy" data-accuracy><input type="hidden" name="location_address" data-location-address>
                <label><span>Status</span><select name="status"><?php foreach (['arrived_pickup', 'picked_up', 'in_transit', 'arrived_delivery', 'delivered'] as $status): ?><option value="<?= e($status) ?>" <?= $load['status'] === $status ? 'selected' : '' ?>><?= e(readable_status($status)) ?></option><?php endforeach; ?></select></label>
                <button class="btn btn-primary btn-block" type="submit">Update Status With Location</button>
            </form>
            <hr class="soft-separator">
            <form method="post" action="<?= url('/driver/loads/location') ?>" class="form-stack" data-location-form>
                <?= csrf_field() ?><input type="hidden" name="id" value="<?= e((string) $load['id']) ?>"><input type="hidden" name="latitude" data-latitude><input type="hidden" name="longitude" data-longitude><input type="hidden" name="accuracy" data-accuracy>
                <label><span>Manual Location / Address</span><input name="location_address" data-location-address placeholder="Warehouse, truck stop, city/state"></label>
                <label><span>Location Note</span><textarea name="notes" rows="2" placeholder="Optional note"></textarea></label>
                <button class="btn btn-light btn-block" type="submit">Share Current Location</button>
            </form>
        </div>

        <?php if ($isReefer): ?>
            <div class="panel temperature-entry-card">
                <div class="panel-header"><div><p class="eyebrow">Cold Chain Check</p><h2>Record Temperature</h2></div></div>
                <form method="post" action="<?= url('/driver/loads/temperature') ?>" enctype="multipart/form-data" class="form-stack" data-location-form>
                    <?= csrf_field() ?><input type="hidden" name="load_id" value="<?= e((string)$load['id']) ?>"><input type="hidden" name="latitude" data-latitude><input type="hidden" name="longitude" data-longitude>
                    <label><span>Stop / Checkpoint</span><select name="stop_id"><option value="">In transit / general check</option><?php foreach ($load['stops'] as $stop): ?><option value="<?= e((string)$stop['id']) ?>"><?= e($stop['sequence'].' · '.readable_status($stop['stop_type']).' · '.$stop['location']) ?></option><?php endforeach; ?></select></label>
                    <div class="form-grid two compact-form-grid"><label><span>Temperature *</span><input type="number" step="0.1" name="temperature" required inputmode="decimal"></label><label><span>Unit</span><select name="temperature_unit"><option value="F" <?= ($load['temperature_unit']??'F')==='F'?'selected':'' ?>>°F</option><option value="C" <?= ($load['temperature_unit']??'')==='C'?'selected':'' ?>>°C</option></select></label></div>
                    <div class="form-grid two compact-form-grid"><label><span>Setpoint</span><input type="number" step="0.1" name="setpoint" value="<?= e((string)($load['temperature_setpoint']??'')) ?>"></label><label><span>Mode</span><select name="reefer_mode"><option value="continuous" <?= ($load['reefer_mode']??'continuous')==='continuous'?'selected':'' ?>>Continuous</option><option value="cycle_sentry" <?= ($load['reefer_mode']??'')==='cycle_sentry'?'selected':'' ?>>Cycle Sentry</option><option value="off">Off</option></select></label></div>
                    <div class="form-grid two compact-form-grid"><label><span>Reefer Fuel %</span><input type="number" min="0" max="100" step="0.1" name="reefer_fuel_level"></label><label><span>Pulp Temperature</span><input type="number" step="0.1" name="pulp_temperature"></label></div>
                    <label><span>Temperature Photo</span><input type="file" name="temperature_photo" accept="image/*,application/pdf" capture="environment"></label>
                    <label><span>Location / Notes</span><input name="location_address" data-location-address placeholder="Auto or manual location"><textarea name="notes" rows="2" placeholder="Seal, unit alarm, product condition, or other notes"></textarea></label>
                    <button class="btn btn-primary btn-block" type="submit">Save Temperature Reading</button>
                </form>
                <div class="temperature-log-list compact-temperature-list">
                    <?php foreach (array_slice($temperatureLogs, 0, 5) as $temperature): ?>
                        <?php $out = ($load['temperature_min'] !== null && (float)$temperature['temperature'] < (float)$load['temperature_min']) || ($load['temperature_max'] !== null && (float)$temperature['temperature'] > (float)$load['temperature_max']); ?>
                        <div class="temperature-log-item <?= $out ? 'out-of-range' : '' ?>"><div><strong><?= e((string)$temperature['temperature'].$temperature['temperature_unit']) ?></strong><span><?= e(datetime_display($temperature['recorded_at'])) ?><?= $temperature['stop_location'] ? ' · '.e($temperature['stop_location']) : '' ?></span></div><span><?= $out ? 'Alert' : e(readable_status($temperature['reefer_mode'] ?: 'recorded')) ?></span></div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="panel">
            <div class="panel-header"><div><p class="eyebrow">Camera Upload</p><h2>Upload Image / Challan</h2></div></div>
            <form method="post" action="<?= url('/driver/loads/upload') ?>" enctype="multipart/form-data" class="form-stack" data-location-form id="driver-upload-form">
                <?= csrf_field() ?><input type="hidden" name="load_id" value="<?= e((string) $load['id']) ?>"><input type="hidden" name="related_type" value="load" id="upload-related-type"><input type="hidden" name="related_id" value="<?= e((string) $load['id']) ?>" id="upload-related-id"><input type="hidden" name="latitude" data-latitude><input type="hidden" name="longitude" data-longitude>
                <label><span>Upload Type</span><select name="document_type" id="upload-document-type"><option value="Load Photo">Load Photo</option><option value="Stop Photo">Stop Photo</option><option value="BOL">BOL</option><option value="POD">POD</option><option value="Seal Photo">Seal Photo</option><option value="Washout Receipt">Washout Receipt</option><option value="Reefer Temperature Photo">Reefer Temperature Photo</option><option value="Challan / Ticket">Challan / Ticket</option><option value="Accident / Damage Photo">Accident / Damage Photo</option><option value="Fuel Receipt">Fuel Receipt</option><option value="Scale Ticket">Scale Ticket</option><option value="Lumper Receipt">Lumper Receipt</option><option value="Other">Other</option></select></label>
                <div class="selected-stop-note" id="selected-stop-note">Attached to full load</div>
                <label><span>Image / PDF</span><input type="file" name="file" accept="image/*,application/pdf" capture="environment" required></label>
                <label><span>Location / Address</span><input name="location_address" data-location-address placeholder="Auto or manual location"></label>
                <label><span>Notes</span><textarea name="notes" rows="3" placeholder="Challan number, amount, seal number, damage notes, loading notes, etc."></textarea></label>
                <button class="btn btn-primary btn-block" type="submit">Upload File</button>
            </form>
        </div>

        <div class="panel">
            <div class="panel-header"><div><p class="eyebrow">Timeline</p><h2>Recent Activity</h2></div></div>
            <div class="timeline compact-timeline"><?php foreach ($events as $event): ?><div><span></span><strong><?= e(readable_status($event['event_type'])) ?></strong><p><?= e($event['description'] ?? '') ?> · <?= e(datetime_display($event['created_at'])) ?></p></div><?php endforeach; ?><?php if (!$events): ?><p class="empty">No activity yet.</p><?php endif; ?></div>
        </div>
    </div>
</div>
