<?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__ . '/../fleet/_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);
fleet_ensure_rental_schema($pdo);
fleet_ensure_receipts_schema($pdo);
csrf_bootstrap();

$svc = new AccountingService($pdo);
$acc = fleet_default_accounts($pdo, $cid);
$msg = '';
$err = '';

$cashAccounts = $pdo->prepare("SELECT id, code, name FROM accounts WHERE company_id=? AND is_active=1 AND (is_cash=1 OR code IN ('1110','1120')) ORDER BY code");
$cashAccounts->execute([$cid]);
$cashOptions = $cashAccounts->fetchAll(PDO::FETCH_ASSOC);

$limoOptionsStmt = $pdo->prepare("SELECT t.id,
    ls.serial_no,
    t.display_no,
    t.trip_date,
    t.customer_id,
    COALESCE(c.full_name, '-') AS customer_name,
    t.trip_amount AS total_amount,
    COALESCE((SELECT SUM(vr.amount) FROM vehicle_receipts vr WHERE vr.company_id=t.company_id AND vr.source_type='LIMO' AND vr.source_id=t.id),0) AS collected_amount
  FROM fleet_limo_trips t
  JOIN fleet_limo_serials ls ON ls.id=t.serial_id AND ls.company_id=t.company_id
  LEFT JOIN customers c ON c.id=t.customer_id AND c.company_id=t.company_id
  WHERE t.company_id=? AND t.trip_status <> 'CANCELLED'
  ORDER BY t.trip_date DESC, t.id DESC");
$limoOptionsStmt->execute([$cid]);
$limoOptions = $limoOptionsStmt->fetchAll(PDO::FETCH_ASSOC);

$rentOptionsStmt = $pdo->prepare("SELECT r.id,
    r.order_serial_no,
    r.contract_serial,
    r.contract_date,
    r.customer_id,
    COALESCE(c.full_name, '-') AS customer_name,
    CASE
      WHEN COALESCE(r.net_amount,0) > 0 THEN r.net_amount
      WHEN COALESCE(r.gross_amount,0) > 0 THEN r.gross_amount
      ELSE r.base_rent_amount
    END AS total_amount,
    COALESCE((SELECT SUM(vr.amount) FROM vehicle_receipts vr WHERE vr.company_id=r.company_id AND vr.source_type='RENT' AND vr.source_id=r.id),0) AS collected_amount
  FROM vehicle_rental_contracts r
  LEFT JOIN customers c ON c.id=r.customer_id AND c.company_id=r.company_id
  WHERE r.company_id=? AND r.status <> 'CANCELLED'
  ORDER BY r.contract_date DESC, r.id DESC");
$rentOptionsStmt->execute([$cid]);
$rentOptions = $rentOptionsStmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = trim((string)($_POST['action'] ?? ''));
  try {
    if ($action === 'create' || $action === 'update') {
      $isUpdate = $action === 'update';
      $editId = (int)($_POST['id'] ?? 0);
      if ($isUpdate) {
        $chk = $pdo->prepare("SELECT posted_entry_id FROM vehicle_receipts WHERE id=? AND company_id=? LIMIT 1");
        $chk->execute([$editId, $cid]);
        $postedEntryId = (int)($chk->fetchColumn() ?: 0);
        if ($postedEntryId > 0) throw new RuntimeException('لا يمكن تعديل سند مرحّل. قم بإلغاء الترحيل أولاً.');
      }

      $receiptNo = trim((string)($_POST['receipt_no'] ?? ''));
      if ($receiptNo === '') $receiptNo = fleet_receipt_next_code($pdo, $cid);
      $sourceType = strtoupper(trim((string)($_POST['source_type'] ?? 'ADVANCE')));
      $sourceId = (int)($_POST['source_id'] ?? 0) ?: null;
      $receiptDate = trim((string)($_POST['receipt_date'] ?? date('Y-m-d')));
      $cashAccountId = (int)($_POST['cash_account_id'] ?? $acc['cash_id']);
      $amount = (float)($_POST['amount'] ?? 0);
      $paymentMethod = strtoupper(trim((string)($_POST['payment_method'] ?? 'CASH')));
      $bankTxnType = strtoupper(trim((string)($_POST['bank_txn_type'] ?? 'INSTA')));
      $bankName = trim((string)($_POST['bank_name'] ?? ''));
      $bankAccountNo = trim((string)($_POST['bank_account_no'] ?? ''));
      $dueDate = trim((string)($_POST['due_date'] ?? ''));
      $memo = trim((string)($_POST['memo'] ?? ''));

      $meta = fleet_receipt_source_meta($pdo, $cid, $sourceType, $sourceId);
      $serialRef = $meta['serial_ref'];
      $operationRef = $meta['operation_ref'];
      $customerId = $sourceType === 'ADVANCE' ? null : ($meta['customer_id'] ?: null);
      if ($amount <= 0) {
        $amount = (float)($meta['amount'] ?? 0);
      }
      if ($amount <= 0) throw new RuntimeException('قيمة التحصيل يجب أن تكون أكبر من صفر.');
      if (!$cashAccountId) throw new RuntimeException('اختر الخزنة أو البنك.');
      if ($sourceType !== 'ADVANCE' && !$sourceId) throw new RuntimeException('اختر أمر التشغيل أو عقد التأجير.');

      if ($paymentMethod === 'BANK') {
        if (!in_array($bankTxnType, ['INSTA','CHEQUE'], true)) $bankTxnType = 'INSTA';
        if ($bankName === '' || $bankAccountNo === '') throw new RuntimeException('في التحصيل البنكي يجب تحديد البنك ورقم الحساب.');
        if ($bankTxnType === 'CHEQUE') {
          if ($dueDate === '') $dueDate = $receiptDate;
        } else {
          $dueDate = null;
        }
      } else {
        $bankTxnType = null;
        $bankName = '';
        $bankAccountNo = '';
        $dueDate = null;
      }

      if ($isUpdate) {
        $pdo->prepare("UPDATE vehicle_receipts SET receipt_no=?, source_type=?, source_id=?, serial_ref=?, operation_ref=?, customer_id=?, receipt_date=?, cash_account_id=?, amount=?, payment_method=?, bank_txn_type=?, bank_name=?, bank_account_no=?, due_date=?, memo=?, updated_at=NOW() WHERE id=? AND company_id=?")
            ->execute([$receiptNo, $sourceType, $sourceId, $serialRef, $operationRef, $customerId, $receiptDate, $cashAccountId, $amount, $paymentMethod, $bankTxnType, $bankName ?: null, $bankAccountNo ?: null, $dueDate ?: null, $memo ?: null, $editId, $cid]);
        $msg = 'تم تعديل سند تحصيل السيارات.';
      } else {
        $pdo->prepare("INSERT INTO vehicle_receipts (company_id, receipt_no, source_type, source_id, serial_ref, operation_ref, customer_id, receipt_date, cash_account_id, amount, payment_method, bank_txn_type, bank_name, bank_account_no, due_date, memo, created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([$cid, $receiptNo, $sourceType, $sourceId, $serialRef, $operationRef, $customerId, $receiptDate, $cashAccountId, $amount, $paymentMethod, $bankTxnType, $bankName ?: null, $bankAccountNo ?: null, $dueDate ?: null, $memo ?: null, $uid ?: null]);
        $msg = 'تم تسجيل سند تحصيل السيارات.';
      }
    } elseif ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      $chk = $pdo->prepare("SELECT posted_entry_id FROM vehicle_receipts WHERE id=? AND company_id=? LIMIT 1");
      $chk->execute([$id, $cid]);
      $postedEntryId = (int)($chk->fetchColumn() ?: 0);
      if ($postedEntryId > 0) throw new RuntimeException('لا يمكن حذف سند مرحّل. قم بإلغاء الترحيل أولاً.');
      $pdo->prepare("DELETE FROM vehicle_receipts WHERE id=? AND company_id=?")->execute([$id, $cid]);
      $msg = 'تم حذف سند التحصيل.';
    } elseif ($action === 'post_journal') {
      $id = (int)($_POST['id'] ?? 0);
      fleet_create_receipt_journal($pdo, $cid, $id, $uid);
      $msg = 'تم إنشاء قيد يومية لتحصيل السيارات.';
    } elseif ($action === 'unpost_journal') {
      $id = (int)($_POST['id'] ?? 0);
      fleet_unpost_receipt_journal($pdo, $cid, $id);
      $msg = 'تم إلغاء قيد تحصيل السيارات.';
    }
  } catch (Throwable $e) {
    $err = $e->getMessage();
  }
}

$list = $pdo->prepare("SELECT r.*, c.full_name AS customer_name, a.code AS cash_code, a.name AS cash_name
  FROM vehicle_receipts r
  LEFT JOIN customers c ON c.id=r.customer_id AND c.company_id=r.company_id
  LEFT JOIN accounts a ON a.id=r.cash_account_id
  WHERE r.company_id=?
  ORDER BY r.id DESC");
$list->execute([$cid]);
$rows = $list->fetchAll(PDO::FETCH_ASSOC);

render_layout('حسابات السيارات','الحسابات <span class="mx-1">/</span> حسابات السيارات', function() use($rows,$cashOptions,$limoOptions,$rentOptions,$msg,$err,$acc,$pdo,$cid){ ?>
<style>
#mReceipt .bootstrap-select{width:100% !important;max-width:100% !important;}
#mReceipt .dropdown-menu{max-width:100% !important;}
#mReceipt .dropdown-menu.inner{max-height:none !important;}
#mReceipt .dropdown-menu li.disabled a{font-weight:700;color:#495057 !important;background:#f8f9fa;}
</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">تحصيل نقدي أو بنكي بدلالة أمر التشغيل والسريال نمبر من الليموزين أو التأجير، أو تسجيل تحصيل مقدم تحت الحساب.</div>
    </div>
    <div class="d-flex flex-wrap gap-2">
      <a class="btn btn-outline-dark" href="<?= url('/journal/daily_posting.php') ?>"><i class="bi bi-journal-check"></i> ترحيل القيود</a>
      <button type="button" class="btn btn-dark" id="btnOpenReceipt" data-bs-toggle="modal" data-bs-target="#mReceipt"><i class="bi bi-plus-lg"></i> تسجيل تحصيل</button>
    </div>
  </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 p-3">
      <table class="table align-middle mb-0">
        <thead>
          <tr class="text-secondary small">
            <th>#</th>
            <th>رقم السند</th>
            <th>نوع التحصيل</th>
            <th>السريال</th>
            <th>أمر التشغيل/العقد</th>
            <th>التاريخ</th>
            <th>طريقة السداد</th>
            <th>الخزنة/البنك</th>
            <th>بيانات البنك</th>
            <th class="text-end">المبلغ</th>
            <th>القيد</th>
            <th class="text-end">إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php if(!$rows): ?>
            <tr><td colspan="12" class="text-center text-secondary py-4">لا توجد تحصيلات سيارات بعد.</td></tr>
          <?php endif; ?>
          <?php foreach($rows as $r): ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td class="fw-semibold"><?= h($r['receipt_no']) ?></td>
              <td><?php if(($r['source_type'] ?? '') === 'LIMO'): ?>أمر تشغيل ليموزين<?php elseif(($r['source_type'] ?? '') === 'RENT'): ?>عقد تأجير سيارات<?php else: ?>مقدم تحت الحساب<?php endif; ?></td>
              <td><?= h($r['serial_ref'] ?: '-') ?></td>
              <td><?= h($r['operation_ref'] ?: '-') ?></td>
              <td><?= h($r['receipt_date']) ?><?php if(!empty($r['due_date'])): ?><div class="small text-secondary">استحقاق: <?= h($r['due_date']) ?></div><?php endif; ?></td>
              <td><?php if(($r['payment_method'] ?? 'CASH') === 'BANK'): ?>بنكي<?php if(($r['bank_txn_type'] ?? '') === 'CHEQUE'): ?><div class="small text-secondary">شيك</div><?php else: ?><div class="small text-secondary">إنستا</div><?php endif; ?><?php else: ?>نقدي<?php endif; ?></td>
              <td class="small"><?= h(trim(($r['cash_code'] ?: '').' - '.($r['cash_name'] ?: ''))) ?></td>
              <td class="small"><?php if(($r['payment_method'] ?? '') === 'BANK'): ?><?= h($r['bank_name'] ?: '-') ?><div class="text-secondary">حساب: <?= h($r['bank_account_no'] ?: '-') ?></div><?php if(($r['bank_txn_type'] ?? '') === 'CHEQUE' && !empty($r['due_date'])): ?><div class="text-secondary">استحقاق الشيك: <?= h($r['due_date']) ?></div><?php endif; ?><?php else: ?>-<?php endif; ?></td>
              <td class="text-end"><?= nf($r['amount']) ?></td>
              <td><?php if(!empty($r['posted_entry_id'])): ?><span class="badge bg-success-subtle text-success border">مرحّل</span><?php else: ?><span class="badge bg-warning-subtle text-warning border">Draft</span><?php endif; ?></td>
              <td class="text-end">
                <button type="button" class="btn btn-outline-secondary btn-sm btnEdit"
                  data-id="<?= (int)$r['id'] ?>"
                  data-receiptno="<?= h($r['receipt_no']) ?>"
                  data-sourcetype="<?= h($r['source_type']) ?>"
                  data-sourceid="<?= (int)$r['source_id'] ?>"
                  data-date="<?= h($r['receipt_date']) ?>"
                  data-cash="<?= (int)$r['cash_account_id'] ?>"
                  data-amount="<?= h($r['amount']) ?>"
                  data-method="<?= h($r['payment_method']) ?>"
                  data-banktxntype="<?= h((string)($r['bank_txn_type'] ?? '')) ?>"
                  data-bankname="<?= h($r['bank_name']) ?>"
                  data-bankaccount="<?= h($r['bank_account_no']) ?>"
                  data-duedate="<?= h((string)$r['due_date']) ?>"
                  data-memo="<?= h($r['memo']) ?>"
                  <?= !empty($r['posted_entry_id']) ? 'disabled title="قم بإلغاء الترحيل أولاً"' : '' ?>><i class="bi bi-pencil"></i></button>
                <?php if(empty($r['posted_entry_id'])): ?>
                  <form method="post" class="d-inline" onsubmit="return confirm('إنشاء قيد يومية لهذا التحصيل؟');">
                    <?= csrf_field() ?><input type="hidden" name="action" value="post_journal"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-outline-success btn-sm"><i class="bi bi-journal-check"></i></button>
                  </form>
                <?php else: ?>
                  <form method="post" class="d-inline" onsubmit="return confirm('إلغاء قيد هذا التحصيل؟');">
                    <?= csrf_field() ?><input type="hidden" name="action" value="unpost_journal"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-outline-warning btn-sm"><i class="bi bi-arrow-counterclockwise"></i></button>
                  </form>
                <?php endif; ?>
                <form method="post" class="d-inline" onsubmit="return confirm('حذف سند التحصيل؟');">
                  <?= csrf_field() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-outline-danger btn-sm" <?= !empty($r['posted_entry_id']) ? 'disabled title="قم بإلغاء الترحيل أولاً"' : '' ?>><i class="bi bi-trash"></i></button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="mReceipt" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <form method="post" id="receiptForm">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="create" id="f_action">
        <input type="hidden" name="id" id="f_id">
        <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 modal-inline-grid">
            <div class="col-md-6">
              <label class="form-label">رقم السند</label>
              <input name="receipt_no" id="f_receipt_no" class="form-control bg-light" readonly>
            </div>
            <div class="col-md-6">
              <label class="form-label">نوع التحصيل</label>
              <select name="source_type" id="f_source_type" class="form-select js-manual-picker" data-live-search="false" data-size="false" data-width="100%" data-dropup-auto="false">
                <option value="LIMO">أمر تشغيل</option>
                <option value="RENT">أمر تأجير</option>
                <option value="ADVANCE">مقدم تحت الحساب</option>
              </select>
            </div>
            <div class="col-md-6 source-wrap">
              <label class="form-label">أمر التشغيل / العقد</label>
              <select name="source_id" id="f_source_id" class="form-select js-source-picker" data-live-search="true" data-size="false" data-width="100%" data-dropup-auto="false">
                <option value="">اختر</option>
                <?php foreach($limoOptions as $r):
                  $due = max(0, (float)$r['total_amount'] - (float)$r['collected_amount']);
                  $label = trim('سريال ' . ($r['serial_no'] ?? '-') . ' / أمر تشغيل ' . ($r['display_no'] ?? '-'));
                ?>
                  <option value="<?= (int)$r['id'] ?>"><?= h($label) ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-md-6">
              <label class="form-label">التاريخ</label>
              <input type="text" name="receipt_date" id="f_receipt_date" value="<?= h(date('Y-m-d')) ?>" class="form-control datepick" autocomplete="off">
            </div>
            <div class="col-md-6">
              <label class="form-label">الخزنة / البنك</label>
              <select name="cash_account_id" id="f_cash_account_id" class="form-select js-manual-picker" data-live-search="true" data-size="false" data-width="100%" data-dropup-auto="false">
                <?php foreach($cashOptions as $a): ?>
                  <option value="<?= (int)$a['id'] ?>" <?= (int)$a['id'] === (int)$acc['cash_id'] ? 'selected' : '' ?>><?= h(trim($a['code'].' - '.$a['name'])) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">المبلغ</label>
              <input type="number" step="0.01" min="0" name="amount" id="f_amount" class="form-control" required>
            </div>

            <div class="col-md-6">
              <label class="form-label">طريقة الدفع</label>
              <select name="payment_method" id="f_payment_method" class="form-select js-manual-picker" data-live-search="false" data-size="false" data-width="100%" data-dropup-auto="false">
                <option value="CASH">نقدي</option>
                <option value="BANK">بنكي</option>
              </select>
            </div>
            <div class="col-md-6 bank-only d-none">
              <label class="form-label">نوع التحويل البنكي</label>
              <select name="bank_txn_type" id="f_bank_txn_type" class="form-select js-manual-picker" data-live-search="false" data-size="false" data-width="100%" data-dropup-auto="false">
                <option value="INSTA">إنستا</option>
                <option value="CHEQUE">شيك</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">المرجع</label>
              <input class="form-control bg-light" id="f_reference_view" readonly>
            </div>
            <div class="col-md-6 bank-cheque-only d-none">
              <label class="form-label">تاريخ الاستحقاق</label>
              <input type="text" name="due_date" id="f_due_date" class="form-control datepick" autocomplete="off">
            </div>

            <div class="col-md-6 bank-only d-none">
              <label class="form-label">اسم البنك</label>
              <input name="bank_name" id="f_bank_name" class="form-control" placeholder="اسم البنك">
            </div>
            <div class="col-md-6 bank-only d-none">
              <label class="form-label">رقم الحساب</label>
              <input name="bank_account_no" id="f_bank_account_no" class="form-control" placeholder="رقم الحساب البنكي">
            </div>

            <div class="col-12">
              <label class="form-label">ملاحظات</label>
              <textarea name="memo" id="f_memo" class="form-control" rows="2" placeholder="أي بيان إضافي يظهر في السند والقيد"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-light" data-bs-dismiss="modal">إغلاق</button>
          <button type="submit" class="btn btn-dark" id="btnSubmitReceipt">حفظ التحصيل</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
const limoOptions = <?= json_encode(array_map(function($r){
  $due = max(0, (float)$r['total_amount'] - (float)$r['collected_amount']);
  return [
    'id' => (int)$r['id'],
    'label' => trim('سريال ' . ($r['serial_no'] ?? '-') . ' / أمر تشغيل ' . ($r['display_no'] ?? '-')),
    'reference' => trim('ليموزين - سريال ' . ($r['serial_no'] ?? '-') . ' - أمر ' . ($r['display_no'] ?? '-')),
    'amount' => $due > 0 ? $due : (float)$r['total_amount'],
  ];
}, $limoOptions), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const rentOptions = <?= json_encode(array_map(function($r){
  $due = max(0, (float)$r['total_amount'] - (float)$r['collected_amount']);
  return [
    'id' => (int)$r['id'],
    'label' => trim('سريال ' . ($r['order_serial_no'] ?? '-') . ' / أمر تأجير ' . ($r['contract_serial'] ?? '-')),
    'reference' => trim('أمر تأجير - سريال ' . ($r['order_serial_no'] ?? '-') . ' - عقد ' . ($r['contract_serial'] ?? '-')),
    'amount' => $due > 0 ? $due : (float)$r['total_amount'],
  ];
}, $rentOptions), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;

const sourceType = document.getElementById('f_source_type');
const sourceId = document.getElementById('f_source_id');
const amountInput = document.getElementById('f_amount');
const refView = document.getElementById('f_reference_view');
const sourceWrap = document.querySelector('.source-wrap');
const paymentMethod = document.getElementById('f_payment_method');
const bankTxnType = document.getElementById('f_bank_txn_type');
const dueDateInput = document.getElementById('f_due_date');
const bankOnlyEls = Array.from(document.querySelectorAll('.bank-only'));
const bankChequeOnlyEls = Array.from(document.querySelectorAll('.bank-cheque-only'));
const modalEl = document.getElementById('mReceipt');
const modal = (window.bootstrap && bootstrap.Modal && modalEl) ? bootstrap.Modal.getOrCreateInstance(modalEl) : null;
const cashAccount = document.getElementById('f_cash_account_id');
const receiptDate = document.getElementById('f_receipt_date');
const receiptForm = document.getElementById('receiptForm');
const openBtn = document.getElementById('btnOpenReceipt');

function pickerOptions(){
  return {
    styleBase: '',
    liveSearchNormalize: true,
    noneSelectedText: 'اختر...',
    noneResultsText: 'لا توجد نتائج {0}',
    selectAllText: 'تحديد الكل',
    deselectAllText: 'إلغاء التحديد',
    dropupAuto: false,
    size: 6,
    liveSearchPlaceholder: 'ابحث هنا'
  };
}


function cleanupPickerShell(el){
  if (!el || !el.parentNode) return;
  const parent = el.parentNode;
  Array.from(parent.children).forEach(function(node){
    if (node !== el && node.classList && node.classList.contains('bootstrap-select')) {
      node.remove();
    }
  });
  el.classList.remove('bs-select-hidden');
  el.style.removeProperty('display');
}

function hardInitPicker(el){
  if (!el || !window.jQuery || !jQuery.fn || !jQuery.fn.selectpicker) return;
  const $el = jQuery(el);
  try {
    if ($el.data('selectpicker')) {
      $el.selectpicker('destroy');
    }
  } catch (e) {}
  cleanupPickerShell(el);
  $el.selectpicker(pickerOptions());
}

function ensureManualPicker(el){
  if (!el || !window.jQuery || !jQuery.fn || !jQuery.fn.selectpicker) return;
  const $el = jQuery(el);
  cleanupPickerShell(el);
  if (!$el.data('selectpicker') || !el.parentNode.querySelector('.bootstrap-select')) {
    hardInitPicker(el);
  } else {
    $el.selectpicker('refresh');
  }
}

function ensureSourcePicker(){
  if (!sourceId || !window.jQuery || !jQuery.fn || !jQuery.fn.selectpicker) return;
  hardInitPicker(sourceId);
}

function refreshPicker(el){
  if (!el) return;
  if (el === sourceId) {
    ensureSourcePicker();
    return;
  }
  if (window.jQuery && jQuery.fn && jQuery.fn.selectpicker) {
    const $el = jQuery(el);
    if ($el.data('selectpicker')) {
      $el.selectpicker('refresh');
    }
  }
}

function setPickerValue(el, value){
  if (!el) return;
  el.value = value == null ? '' : String(value);
  if (window.jQuery && jQuery.fn && jQuery.fn.selectpicker) {
    const $el = jQuery(el);
    if ($el.data('selectpicker')) {
      $el.selectpicker('val', el.value);
      $el.selectpicker('refresh');
    }
  }
}

function getSourceMap(){
  if (sourceType.value === 'LIMO') return limoOptions;
  if (sourceType.value === 'RENT') return rentOptions;
  return [];
}

function currentSourceData(){
  const selectedOption = sourceId.options[sourceId.selectedIndex] || null;
  if (!selectedOption || !selectedOption.value) return null;
  return {
    id: selectedOption.value,
    reference: selectedOption.dataset.reference || '',
    amount: selectedOption.dataset.amount || ''
  };
}

function rebuildSourceOptions(selectedValue){
  const map = getSourceMap();
  const wanted = selectedValue == null ? '' : String(selectedValue);

  sourceId.options.length = 0;
  sourceId.add(new Option('اختر', ''));

  map.forEach(function(item){
    const opt = new Option(item.label || '', String(item.id));
    opt.dataset.reference = item.reference || '';
    opt.dataset.amount = item.amount != null ? String(item.amount) : '';
    sourceId.add(opt);
  });

  const exists = wanted && map.some(item => String(item.id) === wanted);
  sourceId.value = exists ? wanted : '';
  refreshPicker(sourceId);
}

function syncSourceState(preserveAmount){
  const isAdvance = sourceType.value === 'ADVANCE';
  sourceWrap.style.display = isAdvance ? 'none' : '';

  if (isAdvance) {
    sourceId.value = '';
    refreshPicker(sourceId);
    refView.value = 'مقدم تحت الحساب';
    if (!preserveAmount) amountInput.value = '';
    return;
  }

  rebuildSourceOptions(sourceId.value || '');
  const data = currentSourceData();
  if (data) {
    refView.value = data.reference || '';
    if (!preserveAmount) amountInput.value = data.amount || '';
  } else {
    refView.value = '';
    if (!preserveAmount) amountInput.value = '';
  }
}

function syncPaymentMethod(){
  const isBank = paymentMethod.value === 'BANK';
  const isCheque = isBank && bankTxnType.value === 'CHEQUE';
  bankOnlyEls.forEach(el => el.classList.toggle('d-none', !isBank));
  bankChequeOnlyEls.forEach(el => el.classList.toggle('d-none', !isCheque));
  if (isBank) {
    if (!bankTxnType.value) setPickerValue(bankTxnType, 'INSTA');
    if (isCheque && !dueDateInput.value) dueDateInput.value = receiptDate.value || '<?= date('Y-m-d') ?>';
    if (!isCheque) dueDateInput.value = '';
  } else {
    setPickerValue(bankTxnType, 'INSTA');
    document.getElementById('f_bank_name').value = '';
    document.getElementById('f_bank_account_no').value = '';
    dueDateInput.value = '';
  }
}

function resetReceiptForm(){
  receiptForm.reset();
  document.getElementById('f_action').value = 'create';
  document.getElementById('f_id').value = '';
  document.getElementById('f_receipt_no').value = '<?= h(fleet_receipt_next_code($pdo, $cid)) ?>';
  receiptDate.value = '<?= date('Y-m-d') ?>';
  setPickerValue(sourceType, 'LIMO');
  setPickerValue(cashAccount, '<?= (int)$acc['cash_id'] ?>');
  setPickerValue(paymentMethod, 'CASH');
  setPickerValue(bankTxnType, 'INSTA');
  rebuildSourceOptions('');
  amountInput.value = '';
  refView.value = '';
  document.getElementById('f_memo').value = '';
  syncSourceState(false);
  syncPaymentMethod();
}

function onSourceTypeChanged(){
  syncSourceState(false);
}

function onSourceIdChanged(){
  const data = currentSourceData();
  if (data) {
    amountInput.value = data.amount || '';
    refView.value = data.reference || '';
  } else if (sourceType.value === 'ADVANCE') {
    refView.value = 'مقدم تحت الحساب';
  } else {
    amountInput.value = '';
    refView.value = '';
  }
}

if (window.jQuery && jQuery.fn && jQuery.fn.selectpicker) {
  ensureManualPicker(sourceType);
  ensureManualPicker(cashAccount);
  ensureManualPicker(paymentMethod);
  ensureManualPicker(bankTxnType);
  ensureSourcePicker();
  jQuery(sourceType).on('changed.bs.select', onSourceTypeChanged);
  jQuery(sourceId).on('changed.bs.select', onSourceIdChanged);
  jQuery(paymentMethod).on('changed.bs.select', syncPaymentMethod);
  jQuery(bankTxnType).on('changed.bs.select', syncPaymentMethod);
} else {
  sourceType.addEventListener('change', onSourceTypeChanged);
  sourceId.addEventListener('change', onSourceIdChanged);
  paymentMethod.addEventListener('change', syncPaymentMethod);
  bankTxnType.addEventListener('change', syncPaymentMethod);
}

receiptDate.addEventListener('change', function(){
  if (paymentMethod.value === 'BANK' && bankTxnType.value === 'CHEQUE' && !dueDateInput.value) dueDateInput.value = this.value;
});

Array.from(document.querySelectorAll('.btnEdit')).forEach(function(btn){
  btn.addEventListener('click', function(){
    document.getElementById('f_action').value = 'update';
    document.getElementById('f_id').value = this.dataset.id;
    document.getElementById('f_receipt_no').value = this.dataset.receiptno || '';
    setPickerValue(sourceType, this.dataset.sourcetype || 'ADVANCE');
    rebuildSourceOptions(this.dataset.sourceid || '');
    setPickerValue(sourceId, this.dataset.sourceid || '');
    receiptDate.value = this.dataset.date || '<?= date('Y-m-d') ?>';
    setPickerValue(cashAccount, this.dataset.cash || '<?= (int)$acc['cash_id'] ?>');
    amountInput.value = this.dataset.amount || '';
    setPickerValue(paymentMethod, this.dataset.method || 'CASH');
    setPickerValue(bankTxnType, this.dataset.banktxntype || 'INSTA');
    document.getElementById('f_bank_name').value = this.dataset.bankname || '';
    document.getElementById('f_bank_account_no').value = this.dataset.bankaccount || '';
    dueDateInput.value = this.dataset.duedate || '';
    document.getElementById('f_memo').value = this.dataset.memo || '';
    syncSourceState(true);
    onSourceIdChanged();
    syncPaymentMethod();
    if (modal) modal.show();
  });
});

if (modalEl) {
  modalEl.addEventListener('shown.bs.modal', function(){
    ensureManualPicker(sourceType);
    ensureManualPicker(cashAccount);
    ensureManualPicker(paymentMethod);
    ensureSourcePicker();
  });
  modalEl.addEventListener('hidden.bs.modal', function(){
    resetReceiptForm();
  });
}

if (openBtn) {
  openBtn.addEventListener('click', function(){
    resetReceiptForm();
  });
}

if (receiptForm) {
  receiptForm.addEventListener('submit', function(){
    const submitBtn = document.getElementById('btnSubmitReceipt');
    if (submitBtn) {
      submitBtn.disabled = true;
      submitBtn.innerText = 'جاري الحفظ...';
    }
  });
}

setTimeout(function(){ resetReceiptForm(); }, 0);
});
</script>
<?php }); ?>
