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

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

function fleet_vehicle_label(array $row): string {
  $parts = [];
  foreach (['plate_no_current','plate_no','brand','model'] as $k) {
    if (!empty($row[$k])) $parts[] = trim((string)$row[$k]);
  }
  return trim(implode(' - ', array_filter($parts))) ?: ('#' . (int)($row['id'] ?? 0));
}

function fleet_rental_expected_days(string $duration): int {
  return strtoupper(trim($duration)) === 'DAILY' ? 7 : 30;
}

function fleet_rental_expected_end(string $contractDate, string $duration): string {
  $base = $contractDate ?: date('Y-m-d');
  $days = fleet_rental_expected_days($duration);
  return date('Y-m-d', strtotime($base . ' + ' . $days . ' days'));
}

function fleet_rental_label_kind(string $v): string {
  return strtoupper($v) === 'SERVICE' ? 'خدمي' : 'تجاري';
}
function fleet_rental_label_duration(string $v): string {
  return strtoupper($v) === 'DAILY' ? 'يومي' : 'شهري';
}
function fleet_rental_label_payment(?string $v): string {
  return strtoupper((string)$v) === 'CASH' ? 'نقدي' : 'آجل';
}
function fleet_rental_label_insurance(string $v): string {
  return strtoupper($v) === 'CLIENT' ? 'على العميل' : 'على الشركة';
}
function fleet_rental_status_badge(string $v): string {
  return match (strtoupper($v)) {
    'CLOSED' => 'bg-success-subtle text-success border',
    'CANCELLED' => 'bg-secondary-subtle text-secondary border',
    default => 'bg-warning-subtle text-warning border',
  };
}
function fleet_rental_status_label(string $v): string {
  return match (strtoupper($v)) {
    'CLOSED' => 'منتهي',
    'CANCELLED' => 'ملغي',
    default => 'نشط',
  };
}
function fleet_parse_money($v): float {
  return round((float)($v ?? 0), 2);
}
function fleet_parse_int($v): int {
  return (int)max(0, (int)($v ?? 0));
}
function fleet_contract_has_links(PDO $pdo, int $companyId, int $contractId, string $contractSerial): bool {
  $checks = [];
  if (fleet_table_exists($pdo, 'vehicle_rental_maintenance_items')) {
    $checks[] = ['sql' => "SELECT COUNT(*) FROM vehicle_rental_maintenance_items WHERE company_id=? AND contract_id=?", 'args' => [$companyId, $contractId]];
  }
  if (fleet_table_exists($pdo, 'journal_entries')) {
    $checks[] = ['sql' => "SELECT COUNT(*) FROM journal_entries WHERE company_id=? AND (source_id=? OR ref=?)", 'args' => [$companyId, $contractId, $contractSerial]];
  }
  foreach ($checks as $c) {
    $st = $pdo->prepare($c['sql']);
    $st->execute($c['args']);
    if ((int)$st->fetchColumn() > 0) return true;
  }
  return false;
}

$msg = '';
$err = '';
$svc = new AccountingService($pdo);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = trim((string)($_POST['action'] ?? ''));
  try {
    if ($action === 'create') {
      $vehicleId = (int)($_POST['vehicle_id'] ?? 0);
      $customerId = (int)($_POST['customer_id'] ?? 0) ?: null;
      $kmOut = fleet_parse_money($_POST['km_out'] ?? 0);
      $contractKind = strtoupper(trim((string)($_POST['contract_kind'] ?? 'COMMERCIAL')));
      $rentalDuration = strtoupper(trim((string)($_POST['rental_duration'] ?? 'MONTHLY')));
      $contractDate = trim((string)($_POST['contract_date'] ?? date('Y-m-d')));
      $expectedEndDate = trim((string)($_POST['expected_end_date'] ?? '')) ?: fleet_rental_expected_end($contractDate, $rentalDuration);
      $baseRentAmount = $contractKind === 'SERVICE' ? 0 : fleet_parse_money($_POST['base_rent_amount'] ?? 0);
      $extraKmRate = $contractKind === 'SERVICE' ? 0 : fleet_parse_money($_POST['extra_km_rate'] ?? 0);
      $extraDayRate = $contractKind === 'SERVICE' ? 0 : fleet_parse_money($_POST['extra_day_rate'] ?? 0);
      $insuranceParty = strtoupper(trim((string)($_POST['insurance_party'] ?? 'COMPANY')));
      $insuranceAmount = $insuranceParty === 'CLIENT' ? fleet_parse_money($_POST['insurance_amount'] ?? 0) : 0;
      $expectedDays = max(1, (int)ceil((strtotime($expectedEndDate) - strtotime($contractDate)) / 86400));
      $ad1 = (int)($_POST['additional_driver_1_id'] ?? 0) ?: null;
      $ad2 = (int)($_POST['additional_driver_2_id'] ?? 0) ?: null;
      $notes = trim((string)($_POST['notes'] ?? ''));

      if ($vehicleId <= 0) throw new RuntimeException('السيارة مطلوبة.');
      if ($kmOut < 0) throw new RuntimeException('كم الخروج غير صحيح.');
      if ($contractDate === '' || $expectedEndDate === '') throw new RuntimeException('تاريخ العقد وتاريخ الغلق المتوقع مطلوبان.');
      if ($expectedEndDate <= $contractDate) throw new RuntimeException('تاريخ الغلق المتوقع يجب أن يكون بعد تاريخ العقد.');
      if ($contractKind === 'COMMERCIAL' && $extraKmRate <= 0) throw new RuntimeException('في العقد التجاري يجب تحديد سعر كم زائد أكبر من صفر.');
      if ($contractKind === 'COMMERCIAL' && $baseRentAmount <= 0) throw new RuntimeException('في العقد التجاري يجب تحديد سعر التأجير.');

      $pdo->beginTransaction();
      $serial = fleet_next_order_serial($pdo, $cid, 'RENT');
      $orderType = $serial['order_type'];
      $orderSerialNo = (int)$serial['serial_no'];
      $contractSerial = (string)$serial['serial_label'];

      $st = $pdo->prepare("INSERT INTO vehicle_rental_contracts
        (company_id, order_type_id, order_serial_no, contract_serial, vehicle_id, customer_id, km_out, contract_kind, rental_duration,
         base_rent_amount, extra_day_rate, extra_km_rate, contract_date, expected_end_date, expected_days, additional_driver_1_id,
         additional_driver_2_id, insurance_party, insurance_amount, notes, created_by)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
      $st->execute([
        $cid, (int)$orderType['id'], $orderSerialNo, $contractSerial, $vehicleId, $customerId, $kmOut, $contractKind, $rentalDuration,
        $baseRentAmount, $extraDayRate, $extraKmRate, $contractDate, $expectedEndDate, $expectedDays, $ad1, $ad2,
        $insuranceParty, $insuranceAmount, $notes, $uid ?: null
      ]);
      $contractId = (int)$pdo->lastInsertId();
      audit_log($pdo, ['company_id' => $cid, 'user_id' => $uid, 'module' => 'fleet', 'action' => 'CREATE_RENTAL_CONTRACT', 'entity_type' => 'vehicle_rental_contract', 'entity_id' => (string)$contractId, 'description' => 'إنشاء عقد تأجير ' . $contractSerial]);
      $pdo->commit();
      $msg = 'تم تسجيل عقد التأجير برقم ' . $contractSerial;
    }

    if ($action === 'update') {
      $id = (int)($_POST['id'] ?? 0);
      $vehicleId = (int)($_POST['vehicle_id'] ?? 0);
      $customerId = (int)($_POST['customer_id'] ?? 0) ?: null;
      $kmOut = fleet_parse_money($_POST['km_out'] ?? 0);
      $contractKind = strtoupper(trim((string)($_POST['contract_kind'] ?? 'COMMERCIAL')));
      $rentalDuration = strtoupper(trim((string)($_POST['rental_duration'] ?? 'MONTHLY')));
      $contractDate = trim((string)($_POST['contract_date'] ?? date('Y-m-d')));
      $expectedEndDate = trim((string)($_POST['expected_end_date'] ?? '')) ?: fleet_rental_expected_end($contractDate, $rentalDuration);
      $baseRentAmount = $contractKind === 'SERVICE' ? 0 : fleet_parse_money($_POST['base_rent_amount'] ?? 0);
      $extraKmRate = $contractKind === 'SERVICE' ? 0 : fleet_parse_money($_POST['extra_km_rate'] ?? 0);
      $extraDayRate = $contractKind === 'SERVICE' ? 0 : fleet_parse_money($_POST['extra_day_rate'] ?? 0);
      $insuranceParty = strtoupper(trim((string)($_POST['insurance_party'] ?? 'COMPANY')));
      $insuranceAmount = $insuranceParty === 'CLIENT' ? fleet_parse_money($_POST['insurance_amount'] ?? 0) : 0;
      $expectedDays = max(1, (int)ceil((strtotime($expectedEndDate) - strtotime($contractDate)) / 86400));
      $ad1 = (int)($_POST['additional_driver_1_id'] ?? 0) ?: null;
      $ad2 = (int)($_POST['additional_driver_2_id'] ?? 0) ?: null;
      $notes = trim((string)($_POST['notes'] ?? ''));

      $old = $pdo->prepare("SELECT status, contract_serial FROM vehicle_rental_contracts WHERE id=? AND company_id=? LIMIT 1");
      $old->execute([$id, $cid]);
      $oldRow = $old->fetch(PDO::FETCH_ASSOC);
      if (!$oldRow) throw new RuntimeException('العقد غير موجود.');
      if (($oldRow['status'] ?? '') !== 'ACTIVE') throw new RuntimeException('لا يمكن تعديل عقد غير نشط.');
      if ($expectedEndDate <= $contractDate) throw new RuntimeException('تاريخ الغلق المتوقع يجب أن يكون بعد تاريخ العقد.');

      $pdo->prepare("UPDATE vehicle_rental_contracts SET vehicle_id=?, customer_id=?, km_out=?, contract_kind=?, rental_duration=?, base_rent_amount=?, extra_day_rate=?, extra_km_rate=?, contract_date=?, expected_end_date=?, expected_days=?, additional_driver_1_id=?, additional_driver_2_id=?, insurance_party=?, insurance_amount=?, notes=?, updated_at=NOW() WHERE id=? AND company_id=?")
          ->execute([$vehicleId, $customerId, $kmOut, $contractKind, $rentalDuration, $baseRentAmount, $extraDayRate, $extraKmRate, $contractDate, $expectedEndDate, $expectedDays, $ad1, $ad2, $insuranceParty, $insuranceAmount, $notes, $id, $cid]);
      audit_log($pdo, ['company_id' => $cid, 'user_id' => $uid, 'module' => 'fleet', 'action' => 'UPDATE_RENTAL_CONTRACT', 'entity_type' => 'vehicle_rental_contract', 'entity_id' => (string)$id, 'description' => 'تعديل عقد التأجير ' . $oldRow['contract_serial']]);
      $msg = 'تم تعديل بيانات العقد.';
    }

    if ($action === 'add_maintenance') {
      $id = (int)($_POST['contract_id'] ?? 0);
      $itemName = trim((string)($_POST['item_name'] ?? ''));
      $itemNameCustom = trim((string)($_POST['item_name_custom'] ?? ''));
      $itemName = $itemName === 'OTHER' ? $itemNameCustom : $itemName;
      $amount = fleet_parse_money($_POST['amount'] ?? 0);
      $notes = trim((string)($_POST['notes'] ?? ''));
      if ($itemName === '') throw new RuntimeException('اختر بند الصيانة.');
      if ($amount < 0) throw new RuntimeException('قيمة الصيانة غير صحيحة.');

      $st = $pdo->prepare("SELECT id, contract_serial, status FROM vehicle_rental_contracts WHERE id=? AND company_id=? LIMIT 1");
      $st->execute([$id, $cid]);
      $contract = $st->fetch(PDO::FETCH_ASSOC);
      if (!$contract) throw new RuntimeException('العقد غير موجود.');
      if (($contract['status'] ?? '') !== 'ACTIVE') throw new RuntimeException('لا يمكن إضافة بنود بعد إنهاء العقد.');

      $pdo->prepare("INSERT INTO vehicle_rental_maintenance_items (company_id, contract_id, item_name, charge_to, amount, notes, created_by) VALUES (?,?,?,?,?,?,?)")
          ->execute([$cid, $id, $itemName, 'CLIENT', $amount, $notes ?: null, $uid ?: null]);
      audit_log($pdo, ['company_id' => $cid, 'user_id' => $uid, 'module' => 'fleet', 'action' => 'ADD_RENTAL_MAINTENANCE', 'entity_type' => 'vehicle_rental_contract', 'entity_id' => (string)$id, 'description' => 'إضافة بند صيانة على العميل لعقد ' . $contract['contract_serial']]);
      $msg = 'تم إضافة بند الصيانة على العميل.';
    }

    if ($action === 'delete_maintenance') {
      $id = (int)($_POST['id'] ?? 0);
      $contractId = (int)($_POST['contract_id'] ?? 0);
      $pdo->prepare("DELETE FROM vehicle_rental_maintenance_items WHERE id=? AND contract_id=? AND company_id=?")
          ->execute([$id, $contractId, $cid]);
      $msg = 'تم حذف بند الصيانة.';
    }

    if ($action === 'close') {
      $id = (int)($_POST['id'] ?? 0);
      $actualEndDate = trim((string)($_POST['actual_end_date'] ?? date('Y-m-d')));
      $kmIn = fleet_parse_money($_POST['km_in'] ?? 0);
      $paymentType = strtoupper(trim((string)($_POST['payment_type'] ?? 'CASH')));
      $paymentDueDate = trim((string)($_POST['payment_due_date'] ?? date('Y-m-d', strtotime('+1 day'))));
      $returnCondition = strtoupper(trim((string)($_POST['return_condition'] ?? 'GOOD')));
      $closedNotes = trim((string)($_POST['closed_notes'] ?? ''));

      $st = $pdo->prepare("SELECT c.*, ot.revenue_account_id, COALESCE((SELECT SUM(amount) FROM vehicle_rental_maintenance_items m WHERE m.company_id=c.company_id AND m.contract_id=c.id AND m.charge_to='CLIENT'),0) AS maintenance_total
                           FROM vehicle_rental_contracts c
                           LEFT JOIN vehicle_order_types ot ON ot.id=c.order_type_id AND ot.company_id=c.company_id
                           WHERE c.id=? AND c.company_id=? LIMIT 1");
      $st->execute([$id, $cid]);
      $contract = $st->fetch(PDO::FETCH_ASSOC);
      if (!$contract) throw new RuntimeException('العقد غير موجود.');
      if (($contract['status'] ?? '') !== 'ACTIVE') throw new RuntimeException('العقد منتهي بالفعل.');
      if ($actualEndDate <= ($contract['contract_date'] ?? '')) throw new RuntimeException('تاريخ الغلق الفعلي يجب أن يكون بعد تاريخ العقد.');
      if ($kmIn < (float)$contract['km_out']) throw new RuntimeException('كم الدخول يجب أن يكون أكبر من أو يساوي كم الخروج.');

      $usedKm = round($kmIn - (float)$contract['km_out'], 2);
      $actualDays = max(1, (int)ceil((strtotime($actualEndDate) - strtotime((string)$contract['contract_date'])) / 86400));
      $expectedDays = max(1, (int)($contract['expected_days'] ?? fleet_rental_expected_days((string)$contract['rental_duration'])));
      $extraDays = max(0, $actualDays - $expectedDays);
      $extraKm = max(0, $usedKm - 0);
      $base = fleet_parse_money($contract['base_rent_amount'] ?? 0);
      $maintenanceTotal = fleet_parse_money($contract['maintenance_total'] ?? 0);
      $gross = strtoupper((string)$contract['contract_kind']) === 'SERVICE' ? 0 : round($base + ($extraDays * fleet_parse_money($contract['extra_day_rate'] ?? 0)) + ($extraKm * fleet_parse_money($contract['extra_km_rate'] ?? 0)) + $maintenanceTotal, 2);
      $insuranceRefund = (strtoupper((string)$contract['insurance_party']) === 'CLIENT' && $returnCondition === 'GOOD') ? fleet_parse_money($contract['insurance_amount'] ?? 0) : 0;
      $net = max(0, round($gross - $insuranceRefund, 2));

      $entryId = null;
      $revenueAcc = (int)($contract['revenue_account_id'] ?? 0);
      if ($gross > 0 && $revenueAcc > 0 && fleet_table_exists($pdo, 'customers') && !empty($contract['customer_id'])) {
        $cs = $pdo->prepare("SELECT account_id, full_name FROM customers WHERE company_id=? AND id=? LIMIT 1");
        $cs->execute([$cid, (int)$contract['customer_id']]);
        $customer = $cs->fetch(PDO::FETCH_ASSOC) ?: [];
        $customerAcc = (int)($customer['account_id'] ?? 0);
        if ($customerAcc > 0) {
          $lines = [
            ['account_id' => $customerAcc, 'debit' => $gross, 'credit' => 0, 'description' => 'مديونية العميل - ' . (string)$contract['contract_serial']],
            ['account_id' => $revenueAcc, 'debit' => 0, 'credit' => $gross, 'description' => 'إيراد تأجير سيارات - ' . (string)$contract['contract_serial']],
          ];
          if ($insuranceRefund > 0) {
            $lines[] = ['account_id' => $revenueAcc, 'debit' => $insuranceRefund, 'credit' => 0, 'description' => 'خصم تأمين مردود - ' . (string)$contract['contract_serial']];
            $lines[] = ['account_id' => $customerAcc, 'debit' => 0, 'credit' => $insuranceRefund, 'description' => 'رد تأمين العميل - ' . (string)$contract['contract_serial']];
          }
          $entryId = $svc->createManualJournal($cid, $actualEndDate, (string)$contract['contract_serial'], 'إقفال عقد تأجير سيارات ' . (string)$contract['contract_serial'], $lines, $uid ?: null, 'MANUAL', $id);
        }
      }

      $pdo->prepare("UPDATE vehicle_rental_contracts SET actual_end_date=?, km_in=?, used_km=?, actual_days=?, extra_days=?, extra_km=?, maintenance_charge=?, gross_amount=?, insurance_refund=?, net_amount=?, payment_type=?, payment_due_date=?, return_condition=?, closed_notes=?, posted_entry_id=?, status='CLOSED', updated_at=NOW() WHERE id=? AND company_id=?")
          ->execute([$actualEndDate, $kmIn, $usedKm, $actualDays, $extraDays, $extraKm, $maintenanceTotal, $gross, $insuranceRefund, $net, $paymentType, $paymentType === 'CREDIT' ? $paymentDueDate : null, $returnCondition, $closedNotes ?: null, $entryId, $id, $cid]);
      audit_log($pdo, ['company_id' => $cid, 'user_id' => $uid, 'module' => 'fleet', 'action' => 'CLOSE_RENTAL_CONTRACT', 'entity_type' => 'vehicle_rental_contract', 'entity_id' => (string)$id, 'description' => 'إنهاء عقد التأجير ' . $contract['contract_serial']]);
      $msg = 'تم إنهاء العقد وحساب التكلفة النهائية.';
    }

    if ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      $st = $pdo->prepare("SELECT contract_serial, status FROM vehicle_rental_contracts WHERE id=? AND company_id=? LIMIT 1");
      $st->execute([$id, $cid]);
      $contract = $st->fetch(PDO::FETCH_ASSOC);
      if (!$contract) throw new RuntimeException('العقد غير موجود.');
      if (fleet_contract_has_links($pdo, $cid, $id, (string)$contract['contract_serial'])) {
        throw new RuntimeException('لا يمكن حذف السريال لأنه مرتبط ببيانات أخرى داخل النظام.');
      }
      $pdo->prepare("DELETE FROM vehicle_rental_contracts WHERE id=? AND company_id=?")->execute([$id, $cid]);
      audit_log($pdo, ['company_id' => $cid, 'user_id' => $uid, 'module' => 'fleet', 'action' => 'DELETE_RENTAL_CONTRACT', 'entity_type' => 'vehicle_rental_contract', 'entity_id' => (string)$id, 'description' => 'حذف عقد التأجير ' . $contract['contract_serial']]);
      $msg = 'تم حذف العقد والسريال الخاص به.';
    }
  } catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $err = $e->getMessage();
  }
}

$vehicles = [];
if (fleet_table_exists($pdo, 'vehicles')) {
  $st = $pdo->prepare("SELECT * FROM vehicles WHERE company_id=? ORDER BY id DESC");
  $st->execute([$cid]);
  $vehicles = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
}
$vehicleMap = [];
foreach ($vehicles as $v) $vehicleMap[(int)$v['id']] = fleet_vehicle_label($v);

$customers = [];
if (fleet_table_exists($pdo, 'customers')) {
  $nameCol = fleet_col_exists($pdo, 'customers', 'full_name') ? 'full_name' : 'name';
  $st = $pdo->prepare("SELECT id, {$nameCol} AS full_name, account_id FROM customers WHERE company_id=? ORDER BY {$nameCol}");
  $st->execute([$cid]);
  $customers = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
}
$customerMap = [];
foreach ($customers as $c) $customerMap[(int)$c['id']] = $c['full_name'];

$contractsQ = $pdo->prepare("SELECT c.*, 
  COALESCE(cu.full_name, '-') AS customer_name,
  COALESCE(ad1.full_name, '') AS ad1_name,
  COALESCE(ad2.full_name, '') AS ad2_name,
  COALESCE((SELECT SUM(m.amount) FROM vehicle_rental_maintenance_items m WHERE m.company_id=c.company_id AND m.contract_id=c.id AND m.charge_to='CLIENT'),0) AS maintenance_total,
  COALESCE((SELECT COUNT(*) FROM vehicle_rental_maintenance_items m WHERE m.company_id=c.company_id AND m.contract_id=c.id),0) AS maintenance_count
  FROM vehicle_rental_contracts c
  LEFT JOIN customers cu ON cu.id=c.customer_id AND cu.company_id=c.company_id
  LEFT JOIN customers ad1 ON ad1.id=c.additional_driver_1_id AND ad1.company_id=c.company_id
  LEFT JOIN customers ad2 ON ad2.id=c.additional_driver_2_id AND ad2.company_id=c.company_id
  WHERE c.company_id=?
  ORDER BY c.id DESC");
$contractsQ->execute([$cid]);
$rows = $contractsQ->fetchAll(PDO::FETCH_ASSOC) ?: [];

$maintenanceByContract = [];
if ($rows) {
  $ids = array_map(fn($r) => (int)$r['id'], $rows);
  $placeholders = implode(',', array_fill(0, count($ids), '?'));
  $params = array_merge([$cid], $ids);
  $q = $pdo->prepare("SELECT * FROM vehicle_rental_maintenance_items WHERE company_id=? AND contract_id IN ($placeholders) ORDER BY id DESC");
  $q->execute($params);
  foreach (($q->fetchAll(PDO::FETCH_ASSOC) ?: []) as $m) $maintenanceByContract[(int)$m['contract_id']][] = $m;
}

$rentType = fleet_find_order_type($pdo, $cid, 'RENT');
$nextSerialPreview = $rentType ? ('RENT-' . (((int)$rentType['current_no'] > 0 ? (int)$rentType['current_no'] : (int)$rentType['start_no']) + ((int)$rentType['current_no'] > 0 ? 1 : 0))) : 'RENT-1';
if ($rentType) {
  $cur = (int)$rentType['current_no'];
  $nextSerialPreview = 'RENT-' . ($cur > 0 ? ($cur + 1) : max(1, (int)$rentType['start_no']));
}

render_layout('تأجير السيارات', 'إدارة السيارات <span class="mx-1">/</span> تأجير السيارات', function() use($rows,$vehicles,$vehicleMap,$customers,$customerMap,$maintenanceByContract,$msg,$err,$nextSerialPreview){ ?>
<style>
#rentalModal .bootstrap-select, #closeRentalModal .bootstrap-select, #maintenanceModal .bootstrap-select{width:100% !important;}
.rental-maintenance-tags .badge{margin:.12rem; font-weight:500;}
.rental-table td, .rental-table th{vertical-align:middle; white-space:nowrap;}
.rental-card-note{font-size:.82rem;color:#6c757d;}
.rental-table-wrap{overflow-x:auto; overflow-y:visible;}
.rental-row-main{cursor:pointer;}
.rental-row-main:hover{background:#fafbfc;}
.rental-expand-icon{display:inline-flex; align-items:center; justify-content:center; width:1.35rem; height:1.35rem; border:1px solid #dee2e6; border-radius:50%; font-size:.8rem; color:#6c757d; background:#fff; margin-inline-start:.35rem; transition:transform .2s ease;}
.rental-row-main.is-open .rental-expand-icon{transform:rotate(180deg);}
.rental-details-row{background:#fcfcfd;}
.rental-details-box{border:1px solid #e9ecef; border-radius:14px; padding:1rem; background:#fff;}
.rental-details-grid{display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:.75rem;}
.rental-details-item{border:1px solid #eef1f4; border-radius:12px; padding:.75rem .9rem; background:#fbfcfe;}
.rental-details-label{font-size:.78rem; color:#6c757d; margin-bottom:.25rem;}
.rental-actions-cell .dropdown-menu{z-index:1080; min-width:13rem;}
</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">العقود مرتبطة افتراضياً بأمر التشغيل <strong>تأجير</strong>، والسريال يولد تلقائياً من جدول سريال أوامر التشغيل ولا يمكن تعديله.</div>
    </div>
    <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#rentalModal"><i class="bi bi-plus-lg"></i> عقد تأجير جديد</button>
  </div>

  <?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 rental-table-wrap p-3">
      <table class="table rental-table align-middle mb-0">
        <thead>
          <tr class="text-secondary small">
            <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="9" class="text-center text-secondary py-4">لا توجد عقود تأجير بعد.</td></tr><?php endif; ?>
          <?php foreach($rows as $r): ?>
          <tr class="rental-row-main" data-rental-row="<?= (int)$r['id'] ?>">
            <td>
              <?= (int)$r['id'] ?>
              <span class="rental-expand-icon"><i class="bi bi-chevron-down"></i></span>
            </td>
            <td class="fw-semibold">
              <?= h($r['contract_serial']) ?>
              <div class="small text-secondary">أمر تأجير</div>
            </td>
            <td>
              <?= h($vehicleMap[(int)$r['vehicle_id']] ?? ('#'.(int)$r['vehicle_id'])) ?>
              <div class="rental-card-note"><?= h($r['contract_date']) ?> → <?= h($r['expected_end_date']) ?></div>
            </td>
            <td>
              <?= h($r['customer_name']) ?>
              <?php if(!empty($r['ad1_name']) || !empty($r['ad2_name'])): ?>
                <div class="rental-card-note">إضافي: <?= h(trim(($r['ad1_name'] ?: '') . ' / ' . ($r['ad2_name'] ?: ''), ' /')) ?></div>
              <?php endif; ?>
            </td>
            <td>
              متوقع <?= (int)$r['expected_days'] ?> يوم
              <?php if(($r['status'] ?? '') === 'CLOSED'): ?>
                <div class="rental-card-note">فعلي <?= (int)$r['actual_days'] ?> / زائد <?= (int)$r['extra_days'] ?></div>
              <?php endif; ?>
            </td>
            <td class="text-end">
              <?= nf($r['base_rent_amount']) ?>
              <div class="rental-card-note">كم زائد <?= nf($r['extra_km_rate']) ?> / يوم زائد <?= nf($r['extra_day_rate']) ?></div>
            </td>
            <td class="text-end">
              <?php if(($r['status'] ?? '') === 'CLOSED'): ?>
                <strong><?= nf($r['net_amount']) ?></strong>
                <div class="rental-card-note">إجمالي <?= nf($r['gross_amount']) ?> / تأمين مردود <?= nf($r['insurance_refund']) ?></div>
              <?php else: ?>
                <span class="text-secondary">—</span>
              <?php endif; ?>
            </td>
            <td><span class="badge <?= fleet_rental_status_badge($r['status']) ?>"><?= h(fleet_rental_status_label($r['status'])) ?></span></td>
            <td class="text-end rental-actions-cell">
              <div class="dropdown">
                <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" data-bs-display="static" aria-expanded="false">الإجراءات</button>
                <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                  <?php if(($r['status'] ?? '') === 'ACTIVE'): ?>
                    <li><button type="button" class="dropdown-item btnEditRental"
                      data-id="<?= (int)$r['id'] ?>"
                      data-serial="<?= h($r['contract_serial']) ?>"
                      data-vehicle="<?= (int)$r['vehicle_id'] ?>"
                      data-customer="<?= (int)$r['customer_id'] ?>"
                      data-kmout="<?= h($r['km_out']) ?>"
                      data-kind="<?= h($r['contract_kind']) ?>"
                      data-duration="<?= h($r['rental_duration']) ?>"
                      data-contractdate="<?= h($r['contract_date']) ?>"
                      data-expectedend="<?= h($r['expected_end_date']) ?>"
                      data-baserent="<?= h($r['base_rent_amount']) ?>"
                      data-extrakm="<?= h($r['extra_km_rate']) ?>"
                      data-extraday="<?= h($r['extra_day_rate']) ?>"
                      data-ad1="<?= (int)$r['additional_driver_1_id'] ?>"
                      data-ad2="<?= (int)$r['additional_driver_2_id'] ?>"
                      data-insuranceparty="<?= h($r['insurance_party']) ?>"
                      data-insuranceamount="<?= h($r['insurance_amount']) ?>"
                      data-notes="<?= h($r['notes']) ?>">تعديل البيانات</button></li>
                    <li><button type="button" class="dropdown-item btnCloseRental"
                      data-id="<?= (int)$r['id'] ?>"
                      data-serial="<?= h($r['contract_serial']) ?>"
                      data-kmout="<?= h($r['km_out']) ?>"
                      data-contractdate="<?= h($r['contract_date']) ?>"
                      data-expecteddays="<?= (int)$r['expected_days'] ?>"
                      data-baserent="<?= h($r['base_rent_amount']) ?>"
                      data-extrakm="<?= h($r['extra_km_rate']) ?>"
                      data-extraday="<?= h($r['extra_day_rate']) ?>"
                      data-insuranceparty="<?= h($r['insurance_party']) ?>"
                      data-insuranceamount="<?= h($r['insurance_amount']) ?>"
                      data-maintenance="<?= h($r['maintenance_total']) ?>"
                      data-kind="<?= h($r['contract_kind']) ?>">إنهاء العقد</button></li>
                    <li><button type="button" class="dropdown-item btnMaintenance" data-contract-id="<?= (int)$r['id'] ?>" data-contract-serial="<?= h($r['contract_serial']) ?>">الصيانات على العميل</button></li>
                    <li><hr class="dropdown-divider"></li>
                  <?php else: ?>
                    <li><span class="dropdown-item-text text-secondary small"><?= h(fleet_rental_label_payment($r['payment_type'])) ?><?= !empty($r['payment_due_date']) ? ' / '.h($r['payment_due_date']) : '' ?></span></li>
                    <li><hr class="dropdown-divider"></li>
                  <?php endif; ?>
                  <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>
          <tr class="rental-details-row d-none" data-rental-details="<?= (int)$r['id'] ?>">
            <td colspan="9">
              <div class="rental-details-box">
                <div class="rental-details-grid">
                  <div class="rental-details-item">
                    <div class="rental-details-label">نوع العقد</div>
                    <div class="fw-semibold"><?= h(fleet_rental_label_kind($r['contract_kind'])) ?></div>
                    <div class="rental-card-note mt-1"><?= h(fleet_rental_label_duration($r['rental_duration'])) ?></div>
                  </div>
                  <div class="rental-details-item">
                    <div class="rental-details-label">كم الخروج</div>
                    <div class="fw-semibold"><?= nf($r['km_out']) ?></div>
                    <?php if(($r['status'] ?? '') === 'CLOSED'): ?><div class="rental-card-note mt-1">كم الدخول <?= nf($r['km_in']) ?></div><?php endif; ?>
                  </div>
                  <div class="rental-details-item">
                    <div class="rental-details-label">الصيانة على العميل</div>
                    <div class="fw-semibold"><?= nf($r['maintenance_total']) ?></div>
                    <?php if(!empty($maintenanceByContract[(int)$r['id']])): ?>
                      <div class="rental-maintenance-tags mt-2">
                        <?php foreach($maintenanceByContract[(int)$r['id']] as $mi): ?>
                          <span class="badge bg-light text-dark border"><?= h($mi['item_name']) ?><?= (float)$mi['amount'] > 0 ? ' - '.nf($mi['amount']) : '' ?></span>
                        <?php endforeach; ?>
                      </div>
                    <?php else: ?>
                      <div class="rental-card-note mt-1">لا توجد بنود صيانة على العميل.</div>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="rentalModal" tabindex="-1">
  <div class="modal-dialog modal-xl"><div class="modal-content">
    <form method="post" id="rentalForm">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="create">
      <input type="hidden" name="id" value="">
      <div class="modal-header"><h5 class="modal-title">عقد تأجير جديد</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-3"><label class="form-label">أمر التشغيل</label><input class="form-control" value="أمر تأجير" readonly></div>
          <div class="col-md-3"><label class="form-label">سريال العقد</label><input class="form-control" name="contract_serial_preview" value="<?= h($nextSerialPreview) ?>" readonly></div>
          <div class="col-md-3"><label class="form-label">العميل الأساسي</label><select name="customer_id" class="form-select selectpicker" data-live-search="true" data-width="100%"><option value="">— بدون —</option><?php foreach($customers as $c): ?><option value="<?= (int)$c['id'] ?>"><?= h($c['full_name']) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-3"><label class="form-label">ملاحظات</label><input class="form-control" name="notes"></div>

          <div class="col-md-4"><label class="form-label">السيارة</label><select name="vehicle_id" class="form-select selectpicker" data-live-search="true" data-width="100%" required><?php foreach($vehicles as $v): ?><option value="<?= (int)$v['id'] ?>"><?= h($vehicleMap[(int)$v['id']] ?? ('#'.(int)$v['id'])) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-2"><label class="form-label">كم الخروج</label><input type="number" min="0" step="0.01" name="km_out" class="form-control" value="0" required></div>
          <div class="col-md-3"><label class="form-label">طبيعة العقد</label><select name="contract_kind" class="form-select"><option value="COMMERCIAL">تجاري</option><option value="SERVICE">خدمي</option></select></div>
          <div class="col-md-3"><label class="form-label">مدة العقد</label><select name="rental_duration" class="form-select"><option value="MONTHLY">شهري</option><option value="DAILY">يومي</option></select></div>

          <div class="col-md-3 commercial-only"><label class="form-label">سعر التأجير</label><input type="number" min="0" step="0.01" name="base_rent_amount" class="form-control" value="0"></div>
          <div class="col-md-3 commercial-only"><label class="form-label">سعر كم الزائد</label><input type="number" min="0" step="0.01" name="extra_km_rate" class="form-control" value="0"></div>
          <div class="col-md-3 commercial-only"><label class="form-label">قيمة اليوم الزائد</label><input type="number" min="0" step="0.01" name="extra_day_rate" class="form-control" value="0"></div>

          <div class="col-md-3"><label class="form-label">تاريخ العقد</label><input type="date" name="contract_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
          <div class="col-md-3"><label class="form-label">تاريخ الغلق المتوقع</label><input type="date" name="expected_end_date" class="form-control" value="<?= date('Y-m-d', strtotime('+30 days')) ?>"></div>

          <div class="col-md-3"><label class="form-label">السائق الإضافي الأول</label><select name="additional_driver_1_id" class="form-select selectpicker" data-live-search="true" data-width="100%"><option value="">— بدون —</option><?php foreach($customers as $c): ?><option value="<?= (int)$c['id'] ?>"><?= h($c['full_name']) ?></option><?php endforeach; ?></select></div>
          <div class="col-md-3"><label class="form-label">السائق الإضافي الثاني</label><select name="additional_driver_2_id" class="form-select selectpicker" data-live-search="true" data-width="100%"><option value="">— بدون —</option><?php foreach($customers as $c): ?><option value="<?= (int)$c['id'] ?>"><?= h($c['full_name']) ?></option><?php endforeach; ?></select></div>

          <div class="col-md-3"><label class="form-label">طريقة التأمين</label><select name="insurance_party" class="form-select"><option value="COMPANY">على الشركة</option><option value="CLIENT">على العميل</option></select></div>
          <div class="col-md-3 insurance-client-only"><label class="form-label">قيمة التأمين</label><input type="number" min="0" step="0.01" name="insurance_amount" class="form-control" value="0"></div>
          <div class="col-md-6 d-flex align-items-end"><div class="alert alert-light border mb-0 w-100">في العقد الخدمي لا يتم احتساب أي تكلفة. ويمكن إضافة الصيانات على العميل من زر الإجراءات بعد حفظ العقد.</div></div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-dark">حفظ العقد</button></div>
    </form>
  </div></div>
</div>

<div class="modal fade modal-erp" id="maintenanceModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <form method="post">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="add_maintenance">
      <input type="hidden" name="contract_id" value="">
      <div class="modal-header"><h5 class="modal-title">الصيانات على العميل</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="alert alert-light border small">اختر البنود التي يتحملها العميل مثل غيار زيت أو كاوتش أو تيل فرامل أو أي بند إضافي.</div>
        <div class="row g-3">
          <div class="col-12"><label class="form-label">العقد</label><input class="form-control" name="contract_serial" readonly></div>
          <div class="col-12"><label class="form-label">البند</label><select name="item_name" class="form-select"><option value="غيار زيت">غيار زيت</option><option value="غيار كاوتش">غيار كاوتش</option><option value="تيل فرامل">تيل فرامل</option><option value="بطارية">بطارية</option><option value="غسيل وتجهيز">غسيل وتجهيز</option><option value="مخالفات">مخالفات</option><option value="OTHER">أخرى</option></select></div>
          <div class="col-12 d-none" id="maintenanceCustomWrap"><label class="form-label">اسم البند</label><input class="form-control" name="item_name_custom"></div>
          <div class="col-md-6"><label class="form-label">القيمة</label><input type="number" min="0" step="0.01" name="amount" class="form-control" value="0"></div>
          <div class="col-md-6"><label class="form-label">ملاحظات</label><input class="form-control" name="notes"></div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-primary">إضافة</button></div>
    </form>
  </div></div>
</div>

<div class="modal fade modal-erp" id="closeRentalModal" tabindex="-1">
  <div class="modal-dialog modal-lg"><div class="modal-content">
    <form method="post" id="closeRentalForm">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="close">
      <input type="hidden" name="id" value="">
      <input type="hidden" name="calc_base_rent_amount" value="0">
      <input type="hidden" name="calc_extra_day_rate" value="0">
      <input type="hidden" name="calc_extra_km_rate" value="0">
      <input type="hidden" name="calc_contract_kind" value="COMMERCIAL">
      <input type="hidden" name="calc_insurance_party" value="COMPANY">
      <input type="hidden" name="calc_insurance_amount" value="0">
      <input type="hidden" name="calc_contract_date" value="<?= date('Y-m-d') ?>">
      <input type="hidden" name="calc_expected_days" value="30">
      <input type="hidden" name="calc_km_out" value="0">
      <input type="hidden" name="calc_maintenance" value="0">
      <div class="modal-header"><h5 class="modal-title">إنهاء عقد التأجير</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-4"><label class="form-label">السريال</label><input class="form-control" name="contract_serial" readonly></div>
          <div class="col-md-4"><label class="form-label">تاريخ الغلق الفعلي</label><input type="date" name="actual_end_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
          <div class="col-md-4"><label class="form-label">كم الدخول</label><input type="number" step="0.01" min="0" name="km_in" class="form-control" value="0"></div>

          <div class="col-md-4"><label class="form-label">طريقة السداد</label><select name="payment_type" class="form-select"><option value="CASH">نقدي</option><option value="CREDIT">آجل</option></select></div>
          <div class="col-md-4 credit-only"><label class="form-label">تاريخ السداد</label><input type="date" name="payment_due_date" class="form-control" value="<?= date('Y-m-d', strtotime('+1 day')) ?>"></div>
          <div class="col-md-4"><label class="form-label">حالة السيارة</label><select name="return_condition" class="form-select"><option value="GOOD">جيدة</option><option value="DAMAGED">يوجد ملاحظات</option></select></div>

          <div class="col-12"><label class="form-label">ملاحظات الغلق</label><textarea name="closed_notes" class="form-control" rows="2"></textarea></div>

          <div class="col-12">
            <div class="card bg-light border-0">
              <div class="card-body small">
                <div class="row g-2">
                  <div class="col-md-4">عدد الأيام الفعلي: <strong id="calcActualDays">0</strong></div>
                  <div class="col-md-4">عدد الأيام الزائدة: <strong id="calcExtraDays">0</strong></div>
                  <div class="col-md-4">كم المستخدم: <strong id="calcUsedKm">0</strong></div>
                  <div class="col-md-4">الكم الزائد المحتسب: <strong id="calcExtraKm">0</strong></div>
                  <div class="col-md-4">الصيانات على العميل: <strong id="calcMaintenance">0.00</strong></div>
                  <div class="col-md-4">إجمالي العقد: <strong id="calcGross">0.00</strong></div>
                  <div class="col-md-4">خصم التأمين: <strong id="calcInsuranceRefund">0.00</strong></div>
                  <div class="col-md-4">المستحق النهائي: <strong id="calcNet">0.00</strong></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-dark">اعتماد الغلق</button></div>
    </form>
  </div></div>
</div>

<script>
(function(){
  const rentalModal = document.getElementById('rentalModal');
  const closeModal = document.getElementById('closeRentalModal');
  const maintenanceModal = document.getElementById('maintenanceModal');

  document.querySelectorAll('.rental-row-main').forEach(function(row){
    row.addEventListener('click', function(e){
      if (e.target.closest('button, .dropdown, .dropdown-menu, a, input, select, textarea, form, label')) return;
      const id = row.dataset.rentalRow;
      const details = document.querySelector('[data-rental-details="' + id + '"]');
      if (!details) return;
      details.classList.toggle('d-none');
      row.classList.toggle('is-open', !details.classList.contains('d-none'));
    });
  });

  function refreshSelects(scope){
    (scope || document).querySelectorAll('.selectpicker').forEach(function(el){
      if (window.jQuery && jQuery(el).selectpicker) jQuery(el).selectpicker('refresh');
    });
  }

  function syncRentalVisibility(){
    const kind = rentalModal.querySelector('[name=contract_kind]').value;
    const duration = rentalModal.querySelector('[name=rental_duration]').value;
    const insuranceParty = rentalModal.querySelector('[name=insurance_party]').value;
    rentalModal.querySelectorAll('.commercial-only').forEach(el => el.classList.toggle('d-none', kind !== 'COMMERCIAL'));
    rentalModal.querySelectorAll('.insurance-client-only').forEach(el => el.classList.toggle('d-none', insuranceParty !== 'CLIENT'));
    const contractDate = rentalModal.querySelector('[name=contract_date]').value || '<?= date('Y-m-d') ?>';
    const expected = new Date(contractDate + 'T00:00:00');
    expected.setDate(expected.getDate() + (duration === 'DAILY' ? 7 : 30));
    rentalModal.querySelector('[name=expected_end_date]').value = expected.toISOString().slice(0,10);
    if (kind !== 'COMMERCIAL') {
      rentalModal.querySelector('[name=base_rent_amount]').value = '0';
      rentalModal.querySelector('[name=extra_km_rate]').value = '0';
      rentalModal.querySelector('[name=extra_day_rate]').value = '0';
    }
    if (insuranceParty !== 'CLIENT') rentalModal.querySelector('[name=insurance_amount]').value = '0';
  }

  rentalModal.querySelector('[name=contract_kind]').addEventListener('change', syncRentalVisibility);
  rentalModal.querySelector('[name=rental_duration]').addEventListener('change', syncRentalVisibility);
  rentalModal.querySelector('[name=insurance_party]').addEventListener('change', syncRentalVisibility);
  rentalModal.querySelector('[name=contract_date]').addEventListener('change', syncRentalVisibility);

  document.querySelectorAll('.btnEditRental').forEach(function(btn){
    btn.addEventListener('click', function(){
      rentalModal.querySelector('.modal-title').textContent = 'تعديل بيانات العقد';
      rentalModal.querySelector('[name=action]').value = 'update';
      rentalModal.querySelector('[name=id]').value = btn.dataset.id || '';
      rentalModal.querySelector('[name=contract_serial_preview]').value = btn.dataset.serial || '';
      const map = {
        vehicle_id:'vehicle', customer_id:'customer', km_out:'kmout', contract_kind:'kind', rental_duration:'duration', contract_date:'contractdate', expected_end_date:'expectedend',
        base_rent_amount:'baserent', extra_km_rate:'extrakm', extra_day_rate:'extraday', additional_driver_1_id:'ad1', additional_driver_2_id:'ad2', insurance_party:'insuranceparty', insurance_amount:'insuranceamount', notes:'notes'
      };
      Object.keys(map).forEach(function(name){
        const field = rentalModal.querySelector('[name='+name+']');
        if (field) field.value = btn.dataset[map[name]] || '';
      });
      syncRentalVisibility();
      refreshSelects(rentalModal);
      bootstrap.Modal.getOrCreateInstance(rentalModal).show();
    });
  });

  rentalModal.addEventListener('hidden.bs.modal', function(){
    const f = rentalModal.querySelector('form');
    f.reset();
    rentalModal.querySelector('.modal-title').textContent = 'عقد تأجير جديد';
    rentalModal.querySelector('[name=action]').value = 'create';
    rentalModal.querySelector('[name=id]').value = '';
    rentalModal.querySelector('[name=contract_serial_preview]').value = '<?= h($nextSerialPreview) ?>';
    rentalModal.querySelector('[name=contract_date]').value = '<?= date('Y-m-d') ?>';
    rentalModal.querySelector('[name=expected_end_date]').value = '<?= date('Y-m-d', strtotime('+30 days')) ?>';
    syncRentalVisibility();
    refreshSelects(rentalModal);
  });

  maintenanceModal.querySelector('[name=item_name]').addEventListener('change', function(){
    const custom = document.getElementById('maintenanceCustomWrap');
    custom.classList.toggle('d-none', this.value !== 'OTHER');
  });
  document.querySelectorAll('.btnMaintenance').forEach(function(btn){
    btn.addEventListener('click', function(){
      maintenanceModal.querySelector('[name=contract_id]').value = btn.dataset.contractId || '';
      maintenanceModal.querySelector('[name=contract_serial]').value = btn.dataset.contractSerial || '';
      bootstrap.Modal.getOrCreateInstance(maintenanceModal).show();
    });
  });

  function recalcClose(){
    const form = closeModal.querySelector('form');
    const kmOut = parseFloat(form.querySelector('[name=calc_km_out]').value || '0');
    const kmIn = parseFloat(form.querySelector('[name=km_in]').value || '0');
    const contractDate = new Date((form.querySelector('[name=calc_contract_date]').value || '<?= date('Y-m-d') ?>') + 'T00:00:00');
    const actualEndDateVal = form.querySelector('[name=actual_end_date]').value || '<?= date('Y-m-d') ?>';
    const actualEndDate = new Date(actualEndDateVal + 'T00:00:00');
    const expectedDays = parseInt(form.querySelector('[name=calc_expected_days]').value || '0', 10);
    const baseRent = parseFloat(form.querySelector('[name=calc_base_rent_amount]').value || '0');
    const extraDayRate = parseFloat(form.querySelector('[name=calc_extra_day_rate]').value || '0');
    const extraKmRate = parseFloat(form.querySelector('[name=calc_extra_km_rate]').value || '0');
    const maintenance = parseFloat(form.querySelector('[name=calc_maintenance]').value || '0');
    const insuranceParty = form.querySelector('[name=calc_insurance_party]').value || 'COMPANY';
    const insuranceAmount = parseFloat(form.querySelector('[name=calc_insurance_amount]').value || '0');
    const kind = form.querySelector('[name=calc_contract_kind]').value || 'COMMERCIAL';
    const returnCondition = form.querySelector('[name=return_condition]').value || 'GOOD';

    let actualDays = Math.ceil((actualEndDate - contractDate) / 86400000);
    if (!isFinite(actualDays) || actualDays < 1) actualDays = 1;
    const extraDays = Math.max(0, actualDays - expectedDays);
    const usedKm = Math.max(0, kmIn - kmOut);
    const extraKm = Math.max(0, usedKm);
    let gross = 0;
    if (kind === 'COMMERCIAL') gross = baseRent + (extraDays * extraDayRate) + (extraKm * extraKmRate) + maintenance;
    const insuranceRefund = (insuranceParty === 'CLIENT' && returnCondition === 'GOOD') ? insuranceAmount : 0;
    const net = Math.max(0, gross - insuranceRefund);

    document.getElementById('calcActualDays').textContent = actualDays;
    document.getElementById('calcExtraDays').textContent = extraDays;
    document.getElementById('calcUsedKm').textContent = usedKm.toFixed(2);
    document.getElementById('calcExtraKm').textContent = extraKm.toFixed(2);
    document.getElementById('calcMaintenance').textContent = maintenance.toFixed(2);
    document.getElementById('calcGross').textContent = gross.toFixed(2);
    document.getElementById('calcInsuranceRefund').textContent = insuranceRefund.toFixed(2);
    document.getElementById('calcNet').textContent = net.toFixed(2);
    closeModal.querySelectorAll('.credit-only').forEach(el => el.classList.toggle('d-none', form.querySelector('[name=payment_type]').value !== 'CREDIT'));
  }

  document.querySelectorAll('.btnCloseRental').forEach(function(btn){
    btn.addEventListener('click', function(){
      const form = closeModal.querySelector('form');
      form.querySelector('[name=id]').value = btn.dataset.id || '';
      form.querySelector('[name=contract_serial]').value = btn.dataset.serial || '';
      form.querySelector('[name=km_in]').value = btn.dataset.kmout || '0';
      form.querySelector('[name=calc_km_out]').value = btn.dataset.kmout || '0';
      form.querySelector('[name=calc_contract_date]').value = btn.dataset.contractdate || '<?= date('Y-m-d') ?>';
      form.querySelector('[name=calc_expected_days]').value = btn.dataset.expecteddays || '30';
      form.querySelector('[name=calc_base_rent_amount]').value = btn.dataset.baserent || '0';
      form.querySelector('[name=calc_extra_day_rate]').value = btn.dataset.extraday || '0';
      form.querySelector('[name=calc_extra_km_rate]').value = btn.dataset.extrakm || '0';
      form.querySelector('[name=calc_contract_kind]').value = btn.dataset.kind || 'COMMERCIAL';
      form.querySelector('[name=calc_insurance_party]').value = btn.dataset.insuranceparty || 'COMPANY';
      form.querySelector('[name=calc_insurance_amount]').value = btn.dataset.insuranceamount || '0';
      form.querySelector('[name=calc_maintenance]').value = btn.dataset.maintenance || '0';
      form.querySelector('[name=actual_end_date]').value = '<?= date('Y-m-d') ?>';
      form.querySelector('[name=payment_type]').value = 'CASH';
      form.querySelector('[name=payment_due_date]').value = '<?= date('Y-m-d', strtotime('+1 day')) ?>';
      form.querySelector('[name=return_condition]').value = 'GOOD';
      recalcClose();
      bootstrap.Modal.getOrCreateInstance(closeModal).show();
    });
  });
  ['actual_end_date','km_in','payment_type','return_condition'].forEach(function(name){
    closeModal.querySelector('[name='+name+']').addEventListener('input', recalcClose);
    closeModal.querySelector('[name='+name+']').addEventListener('change', recalcClose);
  });
  closeModal.addEventListener('shown.bs.modal', recalcClose);

  syncRentalVisibility();
  refreshSelects(document);
})();
</script>
<?php });
