<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/_lib.php';
require_login();

$pdo = db();
$cid = (int)($_SESSION['company_id'] ?? 0);
$uid = (int)($_SESSION['user_id'] ?? 0);

fleet_ensure_schema($pdo);
fleet_ensure_limo_schema($pdo);
csrf_bootstrap();

function fleet_has_table(PDO $pdo, string $table): bool {
  try {
    $st = $pdo->prepare("SHOW TABLES LIKE ?");
    $st->execute([$table]);
    return (bool)$st->fetchColumn();
  } catch (Throwable $e) {
    return false;
  }
}
function fleet_has_column(PDO $pdo, string $table, string $col): bool {
  try {
    $st = $pdo->prepare("SHOW COLUMNS FROM `{$table}` LIKE ?");
    $st->execute([$col]);
    return (bool)$st->fetchColumn();
  } catch (Throwable $e) {
    return false;
  }
}
function fleet_safe_vehicle_label(array $row): string {
  $parts = [];
  foreach (['plate_no_current','plate_no','brand','model'] as $k) {
    if (!empty($row[$k])) $parts[] = $row[$k];
  }
  return trim(implode(' - ', array_filter($parts))) ?: ('#' . (int)($row['id'] ?? 0));
}
function fleet_limo_upload_attachment_safe(?string $currentPath=null): ?string {
  if (empty($_FILES['attachment']) || ($_FILES['attachment']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) return $currentPath;
  if (($_FILES['attachment']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) throw new RuntimeException('تعذر رفع المرفق.');
  $orig = $_FILES['attachment']['name'] ?? 'attachment';
  $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
  $allowed = ['jpg','jpeg','png','webp','pdf'];
  if (!in_array($ext, $allowed, true)) throw new RuntimeException('نوع المرفق غير مدعوم.');
  $dirRel = 'uploads/fleet/limo/' . date('Y') . '/' . date('m');
  $dirAbs = dirname(__DIR__) . '/' . $dirRel;
  if (!is_dir($dirAbs)) @mkdir($dirAbs, 0775, true);
  $file = 'limo_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
  $abs = $dirAbs . '/' . $file;
  if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $abs)) throw new RuntimeException('تعذر حفظ المرفق.');
  return $dirRel . '/' . $file;
}

$msg = '';
$err = '';
$rows = [];
$vehicles = [];
$customers = [];
$drivers = [];
$pickupLocations = [];
$dropLocations = [];
$serials = [];
$defaultCustomerId = 0;

try {
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $action = $_POST['action'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if ($action === 'save') {
      $mode = trim($_POST['serial_mode'] ?? 'new');
      $serialId = (int)($_POST['serial_id'] ?? 0);
      $vehicleId = (int)($_POST['vehicle_id'] ?? 0);
      $driverId = (int)($_POST['driver_id'] ?? 0) ?: null;
      $customerId = (int)($_POST['customer_id'] ?? 0) ?: null;
      $tripStatus = trim($_POST['trip_status'] ?? 'REQUESTED');
      $tripDate = trim($_POST['trip_date'] ?? date('Y-m-d'));
      $pickupTime = trim($_POST['pickup_time'] ?? '') ?: null;
      $pickupLocationId = (int)($_POST['pickup_location_id'] ?? 0) ?: null;
      $dropoffLocationId = (int)($_POST['dropoff_location_id'] ?? 0) ?: null;
      $kmOut = (float)($_POST['km_out'] ?? 0);
      $kmIn = trim((string)($_POST['km_in'] ?? '')) === '' ? null : (float)$_POST['km_in'];
      $usedKm = $kmIn !== null ? max(0, $kmIn - $kmOut) : 0;
      if ($kmIn !== null && $kmIn < $kmOut) throw new RuntimeException('لا يمكن أن يكون كم الدخول أقل من كم الخروج.');
      $tripAmount = (float)($_POST['trip_amount'] ?? 0);
      $paymentType = trim($_POST['payment_type'] ?? 'CASH');
      $expectedCollectionDate = trim($_POST['expected_collection_date'] ?? '') ?: null;
      if ($paymentType === 'CREDIT') {
        $tomorrow = date('Y-m-d', strtotime('+1 day'));
        if (!$expectedCollectionDate || $expectedCollectionDate < $tomorrow) {
          throw new RuntimeException('في حالة السداد الآجل يجب أن يكون تاريخ التحصيل المتوقع بعد تاريخ اليوم.');
        }
      }
      $notes = trim($_POST['notes'] ?? '');

      if ($vehicleId <= 0) throw new RuntimeException('السيارة مطلوبة.');
      if ($tripDate === '') throw new RuntimeException('تاريخ الرحلة مطلوب.');

      if ($id > 0) {
        $st = $pdo->prepare("SELECT attachment_path FROM fleet_limo_trips WHERE id=? AND company_id=? LIMIT 1");
        $st->execute([$id, $cid]);
        $old = $st->fetch(PDO::FETCH_ASSOC);
        if (!$old) throw new RuntimeException('الرحلة غير موجودة.');
        $attachmentPath = fleet_limo_upload_attachment_safe($old['attachment_path'] ?? null);

        $st = $pdo->prepare("UPDATE fleet_limo_trips SET vehicle_id=?, driver_id=?, customer_id=?, trip_status=?, trip_date=?, pickup_time=?, pickup_location_id=?, dropoff_location_id=?, km_out=?, km_in=?, used_km=?, trip_amount=?, payment_type=?, expected_collection_date=?, notes=?, attachment_path=?, updated_at=NOW() WHERE id=? AND company_id=?");
        $st->execute([$vehicleId,$driverId,$customerId,$tripStatus,$tripDate,$pickupTime,$pickupLocationId,$dropoffLocationId,$kmOut,$kmIn,$usedKm,$tripAmount,$paymentType,$expectedCollectionDate,$notes,$attachmentPath,$id,$cid]);
        $msg = 'تم تعديل رحلة الليموزين.';
      } elseif ($action === 'save') {
        if ($mode === 'new' || $serialId <= 0) {
          $serialId = fleet_create_limo_serial($pdo, $cid, $tripDate, $customerId, $uid);
        } else {
          $st = $pdo->prepare("SELECT id FROM fleet_limo_serials WHERE id=? AND company_id=? LIMIT 1");
          $st->execute([$serialId, $cid]);
          if (!(int)$st->fetchColumn()) throw new RuntimeException('السريال المحدد غير موجود.');
        }

        $tripNo = fleet_next_limo_trip_no($pdo, $cid, $serialId);
        $displayNo = fleet_limo_display_no($pdo, $cid, $serialId, $tripNo);
        $attachmentPath = fleet_limo_upload_attachment_safe();

        $st = $pdo->prepare("INSERT INTO fleet_limo_trips (company_id, serial_id, trip_no, display_no, vehicle_id, driver_id, customer_id, trip_status, trip_date, pickup_time, pickup_location_id, dropoff_location_id, km_out, km_in, used_km, trip_amount, payment_type, expected_collection_date, notes, attachment_path, created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $st->execute([$cid,$serialId,$tripNo,$displayNo,$vehicleId,$driverId,$customerId,$tripStatus,$tripDate,$pickupTime,$pickupLocationId,$dropoffLocationId,$kmOut,$kmIn,$usedKm,$tripAmount,$paymentType,$expectedCollectionDate,$notes,$attachmentPath,$uid]);
        $msg = 'تم تسجيل رحلة الليموزين.';
      }
    }

    if ($action === 'delete') {
      $st = $pdo->prepare("SELECT serial_id FROM fleet_limo_trips WHERE id=? AND company_id=? LIMIT 1");
      $st->execute([$id, $cid]);
      $row = $st->fetch(PDO::FETCH_ASSOC);
      if (!$row) throw new RuntimeException('الرحلة غير موجودة.');
      $serialId = (int)$row['serial_id'];

      $pdo->prepare("DELETE FROM fleet_limo_trips WHERE id=? AND company_id=?")->execute([$id, $cid]);

      $st = $pdo->prepare("SELECT COUNT(*) FROM fleet_limo_trips WHERE company_id=? AND serial_id=?");
      $st->execute([$cid, $serialId]);
      if ((int)$st->fetchColumn() === 0) {
        $pdo->prepare("DELETE FROM fleet_limo_serials WHERE id=? AND company_id=?")->execute([$serialId, $cid]);
      }
      $msg = 'تم حذف رحلة التشغيل.';
    }
  }

  if (fleet_has_table($pdo, 'customers')) {
    try { $defaultCustomerId = (int)(fleet_limo_default_customer_id($pdo, $cid) ?: 0); } catch (Throwable $e) { $defaultCustomerId = 0; }
  }

  if (fleet_has_table($pdo, 'vehicles')) {
    $cols = [];
    foreach ($pdo->query("SHOW COLUMNS FROM vehicles")->fetchAll(PDO::FETCH_ASSOC) as $c) $cols[] = $c['Field'];
    $selectCols = ['id'];
    foreach (['plate_no_current','plate_no','brand','model'] as $c) { if (in_array($c, $cols, true)) $selectCols[] = $c; }
    $sql = "SELECT " . implode(',', $selectCols) . " FROM vehicles";
    if (in_array('company_id', $cols, true)) $sql .= " WHERE company_id=?";
    $order = in_array('plate_no_current', $cols, true) ? 'plate_no_current' : (in_array('plate_no', $cols, true) ? 'plate_no' : 'id');
    $sql .= " ORDER BY {$order}";
    $st = $pdo->prepare($sql);
    $st->execute(in_array('company_id', $cols, true) ? [$cid] : []);
    $vehicles = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
  }

  if (fleet_has_table($pdo, 'customers')) {
    $nameCol = fleet_has_column($pdo, 'customers', 'full_name') ? 'full_name' : (fleet_has_column($pdo, 'customers', 'name') ? 'name' : null);
    if ($nameCol) {
      $st = $pdo->prepare("SELECT id, {$nameCol} AS full_name FROM customers WHERE company_id=? ORDER BY ({$nameCol}='نزيل الفندق') DESC, {$nameCol}");
      $st->execute([$cid]);
      $customers = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
  }

  try {
    $drivers = [];
    if (fleet_has_table($pdo, 'employees')) {
      $nameCol = fleet_has_column($pdo, 'employees', 'full_name') ? 'full_name' : (fleet_has_column($pdo, 'employees', 'name') ? 'name' : null);
      if ($nameCol) {
        $st = $pdo->prepare("SELECT id, {$nameCol} AS display_name FROM employees WHERE company_id=? ORDER BY {$nameCol}");
        $st->execute([$cid]);
        $drivers = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
      }
    } elseif (fleet_has_table($pdo, 'hr_employees')) {
      $nameCol = fleet_has_column($pdo, 'hr_employees', 'full_name') ? 'full_name' : (fleet_has_column($pdo, 'hr_employees', 'name') ? 'name' : null);
      if ($nameCol) {
        $st = $pdo->prepare("SELECT id, {$nameCol} AS display_name FROM hr_employees WHERE company_id=? ORDER BY {$nameCol}");
        $st->execute([$cid]);
        $drivers = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
      }
    }
  } catch (Throwable $e) { $drivers = []; }

  $st = $pdo->prepare("SELECT id, name FROM fleet_locations WHERE company_id=? AND is_active=1 AND is_pickup=1 ORDER BY name");
  $st->execute([$cid]);
  $pickupLocations = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

  $st = $pdo->prepare("SELECT id, name FROM fleet_locations WHERE company_id=? AND is_active=1 AND is_dropoff=1 ORDER BY name");
  $st->execute([$cid]);
  $dropLocations = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

  $st = $pdo->prepare("SELECT id, serial_no FROM fleet_limo_serials WHERE company_id=? AND status='OPEN' ORDER BY serial_no DESC LIMIT 100");
  $st->execute([$cid]);
  $serials = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

  $st = $pdo->prepare("SELECT t.*, s.serial_no, lp.name AS pickup_name, ld.name AS drop_name
    FROM fleet_limo_trips t
    JOIN fleet_limo_serials s ON s.id=t.serial_id
    LEFT JOIN fleet_locations lp ON lp.id=t.pickup_location_id
    LEFT JOIN fleet_locations ld ON ld.id=t.dropoff_location_id
    WHERE t.company_id=?
    ORDER BY t.trip_date DESC, t.id DESC LIMIT 300");
  $st->execute([$cid]);
  $rows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

} catch (Throwable $e) {
  $err = $e->getMessage();
}

$vehicleMap = [];
foreach ($vehicles as $v) $vehicleMap[(int)$v['id']] = $v;

$latestKmMap = [];
try {
  $st = $pdo->prepare("SELECT vehicle_id, MAX(COALESCE(km_in, km_out, 0)) AS last_km FROM fleet_limo_trips WHERE company_id=? GROUP BY vehicle_id");
  $st->execute([$cid]);
  foreach (($st->fetchAll(PDO::FETCH_ASSOC) ?: []) as $kmr) {
    $latestKmMap[(int)$kmr['vehicle_id']] = (int)($kmr['last_km'] ?? 0);
  }
} catch (Throwable $e) {
  $latestKmMap = [];
}

$customerMap = [];
foreach ($customers as $c) $customerMap[(int)$c['id']] = $c['full_name'];

$statuses = ['REQUESTED'=>'طلب توصيل','DONE'=>'تم التنفيذ','COLLECTED'=>'تم التحصيل','CANCELLED'=>'ملغي'];

render_layout('تشغيل الليموزين','إدارة السيارات <span class="mx-1">/</span> تشغيل الليموزين', function() use($rows,$vehicles,$vehicleMap,$latestKmMap,$customerMap,$drivers,$customers,$pickupLocations,$dropLocations,$serials,$statuses,$msg,$err,$defaultCustomerId){ ?>
<style>
#tripModal .bootstrap-select{width:100% !important;max-width:100% !important;}
#tripModal .bootstrap-select > .dropdown-toggle{width:100% !important;}
#tripModal .bootstrap-select .dropdown-menu{max-width:100% !important;min-width:100% !important;}
#tripModal .dropdown-menu.inner{max-height:320px !important;}
#tripModal input[type='date'],
#tripModal input[type='time']{min-height:46px;border-radius:12px;}
#tripModal .form-control,
#tripModal .form-select{min-height:46px;}
.limo-trips-table th,.limo-trips-table td{white-space:nowrap;vertical-align:middle;}
.limo-trips-table{font-size:0.97rem;}
</style>
<div class="container-fluid mt-3">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div><div class="fw-bold fs-4">تشغيل الليموزين اليومي</div><div class="text-secondary small">سريال رئيسي ورقم رحلة فرعي مثل 1001-1. حقل السائق يتم اختياره من الموظفين فقط.</div></div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-dark" href="<?= url('/fleet/locations.php') ?>"><i class="bi bi-geo-alt"></i> مناطق الليموزين</a>
      <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#tripModal"><i class="bi bi-plus-lg"></i> إضافة رحلة</button>
    </div>
  </div>

  <?php if(!$vehicles): ?><div class="alert alert-warning mt-3">لا توجد سيارات مسجلة حاليًا. يجب توفير بيانات السيارات أولاً.</div><?php endif; ?>
  <?php if($msg): ?><div class="alert alert-success mt-3"><?= h($msg) ?></div><?php endif; ?>
  <?php if($err): ?><div class="alert alert-danger mt-3"><?= h($err) ?></div><?php endif; ?>

  <div class="card cardx mt-3"><div class="table-responsive p-3">
    <table class="table align-middle mb-0 limo-trips-table">
      <thead><tr class="text-secondary small"><th>رقم الرحلة</th><th>التاريخ</th><th>السيارة</th><th>العميل</th><th>من</th><th>إلى</th><th class="text-end">كم مستخدم</th><th class="text-end">القيمة</th><th>الحالة</th><th class="text-end">الإجراءات</th></tr></thead>
      <tbody>
      <?php if(!$rows): ?><tr><td colspan="10" class="text-center text-secondary py-4">لا توجد رحلات مسجلة.</td></tr><?php endif; ?>
      <?php foreach($rows as $r): $statusClass = $r['trip_status']==='DONE' ? 'success' : ($r['trip_status']==='COLLECTED' ? 'primary' : ($r['trip_status']==='CANCELLED' ? 'danger' : 'info')); ?>
        <tr>
          <td class="fw-semibold"><?= h($r['display_no']) ?></td>
          <td><?= h($r['trip_date']) ?><?= !empty($r['pickup_time']) ? '<br><span class="small text-secondary">'.h($r['pickup_time']).'</span>' : '' ?></td>
          <td><?= h(fleet_safe_vehicle_label($vehicleMap[(int)($r['vehicle_id'] ?? 0)] ?? ['id'=>(int)($r['vehicle_id'] ?? 0)])) ?></td>
          <td><?= h($customerMap[(int)($r['customer_id'] ?? 0)] ?? '-') ?></td>
          <td><?= h($r['pickup_name'] ?? '-') ?></td>
          <td><?= h($r['drop_name'] ?? '-') ?></td>
          <td class="text-end"><?= number_format((float)$r['used_km'], 2) ?></td>
          <td class="text-end"><?= number_format((float)$r['trip_amount'], 2) ?></td>
          <td><span class="badge bg-<?= h($statusClass) ?>-subtle text-<?= h($statusClass) ?> border border-<?= h($statusClass) ?>-subtle"><?= h($statuses[$r['trip_status']] ?? $r['trip_status']) ?></span></td>
          <td class="text-end">
            <div class="dropdown d-inline-block">
              <button class="btn btn-outline-dark btn-sm dropdown-toggle" data-bs-toggle="dropdown">الإجراءات</button>
              <ul class="dropdown-menu">
                <li><button type="button" class="dropdown-item js-edit"
                  data-id="<?= (int)$r['id'] ?>" data-serialid="<?= (int)$r['serial_id'] ?>" data-displayno="<?= h($r['display_no']) ?>"
                  data-vehicle="<?= (int)$r['vehicle_id'] ?>" data-driver="<?= (int)($r['driver_id'] ?? 0) ?>" data-customer="<?= (int)($r['customer_id'] ?? 0) ?>"
                  data-status="<?= h($r['trip_status']) ?>" data-date="<?= h($r['trip_date']) ?>" data-time="<?= h($r['pickup_time']) ?>"
                  data-pickup="<?= (int)($r['pickup_location_id'] ?? 0) ?>" data-drop="<?= (int)($r['dropoff_location_id'] ?? 0) ?>"
                  data-kmout="<?= h($r['km_out']) ?>" data-kmin="<?= h($r['km_in']) ?>" data-amount="<?= h($r['trip_amount']) ?>"
                  data-payment="<?= h($r['payment_type']) ?>" data-due="<?= h($r['expected_collection_date']) ?>" data-notes="<?= h($r['notes']) ?>">تعديل الرحلة</button></li>
                <?php if(!empty($r['attachment_path'])): ?><li><a class="dropdown-item" href="<?= h(url('/' . ltrim($r['attachment_path'], '/'))) ?>" target="_blank">عرض المرفق</a></li><?php endif; ?>
                <li><a class="dropdown-item" href="<?= h(url('/fleet/limo_trip_print.php?id='.(int)$r['id'])) ?>" target="_blank">طباعة الرحلة</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><form method="post" onsubmit="return confirm('حذف رحلة التشغيل؟');"><?= csrf_field() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button class="dropdown-item text-danger">حذف الرحلة</button></form></li>
              </ul>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div></div>
</div>

<div class="modal fade modal-erp" id="tripModal" tabindex="-1">
  <div class="modal-dialog modal-xl"><div class="modal-content">
    <form method="post" enctype="multipart/form-data" id="tripForm">
      <?= csrf_field() ?><input type="hidden" name="action" value="save"><input type="hidden" name="id" id="trip_id" value="0">
      <div class="modal-header"><h5 class="modal-title" id="trip_title">تسجيل تشغيل الليموزين</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body"><div class="row g-3 modal-inline-grid">
        <div class="col-md-4"><label class="form-label">طريقة السريال</label><select name="serial_mode" id="trip_serial_mode" class="form-select selectpicker"><option value="new">إنشاء سريال جديد</option><option value="existing">إضافة على سريال موجود</option></select></div>
        <div class="col-md-4" id="existing_serial_wrap" style="display:none"><label class="form-label">السريال الرئيسي</label><select name="serial_id" id="trip_serial_id" class="form-select selectpicker" data-live-search="true" data-width="100%"><option value="">— اختر —</option><?php foreach($serials as $s): ?><option value="<?= (int)$s['id'] ?>"><?= h($s['serial_no']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-4"><label class="form-label">رقم الرحلة</label><input class="form-control" id="trip_display_no" value="سيظهر تلقائيًا" readonly></div>

        <div class="col-md-4"><label class="form-label">السيارة</label><select name="vehicle_id" id="trip_vehicle" class="form-select selectpicker" data-live-search="true" data-width="100%" required><?php foreach($vehicles as $v): ?><option value="<?= (int)$v['id'] ?>" data-lastkm="<?= (int)($latestKmMap[(int)$v['id']] ?? 0) ?>"><?= h(fleet_safe_vehicle_label($v)) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-4"><label class="form-label">السائق</label><select name="driver_id" id="trip_driver" class="form-select selectpicker" data-live-search="true" data-width="100%"><option value="">—</option><?php foreach($drivers as $d): ?><option value="<?= (int)$d['id'] ?>"><?= h($d['display_name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-4"><label class="form-label">العميل</label><select name="customer_id" id="trip_customer" class="form-select selectpicker" data-live-search="true" data-width="100%"><?php foreach($customers as $c): ?><option value="<?= (int)$c['id'] ?>" <?= $defaultCustomerId === (int)$c['id'] ? 'selected' : '' ?>><?= h($c['full_name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-4"><label class="form-label">حالة الرحلة</label><select name="trip_status" id="trip_status" class="form-select selectpicker" data-live-search="false" data-width="100%"><?php foreach($statuses as $k=>$v): ?><option value="<?= h($k) ?>"><?= h($v) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-4"><label class="form-label">تاريخ الرحلة</label><input type="date" name="trip_date" id="trip_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
        <div class="col-md-4"><label class="form-label">توقيت التوصيل</label><input type="time" name="pickup_time" id="trip_time" class="form-control" value="<?= date('H:i') ?>"></div>

        <div class="col-md-6"><label class="form-label">مكان التحرك</label><select name="pickup_location_id" id="trip_pickup" class="form-select selectpicker" data-live-search="true" data-width="100%"><option value="">—</option><?php foreach($pickupLocations as $l): ?><option value="<?= (int)$l['id'] ?>"><?= h($l['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-6"><label class="form-label">مكان الوجهة</label><select name="dropoff_location_id" id="trip_drop" class="form-select selectpicker" data-live-search="true" data-width="100%"><option value="">—</option><?php foreach($dropLocations as $l): ?><option value="<?= (int)$l['id'] ?>"><?= h($l['name']) ?></option><?php endforeach; ?></select></div>

        <div class="col-md-4"><label class="form-label">كم الخروج</label><input type="number" step="1" min="0" name="km_out" id="trip_km_out" class="form-control" value="0"></div>
        <div class="col-md-4"><label class="form-label">كم الدخول</label><input type="number" step="1" min="0" name="km_in" id="trip_km_in" class="form-control"></div>
        <div class="col-md-4"><label class="form-label">كم مستخدم</label><input type="number" step="1" min="0" id="trip_used_km" class="form-control" value="0" readonly></div>

        <div class="col-md-4"><label class="form-label">قيمة الرحلة</label><input type="number" step="0.01" name="trip_amount" id="trip_amount" class="form-control" value="0"></div>
        <div class="col-md-4"><label class="form-label">طريقة السداد</label><select name="payment_type" id="trip_payment" class="form-select selectpicker"><option value="CASH">نقدي</option><option value="CREDIT">أجل</option></select></div>
        <div class="col-md-4" id="trip_due_wrap" style="display:none"><label class="form-label">تاريخ التحصيل المتوقع</label><input type="date" name="expected_collection_date" id="trip_due" class="form-control"></div>

        <div class="col-md-6" id="trip_due_wrap"><label class="form-label">تاريخ التحصيل المتوقع</label><input type="date" name="expected_collection_date" id="trip_due" class="form-control"></div>
        <div class="col-md-6"><label class="form-label">المرفق</label><input type="file" name="attachment" class="form-control" accept=".pdf,.jpg,.jpeg,.png,.webp"></div>

        <div class="col-12"><label class="form-label">ملاحظات</label><textarea name="notes" id="trip_notes" class="form-control" rows="2"></textarea></div>
      </div></div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ</button></div>
    </form>
  </div></div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
  const modalEl = document.getElementById('tripModal');
  const modal = bootstrap.Modal.getOrCreateInstance(modalEl);

  function ensurePicker(id){
    const el = document.getElementById(id);
    if (!el) return;
    if (el.classList.contains('selectpicker') && window.jQuery && jQuery.fn && jQuery.fn.selectpicker) {
      const picker = jQuery(el);
      if (!picker.data('selectpicker')) {
        picker.selectpicker({
          liveSearch: el.dataset.liveSearch === 'true',
          size: parseInt(el.dataset.size || '8', 10),
          width: el.dataset.width || '100%',
          dropupAuto: false
        });
      }
      picker.selectpicker('refresh');
    }
  }

  function pickerSet(id, value){
    const el = document.getElementById(id);
    if(!el) return;
    el.value = value || '';
    if (el.classList.contains('selectpicker') && window.jQuery && jQuery.fn && jQuery.fn.selectpicker) {
      const picker = jQuery(el);
      if (!picker.data('selectpicker')) {
        picker.selectpicker({
          liveSearch: el.dataset.liveSearch === 'true',
          size: parseInt(el.dataset.size || '8', 10),
          width: el.dataset.width || '100%',
          dropupAuto: false
        });
      }
      picker.selectpicker('val', value || '');
      picker.selectpicker('refresh');
    }
  }

  function getSelectedVehicleLastKm(){
    const sel = document.getElementById('trip_vehicle');
    if (!sel) return 0;
    const opt = sel.options[sel.selectedIndex];
    return parseInt((opt && opt.dataset.lastkm) || '0', 10) || 0;
  }

  function updateUsedKm(){
    const out = parseInt(document.getElementById('trip_km_out').value || '0', 10);
    const innRaw = document.getElementById('trip_km_in').value;
    const inn = parseInt(innRaw || '0', 10);
    document.getElementById('trip_used_km').value = innRaw === '' ? 0 : Math.max(0, inn - out);
  }

  function todayStr(){
    const d = new Date();
    const y = d.getFullYear();
    const m = String(d.getMonth()+1).padStart(2,'0');
    const day = String(d.getDate()).padStart(2,'0');
    return `${y}-${m}-${day}`;
  }
  function tomorrowStr(){
    const d = new Date();
    d.setDate(d.getDate()+1);
    const y = d.getFullYear();
    const m = String(d.getMonth()+1).padStart(2,'0');
    const day = String(d.getDate()).padStart(2,'0');
    return `${y}-${m}-${day}`;
  }
  function nowTimeStr(){
    const d = new Date();
    const h = String(d.getHours()).padStart(2,'0');
    const m = String(d.getMinutes()).padStart(2,'0');
    return `${h}:${m}`;
  }
  function updatePaymentView(){
    const isCredit = document.getElementById('trip_payment').value === 'CREDIT';
    const dueWrap = document.getElementById('trip_due_wrap');
    const due = document.getElementById('trip_due');
    dueWrap.style.display = isCredit ? '' : 'none';
    due.min = tomorrowStr();
    if (isCredit && !due.value) due.value = tomorrowStr();
    if (!isCredit) due.value = '';
  }

  function updateSerialMode(){
    const mode = document.getElementById('trip_serial_mode').value;
    document.getElementById('existing_serial_wrap').style.display = mode === 'existing' ? '' : 'none';
    if (document.getElementById('trip_id').value === '0') {
      document.getElementById('trip_display_no').value = mode === 'existing' ? 'سيظهر تلقائيًا على السريال المختار' : 'سريال جديد - رحلة 1';
    }
  }

  function setKmOutFromVehicle(){
    if (document.getElementById('trip_id').value !== '0') return;
    document.getElementById('trip_km_out').value = getSelectedVehicleLastKm();
    updateUsedKm();
  }

  function resetForm(){
    document.getElementById('tripForm').reset();
    document.getElementById('trip_id').value = '0';
    document.getElementById('trip_title').textContent = 'تسجيل تشغيل الليموزين';
    document.getElementById('trip_display_no').value = 'سريال جديد - رحلة 1';
    document.getElementById('trip_date').value = todayStr();
    pickerSet('trip_serial_mode', 'new');
    pickerSet('trip_serial_id', '');
    document.getElementById('trip_time').value = nowTimeStr();
    pickerSet('trip_status', 'REQUESTED');
    pickerSet('trip_payment', 'CASH');
    pickerSet('trip_customer', '<?= (int)$defaultCustomerId ?>');
    pickerSet('trip_driver', '');
    updatePaymentView();
    updateSerialMode();
    setKmOutFromVehicle();
    updateUsedKm();
  }

  ['trip_serial_mode','trip_serial_id','trip_vehicle','trip_driver','trip_customer','trip_status','trip_pickup','trip_drop','trip_payment'].forEach(ensurePicker);

  document.getElementById('trip_km_out').addEventListener('input', updateUsedKm);
  document.getElementById('trip_km_in').addEventListener('input', updateUsedKm);
  document.getElementById('tripForm').addEventListener('submit', function(e){
    const out = parseInt(document.getElementById('trip_km_out').value || '0', 10);
    const inVal = document.getElementById('trip_km_in').value;
    if (inVal !== '') {
      const inn = parseInt(inVal, 10);
      if (inn < out) {
        e.preventDefault();
        alert('لا يمكن أن يكون كم الدخول أقل من كم الخروج.');
        document.getElementById('trip_km_in').focus();
        return false;
      }
    }
  });
  document.getElementById('trip_payment').addEventListener('change', updatePaymentView);
  document.getElementById('trip_serial_mode').addEventListener('change', updateSerialMode);
  document.getElementById('trip_vehicle').addEventListener('change', setKmOutFromVehicle);
  modalEl.addEventListener('hidden.bs.modal', resetForm);
  modalEl.addEventListener('shown.bs.modal', function(){
    if (document.getElementById('trip_id').value === '0') {
      document.getElementById('trip_date').value = todayStr();
      document.getElementById('trip_time').value = nowTimeStr();
    }
    updatePaymentView();
  });

  document.querySelectorAll('.js-edit').forEach(function(btn){
    btn.addEventListener('click', function(){
      document.getElementById('trip_id').value = this.dataset.id || '0';
      document.getElementById('trip_title').textContent = 'تعديل رحلة ليموزين';
      pickerSet('trip_serial_mode', 'existing');
      pickerSet('trip_serial_id', this.dataset.serialid || '');
      document.getElementById('trip_display_no').value = this.dataset.displayno || '';
      pickerSet('trip_vehicle', this.dataset.vehicle || '');
      pickerSet('trip_driver', this.dataset.driver || '');
      pickerSet('trip_customer', this.dataset.customer || '<?= (int)$defaultCustomerId ?>');
      pickerSet('trip_status', this.dataset.status || 'REQUESTED');
      document.getElementById('trip_date').value = this.dataset.date || '';
      document.getElementById('trip_time').value = this.dataset.time || nowTimeStr();
      pickerSet('trip_pickup', this.dataset.pickup || '');
      pickerSet('trip_drop', this.dataset.drop || '');
      document.getElementById('trip_km_out').value = parseInt(this.dataset.kmout || '0', 10);
      document.getElementById('trip_km_in').value = this.dataset.kmin || '';
      document.getElementById('trip_amount').value = this.dataset.amount || '0';
      pickerSet('trip_payment', this.dataset.payment || 'CASH');
      document.getElementById('trip_due').value = this.dataset.due || '';
      document.getElementById('trip_notes').value = this.dataset.notes || '';
      updatePaymentView();
      updateSerialMode();
      updateUsedKm();
      modal.show();
    });
  });

  resetForm();
});
</script>
<?php }); ?>
