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

<?php
  $statusBg = ['draft'=>'secondary','pending_review'=>'warning','approved'=>'success','rejected'=>'danger','cancelled'=>'dark','dispatched'=>'primary'][$tr['status']] ?? 'secondary';
  $prioBg   = ['low'=>'light','normal'=>'light','high'=>'warning','urgent'=>'danger'][$tr['priority']] ?? 'light';
?>

<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-clipboard-list me-2 text-muted"></i><?= htmlspecialchars($tr['request_no']); ?>
      <span class="badge bg-<?= $statusBg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ',$tr['status'])); ?></span>
      <?php if ($tr['priority'] !== 'normal'): ?>
        <span class="badge bg-<?= $prioBg; ?> <?= $tr['priority']==='urgent'?'text-white':'text-dark'; ?> ms-1" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars($tr['priority']); ?></span>
      <?php endif; ?>
    </h5>
    <div class="text-muted small">
      <?php if ($tr['customer_name']): ?><a href="<?= PROOT; ?>Customers/view/<?= (int)$tr['customer_id']; ?>"><?= htmlspecialchars($tr['customer_name']); ?></a>
      <?php else: ?><em>Internal request</em><?php endif; ?>
      <?php if ($tr['route_name']): ?> · <a href="<?= PROOT; ?>Routes/view/<?= (int)$tr['route_id']; ?>"><?= htmlspecialchars($tr['route_name']); ?></a><?php endif; ?>
    </div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a href="<?= PROOT; ?>TripRequests" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    <?php if (!in_array($tr['status'], ['dispatched','rejected','cancelled'], true)): ?>
      <a href="<?= PROOT; ?>TripRequests/edit/<?= (int)$tr['c0d']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-pen me-1"></i>Edit</a>
    <?php endif; ?>
  </div>
</div>

<?= flashHtml(); ?>

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

<!-- ── Status transitions ─────────────────────────────────── -->
<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 ($tr['status'] === 'draft'): ?>
      <button type="button" class="btn btn-sm btn-primary"  onclick="doAction('submit')"><i class="fas fa-paper-plane me-1"></i>Submit for review</button>
    <?php endif; ?>

    <?php if ($tr['status'] === 'pending_review'): ?>
      <button type="button" class="btn btn-sm btn-success"  onclick="doAction('approve')"><i class="fas fa-check me-1"></i>Approve</button>
      <button type="button" class="btn btn-sm btn-danger"   onclick="doReject()"><i class="fas fa-times me-1"></i>Reject</button>
    <?php endif; ?>

    <?php if (in_array($tr['status'], ['draft','pending_review','approved'], true)): ?>
      <button type="button" class="btn btn-sm btn-outline-secondary" onclick="doAction('cancel')"><i class="fas fa-ban me-1"></i>Cancel request</button>
    <?php endif; ?>

    <?php if ($tr['status'] === 'approved'): ?>
      <a href="<?= PROOT; ?>Trips/board" class="btn btn-sm btn-primary">
        <i class="fas fa-truck-loading me-1"></i>Dispatch as Trip
        <i class="fas fa-arrow-right ms-1"></i>
      </a>
    <?php elseif ($tr['status'] === 'dispatched'): ?>
      <a href="<?= PROOT; ?>Trips?q=<?= urlencode($tr['request_no']); ?>" class="btn btn-sm btn-outline-primary">
        <i class="fas fa-truck-loading me-1"></i>View trip
      </a>
    <?php endif; ?>

    <span class="ms-auto text-muted small">
      Requested by user #<?= (int)$tr['requested_by']; ?> · <?= humanDateTime($tr['requested_at']); ?>
    </span>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Cargo &amp; Route</h6>
        <dl class="row mb-0">
          <dt class="col-5 text-muted fw-normal">Cargo type</dt>  <dd class="col-7"><?= htmlspecialchars(ucwords(str_replace('_',' ',$tr['cargo_type']))); ?></dd>
          <dt class="col-5 text-muted fw-normal">Description</dt> <dd class="col-7"><?= htmlspecialchars($tr['cargo_description'] ?: '—'); ?></dd>
          <?php if ($tr['weight_kg']):      ?><dt class="col-5 text-muted fw-normal">Weight</dt>   <dd class="col-7"><?= number_format((float)$tr['weight_kg'], 0, '.', ',') . ' kg'; ?></dd><?php endif; ?>
          <?php if ($tr['volume_m3']):      ?><dt class="col-5 text-muted fw-normal">Volume</dt>   <dd class="col-7"><?= number_format((float)$tr['volume_m3'], 2) . ' m³'; ?></dd><?php endif; ?>
          <?php if ($tr['packages_count']): ?><dt class="col-5 text-muted fw-normal">Packages</dt> <dd class="col-7"><?= number_format((int)$tr['packages_count']); ?></dd><?php endif; ?>

          <dt class="col-5 text-muted fw-normal">Pickup address</dt>   <dd class="col-7"><?= htmlspecialchars($tr['origin_address']      ?: '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Delivery address</dt> <dd class="col-7"><?= htmlspecialchars($tr['destination_address'] ?: '—'); ?></dd>
          <?php if ($tr['route_name']): ?>
            <dt class="col-5 text-muted fw-normal">Route</dt>
            <dd class="col-7"><a href="<?= PROOT; ?>Routes/view/<?= (int)$tr['route_id']; ?>"><?= htmlspecialchars($tr['route_name']); ?></a>
              <?php if ($tr['route_distance']): ?> <span class="text-muted small">· <?= number_format((float)$tr['route_distance'],0); ?> km</span><?php endif; ?></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3"><i class="fas fa-calendar me-1"></i>Schedule</h6>
        <dl class="row mb-0">
          <dt class="col-5 text-muted fw-normal">Pickup</dt>  <dd class="col-7"><?= $tr['pickup_date']   ? humanDate($tr['pickup_date'])   . ' ' . ($tr['pickup_time']   ?: '') : '—'; ?></dd>
          <dt class="col-5 text-muted fw-normal">Delivery</dt><dd class="col-7"><?= $tr['delivery_date'] ? humanDate($tr['delivery_date']) . ' ' . ($tr['delivery_time'] ?: '') : '—'; ?></dd>
        </dl>
      </div>
    </div>

    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3"><i class="fas fa-money-bill me-1"></i>Pricing</h6>
        <dl class="row mb-0">
          <dt class="col-5 text-muted fw-normal">Quote amount</dt>
          <dd class="col-7"><?= $tr['quote_amount']
              ? htmlspecialchars($tr['currency']) . ' ' . number_format((float)$tr['quote_amount'], 2, '.', ',')
              : '<span class="text-muted">Not quoted</span>'; ?></dd>
          <?php if ($tr['customer_id']): ?>
            <dt class="col-5 text-muted fw-normal">Customer contact</dt>
            <dd class="col-7 small"><?= htmlspecialchars($tr['customer_poc'] ?: '—'); ?>
              <?php if ($tr['customer_poc_phone']): ?> · <?= htmlspecialchars($tr['customer_poc_phone']); ?><?php endif; ?></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>

    <?php if (!empty($tr['notes'])): ?>
      <div class="card border-0 shadow-sm">
        <div class="card-body">
          <h6 class="text-uppercase text-muted small mb-2">Notes</h6>
          <p class="mb-0 small"><?= nl2br(htmlspecialchars($tr['notes'])); ?></p>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- ── Cargo Items (itemization) ─────────────────────────────────── -->
<?php $items = $this->data['cargo_items']; $sums = $this->data['cargo_sums']; $canEdit = !in_array($tr['status'], ['dispatched','rejected','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-boxes me-1"></i>Cargo Items
        <span class="text-muted">· <?= count($items); ?><?php if ((float)$sums['total_weight'] > 0): ?> · <?= number_format((float)$sums['total_weight'], 0, '.', ','); ?> kg total<?php endif; ?><?php if ((float)$sums['total_volume'] > 0): ?> · <?= number_format((float)$sums['total_volume'], 2); ?> m³ total<?php endif; ?></span>
      </h6>
      <?php if ($canEdit): ?>
        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#addCargoPanel"><i class="fas fa-plus me-1"></i>Add item</button>
      <?php endif; ?>
    </div>

    <?php if ($canEdit): ?>
      <div id="addCargoPanel" class="collapse mb-3">
        <form method="POST" action="<?= PROOT; ?>TripRequests/addCargoItem/<?= (int)$tr['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">Item name <span class="text-danger">*</span></label>
              <input type="text" name="item_name" class="form-control form-control-sm" required placeholder="e.g. Portland cement 50kg bags"></div>
            <div class="col-md-1"><label class="form-label small mb-1">Qty</label>
              <input type="text" name="qty" class="form-control form-control-sm js-num" value="1"></div>
            <div class="col-md-2"><label class="form-label small mb-1">UoM</label>
              <select name="uom" class="form-select form-select-sm">
                <?php foreach (['units','bags','pallets','containers','kg','tons','liters','boxes','drums'] as $u): ?>
                  <option value="<?= $u; ?>"><?= ucfirst($u); ?></option>
                <?php endforeach; ?>
              </select></div>
            <div class="col-md-2"><label class="form-label small mb-1">Weight (kg)</label>
              <input type="text" name="weight_kg" class="form-control form-control-sm js-num"></div>
            <div class="col-md-1"><label class="form-label small mb-1">Volume (m³)</label>
              <input type="text" name="volume_m3" class="form-control form-control-sm js-num"></div>
            <div class="col-md-2"><label class="form-label small mb-1">Packaging</label>
              <input type="text" name="packaging" class="form-control form-control-sm" placeholder="Shrink-wrapped"></div>
            <div class="col-md-8"><label class="form-label small mb-1">Handling notes</label>
              <input type="text" name="handling_notes" class="form-control form-control-sm" placeholder="Fragile · hazardous · cold chain · keep upright"></div>
            <div class="col-md-2"><label class="form-label small mb-1">Unit value (optional)</label>
              <input type="text" name="unit_value" class="form-control form-control-sm js-money"></div>
            <div class="col-md-2 d-flex align-items-end gap-2">
              <button type="button" class="btn btn-sm btn-outline-secondary flex-grow-1" data-bs-toggle="collapse" data-bs-target="#addCargoPanel">Cancel</button>
              <button class="btn btn-sm btn-primary"><i class="fas fa-plus"></i></button>
            </div>
          </div>
        </form>
      </div>
    <?php endif; ?>

    <?php if (empty($items)): ?>
      <p class="text-muted small mb-0 fst-italic">No itemized cargo yet — the header description above is treated as a single-item load.</p>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-sm align-middle mb-0">
          <thead class="table-light">
            <tr><th style="width:40px;">#</th><th>Item</th><th>Qty · UoM</th><th class="money">Weight</th><th class="money">Volume</th><th>Packaging · Handling</th><th class="text-end"></th></tr>
          </thead>
          <tbody>
            <?php foreach ($items as $it): ?>
              <tr>
                <td class="small text-muted"><?= (int)$it['seq_no']; ?></td>
                <td class="small"><strong><?= htmlspecialchars($it['item_name']); ?></strong></td>
                <td class="small"><?= number_format((float)$it['qty'], (float)$it['qty'] == (int)$it['qty'] ? 0 : 2); ?> <?= htmlspecialchars($it['uom']); ?></td>
                <td class="money small"><?= $it['weight_kg'] ? number_format((float)$it['weight_kg'], 0, '.', ',') . ' kg' : '—'; ?></td>
                <td class="money small"><?= $it['volume_m3'] ? number_format((float)$it['volume_m3'], 2) . ' m³' : '—'; ?></td>
                <td class="small">
                  <?php if ($it['packaging']): ?><?= htmlspecialchars($it['packaging']); ?><?php endif; ?>
                  <?php if ($it['handling_notes']): ?><div class="text-muted"><?= htmlspecialchars($it['handling_notes']); ?></div><?php endif; ?>
                </td>
                <td class="text-end">
                  <?php if ($canEdit): ?>
                    <button type="button" class="btn btn-sm btn-outline-danger js-del-cargo" data-id="<?= (int)$it['c0d']; ?>" data-name="<?= htmlspecialchars($it['item_name']); ?>"><i class="fas fa-trash"></i></button>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- ── Planned Stops (route breakdown) ────────────────────────── -->
<?php $stops = $this->data['stops']; ?>
<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>Planned Stops
        <span class="text-muted">· <?= count($stops); ?></span>
      </h6>
      <?php if ($canEdit): ?>
        <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 ($canEdit): ?>
      <div id="addStopPanel" class="collapse mb-3">
        <form method="POST" action="<?= PROOT; ?>TripRequests/addStop/<?= (int)$tr['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 name</label>
              <input type="text" name="location_name" class="form-control form-control-sm" placeholder="e.g. Twiga Cement Plant"></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 name</label>
              <input type="text" name="contact_name" class="form-control form-control-sm"></div>
            <div class="col-md-3"><label class="form-label small mb-1">Contact phone</label>
              <input type="text" name="contact_phone" class="form-control form-control-sm"></div>
            <div class="col-md-3"><label class="form-label small mb-1">Country</label>
              <input type="text" name="country" class="form-control form-control-sm" value="TANZANIA"></div>

            <div class="col-md-3"><label class="form-label small mb-1">Planned arrival</label>
              <input type="datetime-local" name="planned_arrival" class="form-control form-control-sm"></div>
            <div class="col-md-3"><label class="form-label small mb-1">Planned departure</label>
              <input type="datetime-local" name="planned_departure" class="form-control form-control-sm"></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 stop</button>
            </div>
          </div>
        </form>
      </div>
    <?php endif; ?>

    <?php if (empty($stops)): ?>
      <p class="text-muted small mb-0 fst-italic">No stops planned yet — the origin/destination addresses above will be used as pickup/delivery.</p>
    <?php else: ?>
      <ol class="list-unstyled mb-0">
        <?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';
          ?>
          <li class="mb-3 ps-3" style="border-left: 3px solid var(--pacific-navy);">
            <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
              <div>
                <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>
                <div class="fw-semibold small"><?= htmlspecialchars($s['location_name'] ?: '—'); ?></div>
                <div class="small text-muted"><?= htmlspecialchars(trim(($s['address'] ?? '') . ($s['city'] ? ', ' . $s['city'] : ''))); ?></div>
                <?php if ($s['contact_name'] || $s['contact_phone']): ?>
                  <div class="small"><i class="fas fa-user fa-xs me-1 text-muted"></i><?= htmlspecialchars($s['contact_name']); ?><?php if ($s['contact_phone']): ?> · <?= htmlspecialchars($s['contact_phone']); ?><?php endif; ?></div>
                <?php endif; ?>
                <?php if ($s['planned_arrival'] || $s['planned_departure']): ?>
                  <div class="small text-muted mt-1">
                    <?php if ($s['planned_arrival']):   ?><i class="fas fa-sign-in-alt fa-xs me-1"></i>ETA <?= humanDateTime($s['planned_arrival']); ?><?php endif; ?>
                    <?php if ($s['planned_departure']): ?> <i class="fas fa-sign-out-alt fa-xs ms-2 me-1"></i>ETD <?= humanDateTime($s['planned_departure']); ?><?php endif; ?>
                  </div>
                <?php endif; ?>
                <?php if ($s['stop_notes']): ?><div class="small mt-1"><?= htmlspecialchars($s['stop_notes']); ?></div><?php endif; ?>
              </div>
              <?php if ($canEdit): ?>
                <button type="button" class="btn btn-sm btn-outline-danger js-del-stop" data-id="<?= (int)$s['c0d']; ?>" data-name="<?= htmlspecialchars($s['location_name'] ?: $s['kind']); ?>"><i class="fas fa-trash"></i></button>
              <?php endif; ?>
            </div>
          </li>
        <?php endforeach; ?>
      </ol>
    <?php endif; ?>
  </div>
</div>

<!-- Hidden delete forms for cargo items and stops -->
<form id="delCargoForm" method="POST" action="" class="d-none"><?= csrf_field(); ?></form>
<form id="delStopForm"  method="POST" action="" class="d-none"><?= csrf_field(); ?></form>

<div class="text-end mt-3">
  <button type="button" class="btn btn-sm btn-outline-danger" onclick="doDelete()"><i class="fas fa-trash me-1"></i>Delete record</button>
</div>

<!-- Hidden action forms — submitted by JS after user confirms in jQuery-confirm -->
<form id="actForm" method="POST" action="" class="d-none"><?= csrf_field(); ?><input type="hidden" name="reject_reason" id="actReason"></form>
<form id="delForm" method="POST" action="<?= PROOT; ?>TripRequests/delete/<?= (int)$tr['c0d']; ?>" class="d-none"><?= csrf_field(); ?></form>

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

document.querySelectorAll('.js-num').forEach(el   => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 3 }));
document.querySelectorAll('.js-money').forEach(el => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 2 }));

document.querySelectorAll('.js-del-cargo').forEach(btn => btn.addEventListener('click', function() {
    const id = btn.getAttribute('data-id'); const name = btn.getAttribute('data-name');
    $.confirm({ title: 'Remove cargo item?', content: 'Remove <strong>' + name + '</strong>?', type: 'red',
        buttons: { remove: { text: 'Remove', btnClass: 'btn-danger', action: function() {
            const f = document.getElementById('delCargoForm');
            f.action = PROOT + 'TripRequests/deleteCargoItem/' + id; f.submit();
        }}, back: function(){} }
    });
}));

document.querySelectorAll('.js-del-stop').forEach(btn => btn.addEventListener('click', function() {
    const id = btn.getAttribute('data-id'); const name = btn.getAttribute('data-name');
    $.confirm({ title: 'Remove stop?', content: 'Remove <strong>' + name + '</strong>?', type: 'red',
        buttons: { remove: { text: 'Remove', btnClass: 'btn-danger', action: function() {
            const f = document.getElementById('delStopForm');
            f.action = PROOT + 'TripRequests/deleteStop/' + id; f.submit();
        }}, back: function(){} }
    });
}));

function doAction(kind) {
    const map = {
        submit:  { title: 'Submit for review?', msg: 'Ops Manager will review and either approve or reject.', btn: 'Submit',  cls: 'btn-primary' },
        approve: { title: 'Approve this request?', msg: 'The request will move to <strong>approved</strong> and become eligible for trip dispatch.', btn: 'Approve', cls: 'btn-success' },
        cancel:  { title: 'Cancel this request?',  msg: 'Marks the request as cancelled. History is preserved.', btn: 'Cancel request', cls: 'btn-outline-secondary' }
    }[kind];
    $.confirm({
        title: map.title, content: map.msg, type: kind==='approve' ? 'green' : (kind==='cancel' ? 'orange' : 'blue'),
        buttons: {
            go: { text: map.btn, btnClass: map.cls, action: function () {
                const f = document.getElementById('actForm');
                f.action = PROOT + 'TripRequests/' + kind + '/' + REQ_ID;
                f.submit();
            }},
            cancel: function () {}
        }
    });
}

function doReject() {
    $.confirm({
        title: 'Reject this request?',
        content: '<label class="form-label">Reason for rejection</label><textarea class="form-control" id="reasonField" rows="3" placeholder="Why is this being rejected?"></textarea>',
        type: 'red',
        buttons: {
            reject: { text: 'Reject', btnClass: 'btn-danger', action: function () {
                const reason = document.getElementById('reasonField').value.trim();
                if (!reason) { $.alert('Please enter a reason.'); return false; }
                const f = document.getElementById('actForm');
                f.action = PROOT + 'TripRequests/reject/' + REQ_ID;
                document.getElementById('actReason').value = reason;
                f.submit();
            }},
            cancel: function () {}
        }
    });
}

function doDelete() {
    $.confirm({
        title: 'Delete request record?',
        content: 'Soft-deletes the request entirely. Prefer <em>Cancel</em> for open requests — cancellation preserves history in the register.',
        type: 'red',
        buttons: {
            remove: { text: 'Delete', btnClass: 'btn-danger', action: () => document.getElementById('delForm').submit() },
            cancel: function () {}
        }
    });
}
</script>
<?php $this->end(); ?>
