<?php $this->start('body'); ?>
<?php $t = $this->data['t']; $history = $this->data['history']; ?>

<?php
  $bg = ['dispatched'=>'primary','in_transit'=>'info','delivered'=>'warning','closed'=>'success','cancelled'=>'dark'][$t['status']] ?? 'secondary';
?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-truck-loading me-2 text-muted"></i><?= htmlspecialchars($t['trip_no']); ?>
      <span class="badge bg-<?= $bg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ',$t['status'])); ?></span>
    </h5>
    <div class="text-muted small">
      <?php if ($t['request_no']): ?>From <a href="<?= PROOT; ?>TripRequests/view/<?= (int)$t['trip_request_id']; ?>"><?= htmlspecialchars($t['request_no']); ?></a> · <?php endif; ?>
      <a href="<?= PROOT; ?>Drivers/view/<?= (int)$t['driver_id']; ?>"><?= htmlspecialchars($t['driver_name']); ?></a> /
      <a href="<?= PROOT; ?>Trucks/view/<?= (int)$t['truck_id']; ?>"><?= htmlspecialchars($t['truck_reg']); ?></a>
      <?php if ($t['customer_name']): ?> · <a href="<?= PROOT; ?>Customers/view/<?= (int)$t['customer_id']; ?>"><?= htmlspecialchars($t['customer_name']); ?></a><?php endif; ?>
    </div>
  </div>
  <a href="<?= PROOT; ?>Trips" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?= flashHtml(); ?>

<?php if ($t['status'] === 'cancelled' && $t['cancel_reason']): ?>
  <div class="alert alert-danger py-2 small"><i class="fas fa-times-circle me-1"></i><strong>Cancelled:</strong> <?= htmlspecialchars($t['cancel_reason']); ?></div>
<?php endif; ?>

<!-- ══ Assignment card — big, prominent, "who's on this run" ══ -->
<div class="card border-0 shadow-sm mb-3 assignment-card">
  <div class="card-body p-3">
    <div class="row g-3 align-items-center">
      <!-- Driver -->
      <div class="col-md-6">
        <div class="d-flex align-items-center gap-3">
          <div class="assignment-avatar assignment-avatar-driver">
            <?php if ($t['driver_photo']): ?>
              <img src="<?= htmlspecialchars($t['driver_photo']); ?>" alt="Driver">
            <?php else: ?>
              <i class="fas fa-user"></i>
            <?php endif; ?>
          </div>
          <div class="flex-grow-1 min-w-0">
            <div class="text-uppercase text-muted small">Driver</div>
            <div class="fs-6 fw-semibold text-truncate"><a href="<?= PROOT; ?>Drivers/view/<?= (int)$t['driver_id']; ?>" class="text-decoration-none"><?= htmlspecialchars($t['driver_name']); ?></a></div>
            <div class="small text-muted">
              <?php if ($t['driver_employee_no']): ?><?= htmlspecialchars($t['driver_employee_no']); ?> · <?php endif; ?>
              <?php if ($t['driver_phone']):       ?><a href="tel:<?= htmlspecialchars(preg_replace('/\s+/', '', $t['driver_phone'])); ?>" class="text-decoration-none"><i class="fas fa-phone fa-xs me-1"></i><?= htmlspecialchars($t['driver_phone']); ?></a><?php endif; ?>
            </div>
            <?php if ($t['driver_licence_no']): ?>
              <div class="small text-muted">
                Licence <?= htmlspecialchars($t['driver_licence_no']); ?>
                <?php if ($t['driver_licence_class']): ?> · Class <?= htmlspecialchars($t['driver_licence_class']); ?><?php endif; ?>
                <?php if ($t['driver_licence_expires']):
                    $exp = strtotime($t['driver_licence_expires']);
                    $daysToExp = round(($exp - time()) / 86400);
                    $expBg = $daysToExp < 0 ? 'danger' : ($daysToExp <= 30 ? 'warning' : 'success');
                ?>
                  <span class="badge bg-<?= $expBg; ?> ms-1" style="font-size:.6rem;">
                    <?= $daysToExp < 0 ? 'expired' : 'expires ' . humanDate($t['driver_licence_expires']); ?>
                  </span>
                <?php endif; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- Truck -->
      <div class="col-md-6">
        <div class="d-flex align-items-center gap-3">
          <div class="assignment-avatar assignment-avatar-truck">
            <?php if ($t['truck_photo']): ?>
              <img src="<?= htmlspecialchars($t['truck_photo']); ?>" alt="Truck">
            <?php else: ?>
              <i class="fas fa-truck"></i>
            <?php endif; ?>
          </div>
          <div class="flex-grow-1 min-w-0">
            <div class="text-uppercase text-muted small">Vehicle</div>
            <div class="fs-6 fw-semibold font-monospace"><a href="<?= PROOT; ?>Trucks/view/<?= (int)$t['truck_id']; ?>" class="text-decoration-none"><?= htmlspecialchars($t['truck_reg']); ?></a></div>
            <div class="small text-muted">
              <?= htmlspecialchars(trim(($t['make'] ?? '') . ' ' . ($t['model'] ?? ''))); ?>
              <?php if ($t['truck_year']): ?> · <?= (int)$t['truck_year']; ?><?php endif; ?>
            </div>
            <div class="small text-muted">
              <?php if ($t['truck_capacity_kg']):        ?><i class="fas fa-weight-hanging fa-xs me-1"></i><?= number_format((int)$t['truck_capacity_kg']); ?> kg<?php endif; ?>
              <?php if ($t['truck_current_odometer']):   ?> · <i class="fas fa-tachometer-alt fa-xs me-1"></i><?= number_format((int)$t['truck_current_odometer']); ?> km<?php endif; ?>
              <?php if ($t['truck_fuel_tank_liters']):   ?> · <i class="fas fa-gas-pump fa-xs me-1"></i><?= number_format((int)$t['truck_fuel_tank_liters']); ?> L tank<?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<style>
.assignment-card { background: linear-gradient(135deg, var(--pacific-accent) 0%, #ffffff 100%); }
.assignment-avatar { width: 60px; height: 60px; border-radius: 12px; overflow: hidden; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 1.5rem; }
.assignment-avatar img { width: 100%; height: 100%; object-fit: cover; }
.assignment-avatar-driver { background: var(--pacific-tint); color: var(--pacific-navy); }
.assignment-avatar-truck  { background: rgba(34,197,94,.14); color: #16a34a; }
</style>

<?php $gps = $this->data['gps'] ?? []; if (!empty($gps)): ?>
<?php $gpsStale = !empty($gps['last_seen_at']) && strtotime($gps['last_seen_at']) < strtotime('-15 minutes'); ?>
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex align-items-center flex-wrap gap-2 small">
    <span class="text-uppercase text-muted small me-2"><i class="fas fa-map-marker-alt me-1"></i>Live position</span>
    <?php if (!empty($gps['ts'])): ?>
      <span class="font-monospace"><?= number_format((float)$gps['lat'], 5); ?>, <?= number_format((float)$gps['lng'], 5); ?></span>
      <span class="text-muted">·</span>
      <?php if ($gps['speed_kph'] !== null): ?><span><?= number_format((float)$gps['speed_kph'], 0); ?> kph</span><span class="text-muted">·</span><?php endif; ?>
      <?php if ($gps['ignition'] !== null): ?><span class="badge bg-<?= $gps['ignition'] ? 'success' : 'secondary'; ?>"><?= $gps['ignition'] ? 'Ignition on' : 'Ignition off'; ?></span><?php endif; ?>
      <span class="text-muted"><i class="fas fa-clock fa-xs me-1"></i><?= humanDateTime($gps['ts']); ?></span>
      <?php if ($gpsStale): ?><span class="badge bg-danger">stale</span><?php endif; ?>
      <a href="https://www.google.com/maps/search/?api=1&query=<?= (float)$gps['lat']; ?>,<?= (float)$gps['lng']; ?>" target="_blank" rel="noopener" class="btn btn-sm btn-outline-primary ms-auto"><i class="fas fa-external-link-alt me-1"></i>Map</a>
      <a href="<?= PROOT; ?>GpsDevices/view/<?= (int)$gps['device_id']; ?>" class="btn btn-sm btn-outline-secondary" title="Device <?= htmlspecialchars($gps['device_code']); ?>"><i class="fas fa-satellite-dish"></i></a>
    <?php else: ?>
      <span class="text-muted fst-italic">Device <span class="font-monospace"><?= htmlspecialchars($gps['device_code']); ?></span> assigned — awaiting first fix.</span>
    <?php endif; ?>
  </div>
</div>
<?php endif; ?>

<!-- ── Lifecycle actions ─────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-center">
    <span class="text-uppercase text-muted small me-2"><i class="fas fa-play-circle me-1"></i>Actions</span>

    <?php if ($t['status'] === 'dispatched'): ?>
      <button type="button" class="btn btn-sm btn-primary" onclick="doStart()"><i class="fas fa-play me-1"></i>Start trip</button>
    <?php endif; ?>
    <?php if ($t['status'] === 'in_transit'): ?>
      <button type="button" class="btn btn-sm btn-warning" onclick="doAction('deliver','Mark delivered?','Cargo has been dropped off. Trip moves to Delivered awaiting close-out.','Mark delivered','btn-warning','orange')"><i class="fas fa-flag-checkered me-1"></i>Mark delivered</button>
    <?php endif; ?>
    <?php if (in_array($t['status'], ['delivered','in_transit'], true)): ?>
      <button type="button" class="btn btn-sm btn-success" onclick="doClose()"><i class="fas fa-check-double me-1"></i>Close trip</button>
    <?php endif; ?>
    <?php if (in_array($t['status'], ['dispatched','in_transit','delivered'], true)): ?>
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="doCancel()"><i class="fas fa-ban me-1"></i>Cancel trip</button>
    <?php endif; ?>

    <span class="ms-auto text-muted small">
      Dispatched: <?= $t['dispatched_at'] ? humanDateTime($t['dispatched_at']) : '—'; ?>
    </span>
  </div>
</div>

<div class="row g-3">
  <!-- ── Trip Details ─────────────────────────────────────── -->
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Trip Details</h6>
        <dl class="row mb-0">
          <dt class="col-4 text-muted fw-normal">Cargo</dt>       <dd class="col-8"><?= htmlspecialchars($t['cargo_description'] ?: '—'); ?><?php if ($t['cargo_type']): ?> <span class="text-muted small">(<?= htmlspecialchars(ucwords(str_replace('_',' ',$t['cargo_type']))); ?>)</span><?php endif; ?></dd>
          <?php if ($t['weight_kg']): ?><dt class="col-4 text-muted fw-normal">Weight</dt><dd class="col-8"><?= number_format((float)$t['weight_kg'], 0) . ' kg'; ?></dd><?php endif; ?>

          <dt class="col-4 text-muted fw-normal">Origin</dt>      <dd class="col-8"><?= htmlspecialchars($t['origin_address'] ?: '—'); ?></dd>
          <dt class="col-4 text-muted fw-normal">Destination</dt> <dd class="col-8"><?= htmlspecialchars($t['destination_address'] ?: '—'); ?></dd>
          <?php if ($t['route_name']): ?>
            <dt class="col-4 text-muted fw-normal">Route</dt>
            <dd class="col-8"><a href="<?= PROOT; ?>Routes/view/<?= (int)$t['route_id']; ?>"><?= htmlspecialchars($t['route_name']); ?></a>
              <?php if ($t['route_distance']): ?> <span class="text-muted small">· <?= number_format((float)$t['route_distance'], 0); ?> km</span><?php endif; ?></dd>
          <?php endif; ?>

          <hr class="my-2">
          <dt class="col-4 text-muted fw-normal">Planned pickup</dt>  <dd class="col-8"><?= $t['planned_pickup']   ? humanDateTime($t['planned_pickup'])   : '—'; ?></dd>
          <dt class="col-4 text-muted fw-normal">Planned delivery</dt><dd class="col-8"><?= $t['planned_delivery'] ? humanDateTime($t['planned_delivery']) : '—'; ?></dd>
          <?php if ($t['actual_start']): ?><dt class="col-4 text-muted fw-normal">Actual start</dt><dd class="col-8"><?= humanDateTime($t['actual_start']); ?></dd><?php endif; ?>
          <?php if ($t['actual_end']):   ?><dt class="col-4 text-muted fw-normal">Actual end</dt>  <dd class="col-8"><?= humanDateTime($t['actual_end']);   ?></dd><?php endif; ?>

          <hr class="my-2">
          <dt class="col-4 text-muted fw-normal">Odometer</dt><dd class="col-8">
            <?php if ($t['odometer_start'] !== null): ?><?= number_format((int)$t['odometer_start']); ?> km<?php endif; ?>
            <?php if ($t['odometer_end']   !== null): ?> → <?= number_format((int)$t['odometer_end']); ?> km<?php endif; ?>
            <?php if ($t['odometer_start'] === null && $t['odometer_end'] === null): ?>—<?php endif; ?>
          </dd>
          <dt class="col-4 text-muted fw-normal">Distance</dt><dd class="col-8">
            <?php if ($t['actual_km']):  ?><?= number_format((float)$t['actual_km'], 0); ?> km <span class="text-muted small">(actual)</span>
            <?php elseif ($t['planned_km']): ?><?= number_format((float)$t['planned_km'], 0); ?> km <span class="text-muted small">(planned)</span>
            <?php else: ?>—<?php endif; ?>
          </dd>

          <hr class="my-2">
          <dt class="col-4 text-muted fw-normal">Quote</dt>  <dd class="col-8"><?= $t['quote_amount']   ? htmlspecialchars($t['currency']) . ' ' . number_format((float)$t['quote_amount'], 2, '.', ',')   : '—'; ?></dd>
          <dt class="col-4 text-muted fw-normal">Invoice</dt><dd class="col-8"><?= $t['invoice_amount'] ? htmlspecialchars($t['currency']) . ' ' . number_format((float)$t['invoice_amount'], 2, '.', ',') : '—'; ?></dd>

          <?php if ($t['notes']): ?>
            <hr class="my-2">
            <dt class="col-4 text-muted fw-normal">Notes</dt><dd class="col-8"><?= nl2br(htmlspecialchars($t['notes'])); ?></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>
  </div>

  <!-- ── Status Timeline ─────────────────────────────────── -->
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3"><i class="fas fa-history me-1"></i>Status History</h6>
        <?php if (empty($history)): ?>
          <p class="text-muted small mb-0 fst-italic">No status changes logged.</p>
        <?php else: ?>
          <ul class="list-unstyled mb-0 small">
            <?php foreach ($history as $h): ?>
              <li class="mb-3 ps-3" style="border-left: 2px solid var(--pacific-navy);">
                <div class="fw-semibold" style="text-transform:capitalize;">
                  <?= htmlspecialchars(str_replace('_',' ',$h['to_status'])); ?>
                  <?php if ($h['from_status']): ?><span class="text-muted small">← <?= htmlspecialchars(str_replace('_',' ',$h['from_status'])); ?></span><?php endif; ?>
                </div>
                <div class="text-muted small"><?= humanDateTime($h['changed_at']); ?><?php if ($h['actor_name']): ?> · <?= htmlspecialchars($h['actor_name']); ?><?php endif; ?></div>
                <?php if ($h['note']): ?><div class="small mt-1"><?= htmlspecialchars($h['note']); ?></div><?php endif; ?>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- ══ Stops timeline (execution) ══ -->
<?php $stops = $this->data['stops']; $canEditStops = !in_array($t['status'], ['closed','cancelled'], true); ?>
<div class="card border-0 shadow-sm mt-3">
  <div class="card-body">
    <div class="d-flex align-items-center justify-content-between mb-3">
      <h6 class="text-uppercase text-muted small mb-0"><i class="fas fa-map-marked-alt me-1"></i>Stops Timeline
        <span class="text-muted">· <?= count($stops); ?></span>
      </h6>
      <?php if ($canEditStops): ?>
        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#addStopPanel"><i class="fas fa-plus me-1"></i>Add stop</button>
      <?php endif; ?>
    </div>

    <?php if ($canEditStops): ?>
      <div id="addStopPanel" class="collapse mb-3">
        <form method="POST" action="<?= PROOT; ?>Trips/addStop/<?= (int)$t['c0d']; ?>" class="border rounded p-3 bg-light">
          <?= csrf_field(); ?>
          <div class="row g-2">
            <div class="col-md-3"><label class="form-label small mb-1">Kind <span class="text-danger">*</span></label>
              <select name="kind" class="form-select form-select-sm" required>
                <?php foreach (\TripStops::KINDS as $k => $lbl): ?>
                  <option value="<?= $k; ?>"><?= htmlspecialchars($lbl); ?></option>
                <?php endforeach; ?>
              </select></div>
            <div class="col-md-4"><label class="form-label small mb-1">Location</label>
              <input type="text" name="location_name" class="form-control form-control-sm"></div>
            <div class="col-md-5"><label class="form-label small mb-1">Address</label>
              <input type="text" name="address" class="form-control form-control-sm"></div>
            <div class="col-md-3"><label class="form-label small mb-1">City</label><input type="text" name="city" class="form-control form-control-sm"></div>
            <div class="col-md-3"><label class="form-label small mb-1">Contact</label><input type="text" name="contact_phone" class="form-control form-control-sm" placeholder="Phone"></div>
            <div class="col-md-6"><label class="form-label small mb-1">Notes</label><input type="text" name="stop_notes" class="form-control form-control-sm"></div>
            <div class="col-12 d-flex gap-2 justify-content-end pt-2">
              <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#addStopPanel">Cancel</button>
              <button class="btn btn-sm btn-primary"><i class="fas fa-plus me-1"></i>Add</button>
            </div>
          </div>
        </form>
      </div>
    <?php endif; ?>

    <?php if (empty($stops)): ?>
      <p class="text-muted small mb-0 fst-italic">No stops recorded on this trip.</p>
    <?php else: ?>
      <ol class="list-unstyled mb-0 stops-timeline">
        <?php foreach ($stops as $s): ?>
          <?php
            $kindBg  = ['pickup'=>'primary','delivery'=>'success','waypoint'=>'secondary','weighbridge'=>'info','fuel_stop'=>'warning','border'=>'danger','overnight_rest'=>'dark','customer_visit'=>'primary'][$s['kind']] ?? 'secondary';
            $kindIco = ['pickup'=>'fa-box-open','delivery'=>'fa-flag-checkered','waypoint'=>'fa-map-marker-alt','weighbridge'=>'fa-weight-hanging','fuel_stop'=>'fa-gas-pump','border'=>'fa-passport','overnight_rest'=>'fa-bed','customer_visit'=>'fa-handshake'][$s['kind']] ?? 'fa-map-marker-alt';
            $arrived = !empty($s['actual_arrival']);
            $departed = !empty($s['actual_departure']);
            $barColor = $departed ? 'var(--pacific-navy)' : ($arrived ? '#d97706' : '#B8C4D4');
          ?>
          <li class="mb-3 ps-3" style="border-left: 3px solid <?= $barColor; ?>;">
            <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
              <div class="flex-grow-1">
                <span class="badge bg-<?= $kindBg; ?> me-1"><i class="fas <?= $kindIco; ?> fa-xs me-1"></i><?= htmlspecialchars(\TripStops::KINDS[$s['kind']] ?? $s['kind']); ?></span>
                <span class="small text-muted">Stop #<?= (int)$s['seq_no']; ?></span>
                <?php if ($departed): ?><span class="badge bg-success ms-1"><i class="fas fa-check fa-xs me-1"></i>Departed</span>
                <?php elseif ($arrived): ?><span class="badge bg-warning text-dark ms-1"><i class="fas fa-hourglass-half fa-xs me-1"></i>At stop</span>
                <?php else: ?><span class="badge bg-light text-muted border ms-1">Pending</span><?php endif; ?>

                <div class="fw-semibold small"><?= htmlspecialchars($s['location_name'] ?: '—'); ?></div>
                <div class="small text-muted"><?= htmlspecialchars(trim(($s['address'] ?? '') . ($s['city'] ? ', ' . $s['city'] : ''))); ?></div>

                <div class="row g-2 mt-1 small">
                  <?php if ($s['planned_arrival']): ?>
                    <div class="col-sm-6"><span class="text-muted">Planned ETA:</span> <?= humanDateTime($s['planned_arrival']); ?></div>
                  <?php endif; ?>
                  <?php if ($s['actual_arrival']): ?>
                    <div class="col-sm-6"><span class="text-muted">Actual arrival:</span> <?= humanDateTime($s['actual_arrival']); ?><?php if ($s['arrival_odometer']): ?> · <?= number_format((int)$s['arrival_odometer']); ?> km<?php endif; ?></div>
                  <?php endif; ?>
                  <?php if ($s['planned_departure']): ?>
                    <div class="col-sm-6"><span class="text-muted">Planned ETD:</span> <?= humanDateTime($s['planned_departure']); ?></div>
                  <?php endif; ?>
                  <?php if ($s['actual_departure']): ?>
                    <div class="col-sm-6"><span class="text-muted">Actual departure:</span> <?= humanDateTime($s['actual_departure']); ?><?php if ($s['departure_odometer']): ?> · <?= number_format((int)$s['departure_odometer']); ?> km<?php endif; ?></div>
                  <?php endif; ?>
                </div>
                <?php if ($s['stop_notes']): ?><div class="small mt-1"><?= htmlspecialchars($s['stop_notes']); ?></div><?php endif; ?>
              </div>
              <?php if ($canEditStops): ?>
                <div class="d-flex flex-column gap-1">
                  <?php if (!$arrived): ?>
                    <button type="button" class="btn btn-sm btn-outline-warning js-arrive-stop" data-id="<?= (int)$s['c0d']; ?>" data-name="<?= htmlspecialchars($s['location_name'] ?: $s['kind']); ?>"><i class="fas fa-sign-in-alt me-1"></i>Arrived</button>
                  <?php elseif (!$departed): ?>
                    <button type="button" class="btn btn-sm btn-outline-success js-depart-stop" data-id="<?= (int)$s['c0d']; ?>" data-name="<?= htmlspecialchars($s['location_name'] ?: $s['kind']); ?>"><i class="fas fa-sign-out-alt me-1"></i>Departed</button>
                  <?php endif; ?>
                  <button type="button" class="btn btn-sm btn-outline-danger js-del-tstop" data-id="<?= (int)$s['c0d']; ?>"><i class="fas fa-trash"></i></button>
                </div>
              <?php endif; ?>
            </div>
          </li>
        <?php endforeach; ?>
      </ol>
    <?php endif; ?>
  </div>
</div>

<form id="stopActForm" method="POST" action="" class="d-none">
  <?= csrf_field(); ?>
  <input type="hidden" name="odometer" id="stopOdometer">
</form>

<!-- ══ Photos & Documents ══ -->
<?php $atts = $this->data['attachments'] ?? []; ?>
<div class="card border-0 shadow-sm mt-3">
  <div class="card-body">
    <div class="d-flex align-items-center justify-content-between mb-3">
      <h6 class="text-uppercase text-muted small mb-0"><i class="fas fa-images me-1"></i>Photos &amp; Documents <span class="text-muted">· <?= count($atts); ?></span></h6>
      <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#uploadPanel"><i class="fas fa-camera me-1"></i>Upload photo</button>
    </div>

    <div id="uploadPanel" class="collapse mb-3">
      <form method="POST" enctype="multipart/form-data" action="<?= PROOT; ?>TripAttachments/upload/<?= (int)$t['c0d']; ?>" class="border rounded p-3 bg-light">
        <?= csrf_field(); ?>
        <div class="row g-2">
          <div class="col-md-4"><label class="form-label small mb-1">Category</label>
            <select name="category" class="form-select form-select-sm">
              <?php foreach (TripAttachments::CATEGORIES as $k=>$v): ?>
                <option value="<?= $k; ?>"><?= htmlspecialchars($v); ?></option>
              <?php endforeach; ?>
            </select></div>
          <div class="col-md-4"><label class="form-label small mb-1">Photo <span class="text-danger">*</span></label>
            <input type="file" name="photo" class="form-control form-control-sm" accept="image/jpeg,image/png,image/webp,image/heic" required></div>
          <div class="col-md-4"><label class="form-label small mb-1">Caption</label>
            <input type="text" name="caption" class="form-control form-control-sm" maxlength="255"></div>
          <div class="col-12 d-flex justify-content-end gap-2 mt-2">
            <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#uploadPanel">Cancel</button>
            <button class="btn btn-sm btn-primary"><i class="fas fa-upload me-1"></i>Upload</button>
          </div>
        </div>
      </form>
    </div>

    <?php if (empty($atts)): ?>
      <p class="text-muted small mb-0 fst-italic">No photos on this trip yet. Photos-on-start (plates, cargo, odometer) are captured by the mobile app when the driver starts the trip.</p>
    <?php else: ?>
      <div class="row g-2">
        <?php foreach ($atts as $a):
            $isImg = strpos((string)$a['mime_type'], 'image/') === 0;
            $label = TripAttachments::label($a['category']);
            $badgeBg = in_array($a['category'], TripAttachments::START_CATEGORIES, true) ? 'success' : 'info';
        ?>
          <div class="col-6 col-md-4 col-lg-3">
            <div class="border rounded overflow-hidden position-relative bg-light" style="aspect-ratio:1/1;">
              <?php if ($isImg): ?>
                <a href="<?= htmlspecialchars($a['file_url']); ?>" target="_blank" rel="noopener" title="<?= htmlspecialchars(($a['caption'] ?? '') ?: $label); ?>">
                  <img src="<?= htmlspecialchars($a['file_url']); ?>" alt="<?= htmlspecialchars($label); ?>" style="width:100%;height:100%;object-fit:cover;">
                </a>
              <?php else: ?>
                <a href="<?= htmlspecialchars($a['file_url']); ?>" target="_blank" rel="noopener" class="d-flex align-items-center justify-content-center text-decoration-none h-100">
                  <div class="text-center text-muted"><i class="fas fa-file fa-2x mb-1"></i><div class="small"><?= htmlspecialchars($a['file_name'] ?: 'file'); ?></div></div>
                </a>
              <?php endif; ?>
              <span class="badge bg-<?= $badgeBg; ?> position-absolute top-0 start-0 m-1" style="font-size:.6rem;"><?= htmlspecialchars($label); ?></span>
              <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 py-0 px-1 js-del-att"
                      data-id="<?= (int)$a['c0d']; ?>" data-name="<?= htmlspecialchars($label); ?>" style="font-size:.6rem;"><i class="fas fa-trash"></i></button>
            </div>
            <div class="small text-muted mt-1">
              <?php if ($a['caption']): ?><div class="text-truncate" title="<?= htmlspecialchars($a['caption']); ?>"><?= htmlspecialchars($a['caption']); ?></div><?php endif; ?>
              <?= humanDateTime($a['created_on']); ?>
              <?php if ($a['source'] === 'mobile' && $a['driver_name']): ?> · <i class="fas fa-mobile-alt fa-xs" title="Uploaded via mobile by <?= htmlspecialchars($a['driver_name']); ?>"></i><?php endif; ?>
              <?php if ($a['taken_lat']): ?> · <a href="https://www.google.com/maps/search/?api=1&query=<?= (float)$a['taken_lat']; ?>,<?= (float)$a['taken_lng']; ?>" target="_blank" rel="noopener" title="<?= number_format((float)$a['taken_lat'],5); ?>, <?= number_format((float)$a['taken_lng'],5); ?>"><i class="fas fa-map-marker-alt fa-xs"></i></a><?php endif; ?>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<form id="delAttForm" method="POST" action="" class="d-none"><?= csrf_field(); ?></form>

<!-- Hidden forms for POST actions -->
<form id="actForm" method="POST" action="" class="d-none">
  <?= csrf_field(); ?>
  <input type="hidden" name="odometer_start" id="fOdoStart">
  <input type="hidden" name="odometer_end"   id="fOdoEnd">
  <input type="hidden" name="invoice_amount" id="fInvoice">
  <input type="hidden" name="notes"          id="fNotes">
  <input type="hidden" name="cancel_reason"  id="fCancelReason">
</form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
const TRIP_ID = <?= (int)$t['c0d']; ?>;
const PROOT   = '<?= PROOT; ?>';

function submitAct(kind, extra) {
    const f = document.getElementById('actForm');
    f.action = PROOT + 'Trips/' + kind + '/' + TRIP_ID;
    if (extra) for (const [k, v] of Object.entries(extra)) {
        const el = document.getElementById('f' + k.replace(/_(\w)/g, (_, c) => c.toUpperCase()).replace(/^./, c => c.toUpperCase()));
        if (el) el.value = v;
    }
    f.submit();
}

function doAction(kind, title, msg, btn, cls, colour) {
    $.confirm({
        title: title, content: msg, type: colour,
        buttons: { go: { text: btn, btnClass: cls, action: () => submitAct(kind) }, cancel: function(){} }
    });
}

function doStart() {
    $.confirm({
        title: 'Start trip?',
        content: '<label class="form-label small">Odometer at start (km)</label><input type="text" id="odoStart" class="form-control form-control-sm" placeholder="Optional but recommended">',
        type: 'blue',
        buttons: {
            start: { text: 'Start trip', btnClass: 'btn-primary', action: function() {
                const odo = document.getElementById('odoStart').value.replace(/,/g,'');
                submitAct('start', { odometer_start: odo });
            }},
            cancel: function(){}
        }
    });
}

function doClose() {
    $.confirm({
        title: 'Close trip?',
        content: `
            <label class="form-label small">Odometer at end (km)</label>
            <input type="text" id="odoEnd" class="form-control form-control-sm mb-2">
            <label class="form-label small">Invoice amount</label>
            <input type="text" id="invAmt" class="form-control form-control-sm mb-2" value="<?= (float)$t['quote_amount']; ?>">
            <label class="form-label small">Notes</label>
            <textarea id="closeNotes" class="form-control form-control-sm" rows="2"></textarea>
        `,
        type: 'green',
        onContentReady: function() {
            const inv = document.getElementById('invAmt');
            const odo = document.getElementById('odoEnd');
            if (typeof Cleave !== 'undefined') {
                if (inv) new Cleave(inv, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 2 });
                if (odo) new Cleave(odo, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 0 });
            }
        },
        buttons: {
            close: { text: 'Close trip', btnClass: 'btn-success', action: function() {
                submitAct('close', {
                    odometer_end:   document.getElementById('odoEnd').value.replace(/,/g,''),
                    invoice_amount: document.getElementById('invAmt').value.replace(/,/g,''),
                    notes:          document.getElementById('closeNotes').value
                });
            }},
            cancel: function(){}
        }
    });
}

function doCancel() {
    $.confirm({
        title: 'Cancel trip?',
        content: '<label class="form-label small">Reason</label><textarea id="cancelReason" class="form-control form-control-sm" rows="3"></textarea>',
        type: 'red',
        buttons: {
            cancel: { text: 'Cancel trip', btnClass: 'btn-danger', action: function() {
                const r = document.getElementById('cancelReason').value.trim();
                if (!r) { $.alert('Please enter a reason.'); return false; }
                submitAct('cancel', { cancel_reason: r });
            }},
            back: { text: 'Back' }
        }
    });
}

/* ── Stop actions: arrive / depart / delete ────────────────────── */
function stopAct(verb, id, name) {
    const cfg = {
        arrive: { title: 'Mark arrival at ' + name + '?', ok: 'Arrived', cls: 'btn-warning', col: 'orange' },
        depart: { title: 'Mark departure from ' + name + '?', ok: 'Departed', cls: 'btn-success', col: 'green' }
    }[verb];
    $.confirm({
        title: cfg.title,
        content: '<label class="form-label small">Odometer (optional but recommended)</label><input type="text" id="stopOdoIn" class="form-control form-control-sm">',
        type: cfg.col,
        onContentReady: function(){ const el = document.getElementById('stopOdoIn'); if (el && typeof Cleave !== 'undefined') new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 0 }); },
        buttons: {
            go: { text: cfg.ok, btnClass: cfg.cls, action: function() {
                const odo = (document.getElementById('stopOdoIn').value || '').replace(/,/g,'');
                const f = document.getElementById('stopActForm');
                f.action = PROOT + 'Trips/' + verb + 'Stop/' + id;
                document.getElementById('stopOdometer').value = odo;
                f.submit();
            }},
            back: function(){}
        }
    });
}
document.querySelectorAll('.js-arrive-stop').forEach(btn => btn.addEventListener('click', () => stopAct('arrive', btn.getAttribute('data-id'), btn.getAttribute('data-name'))));
document.querySelectorAll('.js-depart-stop').forEach(btn => btn.addEventListener('click', () => stopAct('depart', btn.getAttribute('data-id'), btn.getAttribute('data-name'))));
document.querySelectorAll('.js-del-tstop').forEach(btn => btn.addEventListener('click', function(){
    const id = btn.getAttribute('data-id');
    $.confirm({ title: 'Remove stop?', content: 'Remove this stop from the trip?', type: 'red',
        buttons: { remove: { text: 'Remove', btnClass: 'btn-danger', action: function() {
            const f = document.getElementById('stopActForm');
            f.action = PROOT + 'Trips/deleteStop/' + id; f.submit();
        }}, back: function(){} }
    });
}));

// Delete photo attachment
document.querySelectorAll('.js-del-att').forEach(btn => btn.addEventListener('click', function(){
    const id = btn.getAttribute('data-id'); const name = btn.getAttribute('data-name');
    $.confirm({ title: 'Remove photo?', content: 'Remove <strong>' + name + '</strong>?', type: 'red',
        buttons: { remove: { text: 'Remove', btnClass: 'btn-danger', action: function() {
            const f = document.getElementById('delAttForm');
            f.action = PROOT + 'TripAttachments/delete/' + id; f.submit();
        }}, back: function(){} }
    });
}));
</script>
<?php $this->end(); ?>
