<?php
$stopRows=$load['stops']??[];
if(is_array(old('stop_location'))){
    $stopRows=[];
    $oldLocations=old('stop_location',[]);
    foreach($oldLocations as $i=>$location){
        $stopRows[]=[
            'stop_type'=>old('stop_type',[])[$i]??'pickup','location'=>$location,'scheduled_at'=>old('stop_datetime',[])[$i]??null,
            'contact_name'=>old('stop_contact',[])[$i]??null,'notes'=>old('stop_notes',[])[$i]??null,'latitude'=>old('stop_latitude',[])[$i]??null,
            'longitude'=>old('stop_longitude',[])[$i]??null,'temperature_reading'=>old('stop_temperature',[])[$i]??null,
            'temperature_unit'=>old('stop_temperature_unit',[])[$i]??null,'seal_number'=>old('stop_seal_number',[])[$i]??null,
        ];
    }
}
$selectedCarrier=(string)old('carrier_id',$load['carrier_id']??($preselectedCarrier??''));
?>
<form method="post" action="<?= e($action) ?>" class="form-stack" id="load-form" data-load-form>
<?= csrf_field() ?><?php if(!empty($load['id'])): ?><input type="hidden" name="id" value="<?= e((string)$load['id']) ?>"><?php endif; ?>

<section class="form-section">
<div class="form-section-head"><div><p class="eyebrow">Load Booking</p><h3>Customer, Reference & Status</h3></div><span class="section-chip">Customer rate and operating status</span></div>
<div class="form-grid three">
<label><span>Load Number *</span><input name="load_number" value="<?= e(old('load_number',$load['load_number']??'')) ?>" required></label>
<label><span>Reference Number</span><input name="reference_number" value="<?= e(old('reference_number',$load['reference_number']??'')) ?>"></label>
<label><span>Broker / Customer</span><select name="broker_id"><option value="">Select broker / customer</option><?php foreach($brokers as $broker): ?><option value="<?= e((string)$broker['id']) ?>" <?= (string)old('broker_id',$load['broker_id']??'')===(string)$broker['id']?'selected':'' ?>><?= e($broker['company_name']) ?></option><?php endforeach; ?></select></label>
<label><span>Customer / Broker Rate</span><input type="number" step="0.01" min="0" name="rate" data-customer-rate value="<?= e(old('rate',$load['rate']??'0')) ?>"></label>
<label><span>Miles</span><input type="number" step="0.01" min="0" name="miles" value="<?= e(old('miles',$load['miles']??'0')) ?>"></label>
<label><span>Load Status</span><select name="status"><?php foreach($statuses as $status): ?><option value="<?= e($status) ?>" <?= old('status',$load['status']??'new')===$status?'selected':'' ?>><?= e(readable_status($status)) ?></option><?php endforeach; ?></select></label>
</div>
</section>

<section class="form-section carrier-assignment-section">
<div class="form-section-head"><div><p class="eyebrow">Carrier Assignment</p><h3>External Carrier, Equipment & Dispatch Fee</h3><p class="muted">Designed for dispatch companies managing owner-operators and other trucking companies.</p></div><span class="section-chip">Carrier-first workflow</span></div>
<div class="form-grid three">
<label><span>Carrier Company</span><select name="carrier_id" data-carrier-select><option value="">Unassigned carrier</option><?php foreach($carriers as $carrier): ?><option value="<?= e((string)$carrier['id']) ?>" data-fee-type="<?= e($carrier['dispatch_fee_type']) ?>" data-fee-value="<?= e((string)$carrier['dispatch_fee_value']) ?>" <?= $selectedCarrier===(string)$carrier['id']?'selected':'' ?>><?= e($carrier['company_name']) ?> · <?= e(readable_status($carrier['onboarding_status'])) ?></option><?php endforeach; ?></select></label>
<label><span>Equipment Source</span><select name="equipment_source"><option value="external_carrier" <?= old('equipment_source',$load['equipment_source']??'external_carrier')==='external_carrier'?'selected':'' ?>>External Carrier Equipment</option><option value="company_equipment" <?= old('equipment_source',$load['equipment_source']??'')==='company_equipment'?'selected':'' ?>>Company Equipment</option><option value="rental" <?= old('equipment_source',$load['equipment_source']??'')==='rental'?'selected':'' ?>>Rental Equipment</option><option value="power_only" <?= old('equipment_source',$load['equipment_source']??'')==='power_only'?'selected':'' ?>>Power Only</option></select></label>
<label><span>Carrier Confirmation</span><select name="carrier_confirmation_status"><option value="not_sent" <?= old('carrier_confirmation_status',$load['carrier_confirmation_status']??'not_sent')==='not_sent'?'selected':'' ?>>Not Sent</option><option value="sent" <?= old('carrier_confirmation_status',$load['carrier_confirmation_status']??'')==='sent'?'selected':'' ?>>Sent</option><option value="accepted" <?= old('carrier_confirmation_status',$load['carrier_confirmation_status']??'')==='accepted'?'selected':'' ?>>Accepted</option><option value="rejected" <?= old('carrier_confirmation_status',$load['carrier_confirmation_status']??'')==='rejected'?'selected':'' ?>>Rejected</option></select></label>
<label><span>Carrier Reference</span><input name="carrier_reference" value="<?= e(old('carrier_reference',$load['carrier_reference']??'')) ?>" placeholder="Carrier load / confirmation #"></label>
<label><span>Payment Responsibility</span><select name="payment_responsibility"><option value="broker_pays_carrier" <?= old('payment_responsibility',$load['payment_responsibility']??'broker_pays_carrier')==='broker_pays_carrier'?'selected':'' ?>>Broker Pays Carrier</option><option value="dispatch_collects" <?= old('payment_responsibility',$load['payment_responsibility']??'')==='dispatch_collects'?'selected':'' ?>>Dispatch Company Collects</option><option value="carrier_collects" <?= old('payment_responsibility',$load['payment_responsibility']??'')==='carrier_collects'?'selected':'' ?>>Carrier Collects</option></select></label>
<label><span>Carrier Gross Rate</span><input type="number" step="0.01" min="0" name="carrier_rate" data-carrier-rate value="<?= e(old('carrier_rate',$load['carrier_rate']??($load['rate']??'0'))) ?>"></label>
<label><span>Dispatch Fee Type</span><select name="dispatch_fee_type" data-fee-type><option value="percentage" <?= old('dispatch_fee_type',$load['dispatch_fee_type']??'percentage')==='percentage'?'selected':'' ?>>Percentage</option><option value="fixed" <?= old('dispatch_fee_type',$load['dispatch_fee_type']??'')==='fixed'?'selected':'' ?>>Fixed Amount</option></select></label>
<label><span>Dispatch Fee Value</span><input type="number" step="0.01" min="0" name="dispatch_fee_value" data-fee-value value="<?= e(old('dispatch_fee_value',$load['dispatch_fee_value']??'')) ?>"></label>
<label><span>Driver</span><select name="driver_id" data-equipment-select><option value="">Unassigned</option><?php foreach($drivers as $driver): ?><option value="<?= e((string)$driver['id']) ?>" data-carrier-id="<?= e((string)($driver['carrier_id']??'')) ?>" <?= (string)old('driver_id',$load['driver_id']??'')===(string)$driver['id']?'selected':'' ?>><?= e($driver['name']) ?><?= $driver['carrier_name']?' · '.e($driver['carrier_name']):'' ?></option><?php endforeach; ?></select></label>
<label><span>Truck</span><select name="truck_id" data-equipment-select><option value="">Unassigned</option><?php foreach($trucks as $truck): ?><option value="<?= e((string)$truck['id']) ?>" data-carrier-id="<?= e((string)($truck['carrier_id']??'')) ?>" <?= (string)old('truck_id',$load['truck_id']??'')===(string)$truck['id']?'selected':'' ?>><?= e($truck['unit_number']) ?><?= $truck['carrier_name']?' · '.e($truck['carrier_name']):'' ?></option><?php endforeach; ?></select></label>
<label><span>Trailer</span><select name="trailer_id" data-trailer-select><option value="">Unassigned</option><?php foreach($trailers as $trailer): ?><option value="<?= e((string)$trailer['id']) ?>" data-carrier-id="<?= e((string)($trailer['carrier_id']??'')) ?>" data-reefer="<?= !empty($trailer['reefer_capable'])?'1':'0' ?>" data-setpoint="<?= e((string)($trailer['current_setpoint']??'')) ?>" data-temp-unit="<?= e($trailer['temperature_unit']??'F') ?>" <?= (string)old('trailer_id',$load['trailer_id']??'')===(string)$trailer['id']?'selected':'' ?>><?= e($trailer['trailer_number']) ?> · <?= e($trailer['type']??'Trailer') ?><?= $trailer['carrier_name']?' · '.e($trailer['carrier_name']):'' ?></option><?php endforeach; ?></select></label>
</div>
<div class="financial-preview" data-financial-preview><div><span>Customer Rate</span><strong data-preview-customer><?= money(old('rate',$load['rate']??0)) ?></strong></div><div><span>Carrier Gross</span><strong data-preview-carrier><?= money(old('carrier_rate',$load['carrier_rate']??0)) ?></strong></div><div><span>Dispatch Fee</span><strong data-preview-fee><?= money($load['dispatch_fee_amount']??0) ?></strong></div><div><span>Carrier Net</span><strong data-preview-net><?= money($load['carrier_net_amount']??0) ?></strong></div></div>
</section>

<section class="form-section">
<div class="form-section-head"><div><p class="eyebrow">Route</p><h3>Primary Pickup & Delivery</h3></div></div>
<div class="form-grid two">
<label><span>Pickup Location *</span><input name="pickup_location" value="<?= e(old('pickup_location',$load['pickup_location']??'')) ?>" required></label>
<label><span>Delivery Location *</span><input name="delivery_location" value="<?= e(old('delivery_location',$load['delivery_location']??'')) ?>" required></label>
<label><span>Pickup Date / Time</span><input type="datetime-local" name="pickup_datetime" value="<?= e(old('pickup_datetime',isset($load['pickup_datetime'])&&$load['pickup_datetime']?str_replace(' ','T',substr($load['pickup_datetime'],0,16)):'')) ?>"></label>
<label><span>Delivery Date / Time</span><input type="datetime-local" name="delivery_datetime" value="<?= e(old('delivery_datetime',isset($load['delivery_datetime'])&&$load['delivery_datetime']?str_replace(' ','T',substr($load['delivery_datetime'],0,16)):'')) ?>"></label>
</div>
<div class="line-items" id="load-stops"><div class="section-title-row"><div><h3>Additional Stops</h3><p class="muted">Add extra pickups, deliveries, stop temperature readings, and seal numbers.</p></div><button class="btn btn-light btn-sm" type="button" data-add-stop>Add Stop</button></div>
<?php foreach($stopRows as $stop): ?><div class="stop-row stop-row-expanded">
<select name="stop_type[]" aria-label="Stop type"><option value="pickup" <?= ($stop['stop_type']??'')==='pickup'?'selected':'' ?>>Pickup</option><option value="delivery" <?= ($stop['stop_type']??'')==='delivery'?'selected':'' ?>>Delivery</option></select>
<input name="stop_location[]" value="<?= e($stop['location']??'') ?>" placeholder="Stop location">
<input type="datetime-local" name="stop_datetime[]" value="<?= e(!empty($stop['scheduled_at'])?str_replace(' ','T',substr($stop['scheduled_at'],0,16)):'') ?>">
<input name="stop_contact[]" value="<?= e($stop['contact_name']??'') ?>" placeholder="Contact">
<input type="number" step="0.1" name="stop_temperature[]" value="<?= e((string)($stop['temperature_reading']??'')) ?>" placeholder="Temp">
<select name="stop_temperature_unit[]" aria-label="Temperature unit"><option value="">Unit</option><option value="F" <?= ($stop['temperature_unit']??'')==='F'?'selected':'' ?>>°F</option><option value="C" <?= ($stop['temperature_unit']??'')==='C'?'selected':'' ?>>°C</option></select>
<input name="stop_seal_number[]" value="<?= e($stop['seal_number']??'') ?>" placeholder="Seal #">
<input name="stop_notes[]" value="<?= e($stop['notes']??'') ?>" placeholder="Stop notes">
<input type="hidden" name="stop_latitude[]" value="<?= e((string)($stop['latitude']??'')) ?>"><input type="hidden" name="stop_longitude[]" value="<?= e((string)($stop['longitude']??'')) ?>">
<button class="btn btn-danger btn-sm" type="button" data-remove-row>Remove</button></div><?php endforeach; ?>
</div>
</section>

<section class="form-section">
<div class="form-section-head"><div><p class="eyebrow">Cargo</p><h3>Commodity, Weight & Handling</h3></div></div>
<div class="form-grid three"><label><span>Commodity</span><input name="commodity" value="<?= e(old('commodity',$load['commodity']??'')) ?>"></label><label><span>Weight (lbs)</span><input type="number" step="0.01" name="weight" value="<?= e(old('weight',$load['weight']??'')) ?>"></label></div>
</section>

<section class="form-section reefer-section" data-load-reefer-section>
<div class="form-section-head"><div><p class="eyebrow">Temperature Control</p><h3>Reefer Requirements</h3><p class="muted">Set the booked temperature range and instructions that drivers must follow and log.</p></div><label class="toggle-option toggle-primary"><input type="checkbox" name="temperature_controlled" value="1" data-load-reefer-toggle <?= old('temperature_controlled',$load['temperature_controlled']??0)?'checked':'' ?>><span>Temperature-controlled load</span></label></div>
<div class="form-grid three" data-load-reefer-fields>
<label><span>Temperature Unit</span><select name="temperature_unit" data-load-temp-unit><option value="F" <?= old('temperature_unit',$load['temperature_unit']??'F')==='F'?'selected':'' ?>>Fahrenheit (°F)</option><option value="C" <?= old('temperature_unit',$load['temperature_unit']??'')==='C'?'selected':'' ?>>Celsius (°C)</option></select></label>
<label><span>Setpoint</span><input type="number" step="0.1" name="temperature_setpoint" value="<?= e(old('temperature_setpoint',$load['temperature_setpoint']??'')) ?>"></label>
<label><span>Operating Mode</span><select name="reefer_mode"><option value="">Not specified</option><option value="continuous" <?= old('reefer_mode',$load['reefer_mode']??'')==='continuous'?'selected':'' ?>>Continuous</option><option value="cycle_sentry" <?= old('reefer_mode',$load['reefer_mode']??'')==='cycle_sentry'?'selected':'' ?>>Cycle Sentry</option></select></label>
<label><span>Minimum Allowed</span><input type="number" step="0.1" name="temperature_min" value="<?= e(old('temperature_min',$load['temperature_min']??'')) ?>"></label>
<label><span>Maximum Allowed</span><input type="number" step="0.1" name="temperature_max" value="<?= e(old('temperature_max',$load['temperature_max']??'')) ?>"></label>
<label><span>Pre-cool Temperature</span><input type="number" step="0.1" name="precool_temperature" value="<?= e(old('precool_temperature',$load['precool_temperature']??'')) ?>"></label>
</div>
<div class="option-grid">
<label class="toggle-option"><input type="checkbox" name="precool_required" value="1" <?= old('precool_required',$load['precool_required']??0)?'checked':'' ?>><span>Pre-cool Required</span></label>
<label class="toggle-option"><input type="checkbox" name="pulp_temperature_required" value="1" <?= old('pulp_temperature_required',$load['pulp_temperature_required']??0)?'checked':'' ?>><span>Pulp Temperature Required</span></label>
<label class="toggle-option"><input type="checkbox" name="washout_required" value="1" <?= old('washout_required',$load['washout_required']??0)?'checked':'' ?>><span>Washout Required</span></label>
<label class="toggle-option"><input type="checkbox" name="seal_required" value="1" <?= old('seal_required',$load['seal_required']??0)?'checked':'' ?>><span>Seal Required</span></label>
</div>
<label style="margin-top:16px"><span>Temperature / Reefer Instructions</span><textarea name="temperature_instructions" rows="4" placeholder="Pre-cool procedure, continuous mode, check frequency, pulp requirements, do not break seal, etc."><?= e(old('temperature_instructions',$load['temperature_instructions']??'')) ?></textarea></label>
</section>

<section class="form-section"><div class="form-section-head"><div><p class="eyebrow">Internal Notes</p><h3>Dispatcher Instructions</h3></div></div><label><span>Notes</span><textarea name="notes" rows="5"><?= e(old('notes',$load['notes']??'')) ?></textarea></label></section>

<div class="form-actions sticky-form-actions"><button class="btn btn-primary" type="submit">Save Load</button><a class="btn btn-light" href="<?= url('/loads') ?>">Cancel</a><?php if(!empty($load['id'])): ?><a class="btn btn-light" href="<?= url('/documents/create?related_type=load&related_id='.$load['id']) ?>">Upload Document</a><?php if(in_array($load['status'],['delivered','invoiced'],true)): ?><a class="btn btn-light" href="<?= url('/invoices/create?load_id='.$load['id']) ?>">Create Invoice</a><?php endif; ?><?php endif; ?></div>
</form>

<?php if(!empty($documents)): ?><div class="linked-documents"><h3>Attached Documents</h3><div class="mini-list two-mini"><?php foreach($documents as $document): ?><a class="mini-card" href="<?= url('/documents/download?id='.$document['id']) ?>"><strong><?= e($document['document_type']) ?></strong><span><?= e($document['file_name']) ?></span></a><?php endforeach; ?></div></div><?php endif; ?>
