<?php
declare(strict_types=1);
/**
 * modules/bookings/edit.php
 *
 * Edit a booking (base fields + multi vehicle/driver assignments).
 * - Booking ref handling
 * - Assignments save/delete/reinsert
 * - Corporate clients dropdown
 * - NO transaction writes (handled by complete.php and driver payments)
 */
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops']);

/* NEW: keep pending_payments in sync when a booking changes */
require_once dirname(__DIR__) . '/payments/pending_sync.php';

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) redirect('list.php');

/* ---------------- Load booking ---------------- */
$bk = db()->prepare("SELECT b.* FROM bookings b WHERE b.id=:id AND b.company_id=:cid LIMIT 1");
$bk->execute([':id'=>$id, ':cid'=>$cid]);
$booking = $bk->fetch();
if (!$booking) redirect('list.php');

/* Load assignments */
$as = db()->prepare("
  SELECT bv.*, d.name AS driver_name, v.reg_no AS v_reg_no, v.type AS v_type
  FROM booking_vehicles bv
  LEFT JOIN drivers d ON d.id=bv.driver_id
  LEFT JOIN vehicles v ON v.id=bv.vehicle_id
  WHERE bv.booking_id=:bid
  ORDER BY bv.sequence_order ASC, bv.id ASC
");
$as->execute([':bid'=>$id]);
$assignments = $as->fetchAll();

/* Lookups */
$partners = db()->prepare("SELECT id, name FROM partners WHERE company_id=:cid ORDER BY name");
$partners->execute([':cid'=>$cid]);
$partners = $partners->fetchAll();

$corporates = db()->prepare("SELECT id, name FROM corporates WHERE company_id=:cid AND status='active' ORDER BY name");
$corporates->execute([':cid'=>$cid]);
$corporates = $corporates->fetchAll();

$driversStmt = db()->prepare("SELECT id, name, phone, own_vehicle_reg_no, own_vehicle_type FROM drivers WHERE company_id=:cid AND is_active=1 ORDER BY name");
$driversStmt->execute([':cid'=>$cid]);
$drivers = $driversStmt->fetchAll();

$vehiclesStmt = db()->prepare("SELECT id, reg_no, type FROM vehicles WHERE company_id=:cid ORDER BY reg_no");
$vehiclesStmt->execute([':cid'=>$cid]);
$vehicles = $vehiclesStmt->fetchAll();

$errors = [];
$notice = null;

/* ---------------- Save ---------------- */
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='save') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    // Inputs
    $pickup_date_in = trim((string)($_POST['pickup_date'] ?? ''));
    $booking_ref_in = trim((string)($_POST['booking_ref'] ?? ''));
    $autoRef = ($booking_ref_in === '');

    $genDate = $pickup_date_in !== '' ? $pickup_date_in : ($booking['pickup_date'] ?: date('Y-m-d'));

    $partner_id   = (int)($_POST['partner_id'] ?? 0) ?: null;
    $corporate_id = (int)($_POST['corporate_id'] ?? 0) ?: null;
    $booking_type = in_array(($_POST['booking_type'] ?? ''), ['Transfer','As Directed'], true) ? $_POST['booking_type'] : 'Transfer';
    $hours        = ($_POST['hours'] ?? '') !== '' ? (float)$_POST['hours'] : null;

    $client_name  = trim((string)($_POST['client_name'] ?? ''));
    $client_phone = trim((string)($_POST['client_phone'] ?? ''));
    $client_email = trim((string)($_POST['client_email'] ?? ''));

    $pickup_date    = $pickup_date_in;
    $pickup_time    = trim((string)($_POST['pickup_time'] ?? ''));
    $pickup_address = trim((string)($_POST['pickup_address'] ?? ''));
    $via            = trim((string)($_POST['via'] ?? ''));
    $dropoff        = trim((string)($_POST['dropoff_address'] ?? ''));
    $flight_number  = trim((string)($_POST['flight_number'] ?? ''));

    $pax_count     = (int)($_POST['pax_count'] ?? 0);
    $luggage_count = (int)($_POST['luggage_count'] ?? 0);

    $total_client_price = (float)($_POST['total_client_price'] ?? 0.00);
    $total_driver_price = (float)($_POST['total_driver_price'] ?? 0.00);

    $client_parking_fee = (float)($_POST['client_parking_fee'] ?? 0.00);
    $client_waiting_fee = (float)($_POST['client_waiting_fee'] ?? 0.00);
    $driver_parking_fee = (float)($_POST['driver_parking_fee'] ?? 0.00);
    $driver_waiting_fee = (float)($_POST['driver_waiting_fee'] ?? 0.00);

    $partner_commission_amount = (float)($_POST['partner_commission_amount'] ?? 0.00);

    $status = in_array(($_POST['status'] ?? ''), ['New','Confirmed','Assigned','InProgress','Completed','Invoiced','Paid'], true)
      ? $_POST['status'] : ($booking['status'] ?? 'New');

    $notes = trim((string)($_POST['notes'] ?? ''));

    // booking_ref uniqueness
    $dupCheck = db()->prepare("SELECT id FROM bookings WHERE company_id=:cid AND booking_ref=:ref AND id<>:id LIMIT 1");

    if ($autoRef) {
      $attempts = 0;
      do {
        $booking_ref = generate_booking_ref($cid, $genDate);
        $dupCheck->execute([':cid'=>$cid, ':ref'=>$booking_ref, ':id'=>$id]);
        $exists = $dupCheck->fetch();
        $attempts++;
      } while ($exists && $attempts < 10);
      if ($exists) $errors[] = 'Unable to generate a unique booking reference.';
    } else {
      $booking_ref = $booking_ref_in;
      $dupCheck->execute([':cid'=>$cid, ':ref'=>$booking_ref, ':id'=>$id]);
      if ($dupCheck->fetch()) $errors[] = 'Booking reference already exists.';
    }

    if (!$errors) {
      db()->beginTransaction();

      /* --- Update booking --- */
      $upd = db()->prepare("
        UPDATE bookings
           SET booking_ref=:booking_ref,
               partner_id=:partner_id,
               corporate_id=:corporate_id,
               booking_type=:booking_type,
               hours=:hours,
               client_name=:client_name,
               client_phone=:client_phone,
               client_email=:client_email,
               pickup_date=:pickup_date,
               pickup_time=:pickup_time,
               pickup_address=:pickup_address,
               via=:via,
               dropoff_address=:dropoff_address,
               flight_number=:flight_number,
               pax_count=:pax_count,
               luggage_count=:luggage_count,
               total_client_price=:total_client_price,
               total_driver_price=:total_driver_price,
               client_parking_fee=:client_parking_fee,
               client_waiting_fee=:client_waiting_fee,
               driver_parking_fee=:driver_parking_fee,
               driver_waiting_fee=:driver_waiting_fee,
               partner_commission_amount=:partner_commission_amount,
               status=:status,
               notes=:notes
         WHERE id=:id AND company_id=:cid
      ");
      $upd->execute([
        ':booking_ref'=>$booking_ref,
        ':partner_id'=>$partner_id,
        ':corporate_id'=>$corporate_id,
        ':booking_type'=>$booking_type,
        ':hours'=>$hours,
        ':client_name'=>$client_name !== '' ? $client_name : null,
        ':client_phone'=>$client_phone !== '' ? $client_phone : null,
        ':client_email'=>$client_email !== '' ? $client_email : null,
        ':pickup_date'=>$pickup_date !== '' ? $pickup_date : null,
        ':pickup_time'=>$pickup_time !== '' ? $pickup_time : null,
        ':pickup_address'=>$pickup_address !== '' ? $pickup_address : null,
        ':via'=>$via !== '' ? $via : null,
        ':dropoff_address'=>$dropoff !== '' ? $dropoff : null,
        ':flight_number'=>$flight_number !== '' ? $flight_number : null,
        ':pax_count'=>$pax_count,
        ':luggage_count'=>$luggage_count,
        ':total_client_price'=>$total_client_price,
        ':total_driver_price'=>$total_driver_price,
        ':client_parking_fee'=>$client_parking_fee,
        ':client_waiting_fee'=>$client_waiting_fee,
        ':driver_parking_fee'=>$driver_parking_fee,
        ':driver_waiting_fee'=>$driver_waiting_fee,
        ':partner_commission_amount'=>$partner_commission_amount,
        ':status'=>$status,
        ':notes'=>$notes !== '' ? $notes : null,
        ':id'=>$id,
        ':cid'=>$cid,
      ]);

      /* --- Re-sync booking_vehicles --- */
      $del = db()->prepare("DELETE FROM booking_vehicles WHERE booking_id=:bid");
      $del->execute([':bid'=>$id]);

      $drv_ids   = $_POST['drv_id']   ?? [];
      $veh_ids   = $_POST['veh_id']   ?? [];
      $own_regs  = $_POST['own_reg']  ?? [];
      $own_types = $_POST['own_type'] ?? [];
      $cprices   = $_POST['cprice']   ?? [];
      $dprices   = $_POST['dprice']   ?? [];
      $orders    = $_POST['seq']      ?? [];

      $driversMap=[]; foreach($drivers as $d) $driversMap[(int)$d['id']]=$d;
      $vehiclesMap=[]; foreach($vehicles as $v) $vehiclesMap[(int)$v['id']]=$v;

      $ins = db()->prepare("
        INSERT INTO booking_vehicles
          (booking_id, vehicle_id, vehicle_type, vehicle_reg_no, driver_id, driver_price, client_price, sequence_order)
        VALUES
          (:bid,:vehicle_id,:vehicle_type,:vehicle_reg_no,:driver_id,:driver_price,:client_price,:sequence_order)
      ");

      $rowCount = max(count($drv_ids),count($veh_ids),count($own_regs),count($own_types),count($cprices),count($dprices),count($orders));

      for ($i=0;$i<$rowCount;$i++) {
        $drvId = isset($drv_ids[$i])?(int)$drv_ids[$i]:0;
        $vehId = isset($veh_ids[$i])?(int)$veh_ids[$i]:0;
        $seq   = isset($orders[$i])?(int)$orders[$i]:($i+1);
        $cp    = isset($cprices[$i])?(float)$cprices[$i]:0.00;
        $dp    = isset($dprices[$i])?(float)$dprices[$i]:0.00;

        $regStore=null; $typeStore=null;
        if ($vehId>0 && isset($vehiclesMap[$vehId])) {
          $regStore=$vehiclesMap[$vehId]['reg_no'];
          $typeStore=$vehiclesMap[$vehId]['type'];
        } elseif ($drvId>0 && isset($driversMap[$drvId]) && !empty($driversMap[$drvId]['own_vehicle_reg_no'])) {
          $regStore=$driversMap[$drvId]['own_vehicle_reg_no'];
          $typeStore=$driversMap[$drvId]['own_vehicle_type'];
        } else {
          $regStore=isset($own_regs[$i])&&$own_regs[$i]!==''?strtoupper($own_regs[$i]):null;
          $typeStore=isset($own_types[$i])&&$own_types[$i]!==''?$own_types[$i]:null;
        }
        if ($drvId<=0 && $vehId<=0 && $regStore===null && $typeStore===null && $cp==0.00 && $dp==0.00) continue;

        $ins->execute([
          ':bid'=>$id,
          ':vehicle_id'=>$vehId>0?$vehId:null,
          ':vehicle_type'=>$typeStore,
          ':vehicle_reg_no'=>$regStore,
          ':driver_id'=>$drvId>0?$drvId:null,
          ':driver_price'=>$dp,
          ':client_price'=>$cp,
          ':sequence_order'=>$seq,
        ]);
      }

      /* NEW: keep pending_payments (client) aligned with edited totals & ref */
      pending_upsert_client($cid, $id);

      db()->commit();
      audit_log('booking.update','booking',$id,['fields'=>'all']);
      $notice='Booking saved successfully.';

      $bk->execute([':id'=>$id, ':cid'=>$cid]); $booking=$bk->fetch();
      $as->execute([':bid'=>$id]); $assignments=$as->fetchAll();
    }
  } catch(Throwable $e) {
    if (db()->inTransaction()) db()->rollBack();
    $errors[]=(defined('APP_ENV')&&APP_ENV==='dev')?$e->getMessage():'Unable to save booking.';
  }
}

/* ---------------- UI helpers ---------------- */
function opt_selected($a,$b):string{return((string)$a===(string)$b&&$a!=='')?'selected':'';}
function status_options(string $cur):string{$opts=['New','Confirmed','Assigned','InProgress','Completed','Invoiced','Paid'];$h='';foreach($opts as $o)$h.='<option value="'.e($o).'" '.($cur===$o?'selected':'').'>'.e($o).'</option>';return$h;}

include dirname(__DIR__,2).'/includes/header.php';
?>

<!-- your entire HTML form remains exactly as in your original file (omitted here for brevity) -->


<!-- Separate COMPLETE form (outside the main form to avoid nested forms) -->
<form id="completeForm" method="post" action="complete.php" class="d-none">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
  <input type="hidden" name="id" value="<?= (int)$booking['id'] ?>">
</form>

<form method="post" id="bookingForm" autocomplete="off">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
  <input type="hidden" name="action" value="save">

  <!-- Sticky action bar -->
  <div class="position-sticky top-0 z-3 pb-2" style="background:#f8fafc;">
    <div class="d-flex justify-content-between align-items-center mb-2 pt-2">
      <h1 class="h4 mb-0">Edit Booking</h1>
      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-dark" form="bookingForm">Save Changes</button>
        <button type="submit" class="btn btn-success" form="completeForm" onclick="return confirm('Mark this booking as Completed?');">Mark as Completed</button>
        <a class="btn btn-outline-secondary" href="list.php">Back</a>
      </div>
    </div>
  </div>

  <?php if ($notice): ?>
    <div class="alert alert-success"><?= e($notice) ?></div>
  <?php endif; ?>
  <?php if ($errors): ?>
    <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e) echo '<li>'.e($e).'</li>'; ?></ul></div>
  <?php endif; ?>

  <!-- Summary (live totals) -->
  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="row g-3">
        <div class="col-md-3">
          <label class="form-label">Booking Ref</label>
          <input class="form-control" name="booking_ref" value="<?= e($_POST['booking_ref'] ?? $booking['booking_ref']) ?>">
          <div class="form-text">Leave blank to auto-generate (BHC-DDMMYYYY-###).</div>
        </div>

        <div class="col-md-3">
          <label class="form-label">Partner</label>
          <select class="form-select" name="partner_id">
            <option value="">—</option>
            <?php
            $curPartner = $_POST['partner_id'] ?? $booking['partner_id'];
            foreach ($partners as $p): ?>
              <option value="<?= (int)$p['id'] ?>" <?= opt_selected($curPartner, $p['id']) ?>><?= e($p['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- NEW: Corporate Client -->
        <div class="col-md-3">
          <label class="form-label">Corporate Client</label>
          <select class="form-select" name="corporate_id">
            <option value="">—</option>
            <?php
            $curCorporate = $_POST['corporate_id'] ?? $booking['corporate_id'];
            foreach ($corporates as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= opt_selected($curCorporate, $c['id']) ?>><?= e($c['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-3">
          <label class="form-label">Type</label>
          <?php $curType = $_POST['booking_type'] ?? $booking['booking_type']; ?>
          <select class="form-select" name="booking_type">
            <option value="Transfer"   <?= $curType==='Transfer'?'selected':'' ?>>Transfer</option>
            <option value="As Directed"<?= $curType==='As Directed'?'selected':'' ?>>As Directed</option>
          </select>
        </div>

        <div class="col-md-3">
          <label class="form-label">Hours (As Directed)</label>
          <input type="number" step="0.5" class="form-control" name="hours"
                 value="<?= e($_POST['hours'] ?? (string)($booking['hours'] ?? '')) ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Client Name</label>
          <input class="form-control" name="client_name"
                 value="<?= e($_POST['client_name'] ?? $booking['client_name']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Client Phone</label>
          <input class="form-control" name="client_phone"
                 value="<?= e($_POST['client_phone'] ?? $booking['client_phone']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Client Email</label>
          <input type="email" class="form-control" name="client_email"
                 value="<?= e($_POST['client_email'] ?? $booking['client_email']) ?>">
        </div>

        <div class="col-md-3">
          <label class="form-label">Pickup Date</label>
          <input type="date" class="form-control" name="pickup_date"
                 value="<?= e($_POST['pickup_date'] ?? $booking['pickup_date']) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Pickup Time</label>
          <input type="time" class="form-control" name="pickup_time"
                 value="<?= e($_POST['pickup_time'] ?? $booking['pickup_time']) ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Pickup Address</label>
          <input class="form-control" name="pickup_address"
                 value="<?= e($_POST['pickup_address'] ?? $booking['pickup_address']) ?>">
        </div>

        <div class="col-md-6">
          <label class="form-label">Via</label>
          <input class="form-control" name="via" value="<?= e($_POST['via'] ?? $booking['via']) ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Dropoff Address</label>
          <input class="form-control" name="dropoff_address"
                 value="<?= e($_POST['dropoff_address'] ?? $booking['dropoff_address']) ?>">
        </div>

        <div class="col-md-3">
          <label class="form-label">Passengers</label>
          <input type="number" class="form-control" name="pax_count"
                 value="<?= e($_POST['pax_count'] ?? (string)($booking['pax_count'] ?? 0)) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Luggage</label>
          <input type="number" class="form-control" name="luggage_count"
                 value="<?= e($_POST['luggage_count'] ?? (string)($booking['luggage_count'] ?? 0)) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Flight Number</label>
          <input class="form-control" name="flight_number"
                 value="<?= e($_POST['flight_number'] ?? $booking['flight_number']) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Status</label>
          <select class="form-select" name="status">
            <?= status_options((string)($_POST['status'] ?? $booking['status'])) ?>
          </select>
        </div>

        <div class="col-12">
          <label class="form-label">Notes</label>
          <textarea class="form-control" rows="2" name="notes"><?= e($_POST['notes'] ?? $booking['notes']) ?></textarea>
        </div>
      </div>
    </div>
  </div>

  <!-- Pricing -->
  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <h2 class="h6 mb-3">Pricing</h2>
      <div class="row g-3 align-items-end">
        <div class="col-md-2">
          <label class="form-label">£ Client</label>
          <input type="number" step="0.01" class="form-control js-calc" name="total_client_price"
                 value="<?= e($_POST['total_client_price'] ?? (string)($booking['total_client_price'] ?? '0.00')) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label">£ Driver</label>
          <input type="number" step="0.01" class="form-control js-calc" name="total_driver_price"
                 value="<?= e($_POST['total_driver_price'] ?? (string)($booking['total_driver_price'] ?? '0.00')) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label">Client Parking</label>
          <input type="number" step="0.01" class="form-control js-calc" name="client_parking_fee"
                 value="<?= e($_POST['client_parking_fee'] ?? (string)($booking['client_parking_fee'] ?? '0.00')) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label">Client Waiting</label>
          <input type="number" step="0.01" class="form-control js-calc" name="client_waiting_fee"
                 value="<?= e($_POST['client_waiting_fee'] ?? (string)($booking['client_waiting_fee'] ?? '0.00')) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label">Driver Parking</label>
          <input type="number" step="0.01" class="form-control js-calc" name="driver_parking_fee"
                 value="<?= e($_POST['driver_parking_fee'] ?? (string)($booking['driver_parking_fee'] ?? '0.00')) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label">Driver Waiting</label>
          <input type="number" step="0.01" class="form-control js-calc" name="driver_waiting_fee"
                 value="<?= e($_POST['driver_waiting_fee'] ?? (string)($booking['driver_waiting_fee'] ?? '0.00')) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Partner Commission (£)</label>
          <input type="number" step="0.01" class="form-control js-calc" name="partner_commission_amount"
                 value="<?= e($_POST['partner_commission_amount'] ?? (string)($booking['partner_commission_amount'] ?? '0.00')) ?>">
        </div>
      </div>

      <div class="row g-3 mt-3">
        <div class="col-md-3">
          <div class="p-2 border rounded bg-light">
            <div class="small text-muted">Client Total</div>
            <div class="fw-bold" id="sumClient">0.00</div>
          </div>
        </div>
        <div class="col-md-3">
          <div class="p-2 border rounded bg-light">
            <div class="small text-muted">Driver Total</div>
            <div class="fw-bold" id="sumDriver">0.00</div>
          </div>
        </div>
        <div class="col-md-3">
          <div class="p-2 border rounded bg-light">
            <div class="small text-muted">Commission</div>
            <div class="fw-bold" id="sumCommission">0.00</div>
          </div>
        </div>
        <div class="col-md-3">
          <div class="p-2 border rounded bg-light">
            <div class="small text-muted">Profit</div>
            <div class="fw-bold" id="sumProfit">0.00</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Assignments -->
  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h2 class="h6 mb-0">Vehicles & Drivers</h2>
        <button type="button" class="btn btn-sm btn-outline-primary" id="btnAddRow">Add Row</button>
      </div>

      <div class="table-responsive">
        <table class="table align-middle" id="assignTable">
          <thead class="table-light">
            <tr>
              <th style="width:60px;">#</th>
              <th style="min-width:180px;">Driver</th>
              <th style="min-width:180px;">Vehicle</th>
              <th>Own Reg</th>
              <th>Own Type</th>
              <th class="text-end" style="width:120px;">£ Client</th>
              <th class="text-end" style="width:120px;">£ Driver</th>
              <th style="width:80px;"></th>
            </tr>
          </thead>
          <tbody>
            <?php
            $rows = $_SERVER['REQUEST_METHOD']==='POST'
              ? array_map(null,
                  (array)($_POST['seq']??[]),
                  (array)($_POST['drv_id']??[]),
                  (array)($_POST['veh_id']??[]),
                  (array)($_POST['own_reg']??[]),
                  (array)($_POST['own_type']??[]),
                  (array)($_POST['cprice']??[]),
                  (array)($_POST['dprice']??[])
                )
              : array_map(function($r){
                  return [
                    $r['sequence_order'] ?? null,
                    $r['driver_id'] ?? null,
                    $r['vehicle_id'] ?? null,
                    $r['vehicle_reg_no'] ?? null,
                    $r['vehicle_type'] ?? null,
                    $r['client_price'] ?? null,
                    $r['driver_price'] ?? null,
                  ];
                }, $assignments);

            if (!$rows || count($rows)===0) $rows = [[1,null,null,null,null,null,null]];

            $driverOpts = function($sel) use ($drivers) {
              $h='<option value="">—</option>';
              foreach ($drivers as $d) {
                $h.='<option value="'.(int)$d['id'].'" '.($sel==$d['id']?'selected':'').'>'.e($d['name']).'</option>';
              }
              return $h;
            };
            $vehicleOpts = function($sel) use ($vehicles) {
              $h='<option value="">—</option>';
              foreach ($vehicles as $v) {
                $label = $v['reg_no'].' ('.$v['type'].')';
                $h.='<option value="'.(int)$v['id'].'" '.($sel==$v['id']?'selected':'').'>'.e($label).'</option>';
              }
              return $h;
            };

            foreach ($rows as $i => $r):
              $seq   = (int)($r[0] ?? ($i+1));
              $drvId = (int)($r[1] ?? 0);
              $vehId = (int)($r[2] ?? 0);
              $oreg  = (string)($r[3] ?? '');
              $otype = (string)($r[4] ?? '');
              $cp    = (string)($r[5] ?? '');
              $dp    = (string)($r[6] ?? '');
            ?>
            <tr>
              <td><input class="form-control form-control-sm" name="seq[]" value="<?= e($seq) ?>"></td>
              <td>
                <select class="form-select form-select-sm js-driver" name="drv_id[]">
                  <?= $driverOpts($drvId) ?>
                </select>
              </td>
              <td>
                <select class="form-select form-select-sm js-vehicle" name="veh_id[]">
                  <?= $vehicleOpts($vehId) ?>
                </select>
              </td>
              <td><input class="form-control form-control-sm js-own-reg"   name="own_reg[]"  value="<?= e($oreg) ?>"></td>
              <td>
                <select class="form-select form-select-sm js-own-type" name="own_type[]">
                  <option value="">—</option>
                  <?php foreach (VEHICLE_TYPES as $t): ?>
                    <option value="<?= e($t) ?>" <?= $otype===$t?'selected':'' ?>><?= e($t) ?></option>
                  <?php endforeach; ?>
                </select>
              </td>
              <td><input type="number" step="0.01" class="form-control form-control-sm text-end js-calc" name="cprice[]" value="<?= e($cp) ?>"></td>
              <td><input type="number" step="0.01" class="form-control form-control-sm text-end js-calc" name="dprice[]" value="<?= e($dp) ?>"></td>
              <td><button type="button" class="btn btn-sm btn-outline-danger js-del-row">Delete</button></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="text-muted small">
        Tip: pick a driver first — if they have an own vehicle, the Reg/Type auto-fills. You can still change vehicle via dropdown.
      </div>
    </div>
  </div>

  <div class="d-flex gap-2">
    <button type="submit" class="btn btn-dark">Save Changes</button>
    <a class="btn btn-outline-secondary" href="list.php">Cancel</a>
  </div>
</form>

<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>

<script>
/* ===== Live totals ===== */
(function(){
  const q = s => document.querySelector(s);
  const fields = [
    'input[name="total_client_price"]',
    'input[name="client_parking_fee"]',
    'input[name="client_waiting_fee"]',
    'input[name="total_driver_price"]',
    'input[name="driver_parking_fee"]',
    'input[name="driver_waiting_fee"]',
    'input[name="partner_commission_amount"]'
  ];
  function num(v){ const n=parseFloat(v); return isNaN(n)?0:n; }
  function calc(){
    const client = num(q('input[name="total_client_price"]').value) +
                   num(q('input[name="client_parking_fee"]').value) +
                   num(q('input[name="client_waiting_fee"]').value);
    const driver = num(q('input[name="total_driver_price"]').value) +
                   num(q('input[name="driver_parking_fee"]').value) +
                   num(q('input[name="driver_waiting_fee"]').value);
    const comm   = num(q('input[name="partner_commission_amount"]').value);
    const profit = client - driver - comm;
    q('#sumClient').textContent     = client.toFixed(2);
    q('#sumDriver').textContent     = driver.toFixed(2);
    q('#sumCommission').textContent = comm.toFixed(2);
    q('#sumProfit').textContent     = profit.toFixed(2);
  }
  fields.forEach(sel=>{
    const el = q(sel);
    if (el) el.addEventListener('input', calc);
  });
  // also recalc when assignment prices change
  const assign = document.getElementById('assignTable');
  if (assign) {
    assign.addEventListener('input', e=>{
      if (e.target.matches('input[name="cprice[]"], input[name="dprice[]"]')) calc();
    });
  }
  calc();
})();

/* ===== Assignment rows & own-vehicle auto-fill ===== */
(function(){
  const driversData  = <?= json_encode(array_values($drivers), JSON_UNESCAPED_UNICODE) ?>;
  const vehiclesData = <?= json_encode(array_values($vehicles), JSON_UNESCAPED_UNICODE) ?>;

  const tableBody = document.querySelector('#assignTable tbody');
  const btnAdd = document.getElementById('btnAddRow');

  btnAdd.addEventListener('click', () => addRow());

  tableBody.addEventListener('click', (e) => {
    const btn = e.target.closest('.js-del-row');
    if (!btn) return;
    const tr = btn.closest('tr');
    tr.remove();
    renumber();
  });

  tableBody.addEventListener('change', (e) => {
    const sel = e.target;
    const tr  = sel.closest('tr');
    if (!tr) return;

    // Select driver -> auto set own vehicle if available
    if (sel.classList.contains('js-driver')) {
      const drvId = parseInt(sel.value || '0', 10);
      const d = driversData.find(x => parseInt(x.id,10) === drvId);
      if (d && d.own_vehicle_reg_no) {
        tr.querySelector('.js-own-reg').value = d.own_vehicle_reg_no || '';
        const typeSel = tr.querySelector('.js-own-type');
        if (typeSel) typeSel.value = d.own_vehicle_type || '';
        // Clear explicit vehicle dropdown (free-text own vehicle mode)
        const vehSel = tr.querySelector('.js-vehicle');
        if (vehSel) vehSel.value = '';
        toast('Own vehicle applied');
      }
    }
  });

  function renumber(){
    [...tableBody.rows].forEach((tr,idx)=>{
      const seq = tr.querySelector('input[name="seq[]"]');
      if (seq) seq.value = String(idx+1);
    });
  }

  function addRow(){
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td><input class="form-control form-control-sm" name="seq[]" value="\${tableBody.rows.length+1}"></td>
      <td>
        <select class="form-select form-select-sm js-driver" name="drv_id[]">
          <option value="">—</option>
          ${driversData.map(d => `<option value="${'${d.id}'}">${'${escapeHtml(d.name)}'}</option>`).join('')}
        </select>
      </td>
      <td>
        <select class="form-select form-select-sm js-vehicle" name="veh_id[]">
          <option value="">—</option>
          ${vehiclesData.map(v => `<option value="${'${v.id}'}">${'${escapeHtml(v.reg_no)}'} (${''+ '${escapeHtml(v.type)}'})</option>`).join('')}
        </select>
      </td>
      <td><input class="form-control form-control-sm js-own-reg" name="own_reg[]" value=""></td>
      <td>
        <select class="form-select form-select-sm js-own-type" name="own_type[]">
          <option value="">—</option>
          <?php foreach (VEHICLE_TYPES as $t): ?>
          <option value="<?= e($t) ?>"><?= e($t) ?></option>
          <?php endforeach; ?>
        </select>
      </td>
      <td><input type="number" step="0.01" class="form-control form-control-sm text-end js-calc" name="cprice[]" value=""></td>
      <td><input type="number" step="0.01" class="form-control form-control-sm text-end js-calc" name="dprice[]" value=""></td>
      <td><button type="button" class="btn btn-sm btn-outline-danger js-del-row">Delete</button></td>
    `;
    tableBody.appendChild(tr);
  }

  function escapeHtml(s){return (s||'').replace(/[&<>"']/g,m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]));}

  function toast(text){
    const t = document.createElement('div');
    t.textContent = text;
    t.style.position='fixed';
    t.style.right='1rem';
    t.style.bottom='1rem';
    t.style.background='#212529';
    t.style.color='#fff';
    t.style.padding='.5rem .75rem';
    t.style.borderRadius='8px';
    t.style.zIndex='1055';
    document.body.appendChild(t);
    setTimeout(()=>t.remove(),1200);
  }
})();
</script>
