<?php
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.php';
require_once __DIR__ . '/../app/Services/AccountingService.php';
require_once __DIR__ . '/../app/cash_tx_lock.php';
require_login();

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

$date_from = $_GET['from'] ?? date('Y-m-01');
$date_to   = $_GET['to'] ?? date('Y-m-t');

$cashAccStmt = $pdo->prepare("SELECT id, code, name FROM accounts WHERE company_id=? AND is_cash=1 AND is_active=1 ORDER BY code");
$cashAccStmt->execute([$cid]);
$cashAcc = $cashAccStmt->fetchAll(PDO::FETCH_ASSOC);

$counterAccStmt = $pdo->prepare("SELECT id, code, name, type FROM accounts WHERE company_id=? AND is_active=1 ORDER BY code");
$counterAccStmt->execute([$cid]);
$counterAcc = $counterAccStmt->fetchAll(PDO::FETCH_ASSOC);

$editId = (int)($_GET['edit'] ?? 0);
$editTx = null;
if ($editId > 0) {
  $editMap = $pdo->prepare("SELECT entry_id FROM cash_tx_journal_map WHERE cash_tx_id=? LIMIT 1");
  $editMap->execute([$editId]);
  if (!$editMap->fetchColumn() && !cash_tx_is_locked_from_cash_page($pdo, $cid, $editId)) {
    $editStmt = $pdo->prepare("SELECT * FROM cash_transactions WHERE id=? AND company_id=? LIMIT 1");
    $editStmt->execute([$editId, $cid]);
    $editTx = $editStmt->fetch(PDO::FETCH_ASSOC) ?: null;
  }
}

$err = '';
$openModal = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();

  $formMode = $_POST['form_mode'] ?? 'create';
  $txId = (int)($_POST['id'] ?? 0);
  $tx_date = $_POST['tx_date'] ?? date('Y-m-d');
  $tx_type = $_POST['tx_type'] ?? 'IN';
  $cash_account_id = (int)($_POST['cash_account_id'] ?? 0);
  $counter_account_id = (int)($_POST['counter_account_id'] ?? 0);
  $amount = (float)($_POST['amount'] ?? 0);
  $memo = trim($_POST['memo'] ?? '');

  if ($tx_date > date('Y-m-d')) {
    $err = 'لا يجوز إنشاء أو تعديل حركة مالية بتاريخ أحدث من التاريخ الحالي';
  }
  if (!$err && !in_array($tx_type, ['IN', 'OUT'], true)) {
    $err = 'نوع الحركة غير صالح';
  }
  if (!$err && (!$cash_account_id || !$counter_account_id || $amount <= 0)) {
    $err = 'تحقق من البيانات';
  }
  if (!$err && $cash_account_id === $counter_account_id) {
    $err = 'لا يجوز اختيار نفس الحساب للنقدية والحساب المقابل';
  }

  if ($formMode === 'edit') {
    $openModal = 'edit';

    $txStmt = $pdo->prepare("SELECT * FROM cash_transactions WHERE id=? AND company_id=? LIMIT 1");
    $txStmt->execute([$txId, $cid]);
    $editTx = $txStmt->fetch(PDO::FETCH_ASSOC) ?: null;

    if (!$editTx) {
      $err = 'الحركة المالية غير موجودة';
    }

    if (!$err) {
      if (cash_tx_is_locked_from_cash_page($pdo, $cid, $txId)) {
        $label = cash_tx_linked_source_label($pdo, $cid, $txId) ?: 'صفحة أخرى';
        $err = 'لا يمكن تعديل هذه الحركة من صفحة الوارد والمنصرف لأنها مرتبطة بـ ' . $label;
      } else {
        $mapStmt = $pdo->prepare("SELECT entry_id FROM cash_tx_journal_map WHERE cash_tx_id=? LIMIT 1");
        $mapStmt->execute([$txId]);
        if ($mapStmt->fetchColumn()) {
          $err = 'لا يمكن تعديل حركة مرحّلة. قم بإلغاء الترحيل أولاً.';
        }
      }
    }

    $attachment = $editTx['attachment'] ?? null;
    if (!$err && !empty($_FILES['attachment']) && $_FILES['attachment']['error'] !== UPLOAD_ERR_NO_FILE) {
      if ($_FILES['attachment']['error'] !== UPLOAD_ERR_OK) {
        $err = 'تعذر رفع المرفق';
      } else {
        $maxBytes = 10 * 1024 * 1024;
        if ($_FILES['attachment']['size'] > $maxBytes) {
          $err = 'حجم المرفق كبير (الحد 10MB)';
        } else {
          $orig = $_FILES['attachment']['name'] ?? 'file';
          $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
          $allowed = ['jpg','jpeg','png','webp','pdf'];
          if (!in_array($ext, $allowed, true)) {
            $err = 'نوع المرفق غير مدعوم (PDF/صور فقط)';
          } else {
            $subdir = 'uploads/cash/' . date('Y') . '/' . date('m');
            $absDir = dirname(__DIR__) . '/' . $subdir;
            if (!is_dir($absDir)) { @mkdir($absDir, 0775, true); }
            $fname = 'tx_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            $absPath = $absDir . '/' . $fname;
            if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $absPath)) {
              $err = 'تعذر حفظ المرفق على السيرفر';
            } else {
              $attachment = $subdir . '/' . $fname;
            }
          }
        }
      }
    }

    if (!$err && $editTx) {
      try {
        $st = $pdo->prepare("UPDATE cash_transactions
          SET tx_date=?, tx_type=?, cash_account_id=?, counter_account_id=?, amount=?, memo=?, attachment=?
          WHERE id=? AND company_id=?");
        $st->execute([$tx_date, $tx_type, $cash_account_id, $counter_account_id, $amount, $memo ?: null, $attachment, $txId, $cid]);
        audit_log($pdo, [
          'company_id' => $cid,
          'user_id' => $uid,
          'module' => 'cash',
          'action' => 'UPDATE',
          'entity_type' => 'cash_transaction',
          'entity_id' => (string)$txId,
          'description' => audit_cash_description($pdo, $cid, 'تعديل حركة مالية', [
            'tx_type' => $tx_type,
            'amount' => $amount,
            'cash_account_id' => $cash_account_id,
            'counter_account_id' => $counter_account_id,
            'memo' => $memo,
            'tx_date' => $tx_date,
          ]),
        ]);
        flash_set('تم تعديل الحركة المالية بنجاح');
        header('Location: ' . url('/cash/index.php?from=' . urlencode($date_from) . '&to=' . urlencode($date_to)));
        exit;
      } catch (Throwable $e) {
        $err = 'خطأ: ' . $e->getMessage();
      }
    }

    if ($editTx) {
      $editTx['tx_date'] = $tx_date;
      $editTx['tx_type'] = $tx_type;
      $editTx['cash_account_id'] = $cash_account_id;
      $editTx['counter_account_id'] = $counter_account_id;
      $editTx['amount'] = $amount;
      $editTx['memo'] = $memo;
    }
  } else {
    $openModal = 'create';
    $attachment = null;
    if (!empty($_FILES['attachment']) && $_FILES['attachment']['error'] !== UPLOAD_ERR_NO_FILE) {
      if ($_FILES['attachment']['error'] !== UPLOAD_ERR_OK) {
        $err = 'تعذر رفع المرفق';
      } else {
        $maxBytes = 10 * 1024 * 1024;
        if ($_FILES['attachment']['size'] > $maxBytes) {
          $err = 'حجم المرفق كبير (الحد 10MB)';
        } else {
          $orig = $_FILES['attachment']['name'] ?? 'file';
          $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
          $allowed = ['jpg','jpeg','png','webp','pdf'];
          if (!in_array($ext, $allowed, true)) {
            $err = 'نوع المرفق غير مدعوم (PDF/صور فقط)';
          } else {
            $subdir = 'uploads/cash/' . date('Y') . '/' . date('m');
            $absDir = dirname(__DIR__) . '/' . $subdir;
            if (!is_dir($absDir)) { @mkdir($absDir, 0775, true); }
            $fname = 'tx_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            $absPath = $absDir . '/' . $fname;
            if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $absPath)) {
              $err = 'تعذر حفظ المرفق على السيرفر';
            } else {
              $attachment = $subdir . '/' . $fname;
            }
          }
        }
      }
    }

    if (!$err) {
      try {
        $svc = new AccountingService($pdo);
        $newTxId = (int)$svc->createCashTxDraft([
          'company_id' => $cid,
          'tx_date' => $tx_date,
          'tx_type' => $tx_type,
          'cash_account_id' => $cash_account_id,
          'counter_account_id' => $counter_account_id,
          'amount' => $amount,
          'memo' => $memo,
          'attachment' => $attachment,
          'created_by' => $uid,
        ]);
        audit_log($pdo, [
          'company_id' => $cid,
          'user_id' => $uid,
          'module' => 'cash',
          'action' => 'CREATE',
          'entity_type' => 'cash_transaction',
          'entity_id' => (string)$newTxId,
          'description' => audit_cash_description($pdo, $cid, 'إنشاء حركة مالية', [
            'tx_type' => $tx_type,
            'amount' => $amount,
            'cash_account_id' => $cash_account_id,
            'counter_account_id' => $counter_account_id,
            'memo' => $memo,
            'tx_date' => $tx_date,
          ]),
        ]);
        flash_set('تم إضافة الحركة المالية وترحيلها بنجاح');
        header('Location: ' . url('/cash/index.php?from=' . urlencode($date_from) . '&to=' . urlencode($date_to)));
        exit;
      } catch (Throwable $e) {
        $err = 'خطأ: ' . $e->getMessage();
      }
    }
  }
}

$stmt = $pdo->prepare("
  SELECT ct.*, a1.code AS cash_code, a1.name AS cash_name, a2.code AS cnt_code, a2.name AS cnt_name, m.entry_id,
         ea.id AS employee_advance_id,
         eas.id AS employee_settlement_id
  FROM cash_transactions ct
  JOIN accounts a1 ON a1.id=ct.cash_account_id
  JOIN accounts a2 ON a2.id=ct.counter_account_id
  LEFT JOIN cash_tx_journal_map m ON m.cash_tx_id=ct.id
  LEFT JOIN employee_advances ea ON ea.company_id=ct.company_id AND ea.cash_tx_id=ct.id
  LEFT JOIN employee_advance_settlements eas ON eas.company_id=ct.company_id AND eas.cash_tx_id=ct.id
  WHERE ct.company_id=? AND ct.tx_date BETWEEN ? AND ?
  ORDER BY ct.id DESC
");
$stmt->execute([$cid, $date_from, $date_to]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

render_layout('الوارد والمنصرف', "الرئيسية <span class='mx-1'>/</span> الحسابات <span class='mx-1'>/</span> الوارد والمنصرف", function() use ($rows, $date_from, $date_to, $cashAcc, $counterAcc, $err, $openModal, $editTx) {
?>
<div class="card cardx mt-3">
  <div class="p-3 d-flex align-items-center justify-content-between flex-wrap gap-2">
    <div>
      <div class="fw-bold">الوارد والمنصرف</div>
      <div class="text-secondary small">الإضافة والتعديل من خلال Modal داخل الصفحة نفسها.</div>
    </div>
    <button class="btn btn-dark btn-sm" data-bs-toggle="modal" data-bs-target="#cashCreateModal"><i class="bi bi-plus-lg"></i> إضافة حركة</button>
  </div>

  <?php if($err): ?>
    <div class="px-3 pb-0"><div class="alert alert-danger mb-0"><?= h($err) ?></div></div>
  <?php endif; ?>

  <div class="px-3 pb-3 pt-3">
    <form class="row g-2 align-items-end mb-2" method="get">
      <div class="col-12 col-md-4">
        <label class="form-label small text-secondary">من</label>
        <?= render_date_input('from', $date_from) ?>
      </div>
      <div class="col-12 col-md-4">
        <label class="form-label small text-secondary">إلى</label>
        <?= render_date_input('to', $date_to) ?>
      </div>
      <div class="col-12 col-md-4 d-flex gap-2">
        <button class="btn btn-outline-secondary w-100"><i class="bi bi-funnel"></i> فلترة</button>
        <a class="btn btn-outline-dark w-100" href="<?= url('/cash/index.php') ?>"><i class="bi bi-arrow-counterclockwise"></i> إعادة</a>
      </div>
    </form>

    <div class="table-responsive">
      <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 class="text-end">المبلغ</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 else: foreach($rows as $r): ?>
            <?php
              $linkedSourceLabel = null;
              if (!empty($r['employee_advance_id'])) {
                $linkedSourceLabel = 'عهدة موظف';
              } elseif (!empty($r['employee_settlement_id'])) {
                $linkedSourceLabel = 'تسوية عهدة';
              }
              $canManageFromCash = empty($linkedSourceLabel) && empty($r['entry_id']);
            ?>
            <tr>
              <td class="text-secondary"><?= (int)$r['id'] ?></td>
              <td class="text-secondary"><?= h($r['tx_date']) ?></td>
              <td>
                <?php if($r['tx_type'] === 'IN'): ?>
                  <span class="badge bg-success-subtle text-success border border-success-subtle">وارد</span>
                <?php else: ?>
                  <span class="badge bg-danger-subtle text-danger border border-danger-subtle">منصرف</span>
                <?php endif; ?>
              </td>
              <td class="small"><?= h($r['cash_code'] . ' - ' . $r['cash_name']) ?></td>
              <td class="small"><?= h($r['cnt_code'] . ' - ' . $r['cnt_name']) ?></td>
              <td>
                <?php if(!empty($r['attachment'])): ?>
                  <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#attachmentModal" data-att-url="<?= url('/' . ltrim($r['attachment'], '/')) ?>" title="معاينة المرفق"><i class="bi bi-paperclip"></i></button>
                <?php else: ?>
                  <span class="text-secondary small">—</span>
                <?php endif; ?>
              </td>
              <td>
                <?php if($linkedSourceLabel): ?>
                  <div class="d-flex flex-column gap-1 align-items-start">
                    <span class="badge bg-info-subtle text-info border border-info-subtle">مربوطة بـ <?= h($linkedSourceLabel) ?></span>
                    <?php if(!empty($r['entry_id'])): ?>
                      <span class="badge bg-success-subtle text-success border border-success-subtle">مرحل</span>
                    <?php else: ?>
                      <span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle">من صفحة أخرى</span>
                    <?php endif; ?>
                  </div>
                <?php elseif(!empty($r['entry_id'])): ?>
                  <span class="badge bg-success-subtle text-success border border-success-subtle">مرحل</span>
                <?php else: ?>
                  <span class="badge bg-warning-subtle text-warning border border-warning-subtle">غير مرحل</span>
                <?php endif; ?>
              </td>
              <td class="text-end fw-semibold"><?= number_format((float)$r['amount'], 2) ?></td>
              <td class="text-end">
                <?php if($canManageFromCash): ?>
                  <a class="btn btn-sm btn-outline-secondary" href="<?= url('/cash/index.php?edit=' . (int)$r['id'] . '&from=' . urlencode($date_from) . '&to=' . urlencode($date_to)) ?>" title="تعديل"><i class="bi bi-pencil"></i></a>
                  <a class="btn btn-sm btn-outline-danger" href="delete.php?id=<?= (int)$r['id'] ?>" onclick="return confirm('تأكيد حذف الحركة؟');" title="حذف"><i class="bi bi-trash"></i></a>
                <?php elseif($linkedSourceLabel): ?>
                  <span class="text-secondary small">يُدار من <?= h($linkedSourceLabel) ?></span>
                <?php else: ?>
                  <a class="btn btn-sm btn-outline-danger" href="<?= url('/journal/unpost_cash.php?id=' . (int)$r['id']) ?>" onclick="return confirm('تأكيد إلغاء الترحيل؟ سيتم حذف القيد المرتبط لإجراء تصحيح.');" title="إلغاء الترحيل"><i class="bi bi-x-circle"></i></a>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<style>
.cash-compact-modal .modal-dialog{max-width:760px;}
.cash-compact-modal .modal-body{padding-top:.75rem;padding-bottom:.75rem;overflow-x:hidden;}
.cash-field-row{display:flex;align-items:center;gap:.65rem;min-width:0;}
.cash-field-row .cash-label{flex:0 0 auto;min-width:max-content;max-width:120px;margin:0;font-size:.92rem;color:#495057;font-weight:600;white-space:nowrap;}
.cash-field-row .cash-control{flex:1 1 auto;min-width:0;max-width:100%;}
.cash-compact-modal .bootstrap-select,
.cash-compact-modal .bootstrap-select>.dropdown-toggle,
.cash-compact-modal .form-control,
.cash-compact-modal .form-select{width:100%!important;max-width:100%;}
.cash-compact-modal .picker-with-action{display:flex;align-items:center;gap:.5rem;min-width:0;max-width:100%;}
.cash-compact-modal .picker-with-action .bootstrap-select{flex:1 1 auto!important;min-width:0;}
.cash-compact-modal .picker-action-btn{flex:0 0 auto;}
.cash-compact-note{font-size:.78rem;color:#6c757d;padding-inline-start:100px;margin-top:.2rem;}
.cash-compact-modal .bootstrap-select .dropdown-toggle{overflow:hidden;}
.cash-compact-modal .bootstrap-select .filter-option,
.cash-compact-modal .bootstrap-select .filter-option-inner,
.cash-compact-modal .bootstrap-select .filter-option-inner-inner{max-width:100%;}
.cash-compact-modal .bootstrap-select .filter-option-inner-inner{white-space:nowrap;overflow-x:auto;overflow-y:hidden;text-overflow:clip;scrollbar-width:thin;}
.cash-compact-modal .bootstrap-select .dropdown-menu{max-width:100%;min-width:100%!important;overflow:hidden;}
.cash-compact-modal .bootstrap-select .dropdown-menu .inner{max-width:100%;overflow-x:auto;overflow-y:auto;}
.cash-compact-modal .bootstrap-select .dropdown-menu .dropdown-item{display:block;width:max-content;min-width:100%;white-space:nowrap;}
.cash-compact-modal .form-control,.cash-compact-modal .form-select{min-width:0;}
@media (max-width: 767.98px){
  .cash-compact-modal .modal-dialog{max-width:calc(100vw - 1rem);margin:.5rem auto;}
  .cash-field-row{display:block;}
  .cash-field-row .cash-label{display:block;min-width:0;max-width:none;margin-bottom:.35rem;}
  .cash-compact-note{padding-inline-start:0;}
}
</style>

<div class="modal fade modal-erp cash-compact-modal" id="cashCreateModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <input type="hidden" name="form_mode" value="create">
        <input type="hidden" name="from" value="<?= h($date_from) ?>">
        <input type="hidden" name="to" value="<?= h($date_to) ?>">
        <div class="modal-header">
          <h5 class="modal-title">إضافة حركة مالية</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="row g-2">
            <div class="col-12 col-md-6">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_create_date">التاريخ</label>
                <div class="cash-control"><?= render_date_input('tx_date', $_POST['tx_date'] ?? date('Y-m-d')) ?></div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_create_type">النوع</label>
                <div class="cash-control">
                  <select id="cash_create_type" class="form-select selectpicker" data-width="100%" name="tx_type">
                    <option value="IN" <?= (($_POST['tx_type'] ?? 'IN') === 'IN') ? 'selected' : '' ?>>وارد</option>
                    <option value="OUT" <?= (($_POST['tx_type'] ?? '') === 'OUT') ? 'selected' : '' ?>>منصرف</option>
                  </select>
                </div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_create_amount">المبلغ</label>
                <div class="cash-control"><input id="cash_create_amount" class="form-control" type="number" step="0.01" name="amount" required value="<?= h($_POST['amount'] ?? '') ?>"></div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_account_id">النقدية</label>
                <div class="cash-control"><div class="picker-with-action"><select id="cash_account_id" class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" required name="cash_account_id" title="— اختر —">
                  <?php foreach($cashAcc as $a): ?>
                    <option value="<?= (int)$a['id'] ?>" <?= ((int)$a['id'] === (int)($_POST['cash_account_id'] ?? 0)) ? 'selected' : '' ?>><?= h($a['code'] . ' - ' . $a['name']) ?></option>
                  <?php endforeach; ?>
                </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="account" data-target="#cash_account_id" title="إضافة حساب جديد"><i class="bi bi-plus-lg"></i></button></div></div>
              </div>
              <div class="cash-compact-note">صندوق أو بنك</div>
            </div>
            <div class="col-12">
              <div class="cash-field-row">
                <label class="cash-label" for="counter_account_id">المقابل</label>
                <div class="cash-control"><div class="picker-with-action"><select id="counter_account_id" class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" required name="counter_account_id" title="— اختر —">
                  <?php foreach($counterAcc as $a): ?>
                    <option value="<?= (int)$a['id'] ?>" <?= ((int)$a['id'] === (int)($_POST['counter_account_id'] ?? 0)) ? 'selected' : '' ?>><?= h($a['code'] . ' - ' . $a['name'] . ' (' . $a['type'] . ')') ?></option>
                  <?php endforeach; ?>
                </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="account" data-target="#counter_account_id" title="إضافة حساب جديد"><i class="bi bi-plus-lg"></i></button></div></div>
              </div>
              <div class="cash-compact-note">الحساب الطرف الآخر</div>
            </div>
            <div class="col-12">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_create_memo">البيان</label>
                <div class="cash-control"><input id="cash_create_memo" class="form-control" name="memo" placeholder="بيان مختصر للحركة" value="<?= h($_POST['memo'] ?? '') ?>"></div>
              </div>
            </div>
            <div class="col-12">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_create_attachment">المرفق</label>
                <div class="cash-control"><input id="cash_create_attachment" class="form-control" type="file" name="attachment" accept=".pdf,image/*"></div>
              </div>
              <div class="cash-compact-note">PDF أو صورة - حتى 10MB</div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ وترحيل</button>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php if($editTx): ?>
<div class="modal fade modal-erp cash-compact-modal" id="cashEditModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <input type="hidden" name="form_mode" value="edit">
        <input type="hidden" name="id" value="<?= (int)$editTx['id'] ?>">
        <input type="hidden" name="from" value="<?= h($date_from) ?>">
        <input type="hidden" name="to" value="<?= h($date_to) ?>">
        <div class="modal-header">
          <h5 class="modal-title">تعديل حركة مالية #<?= (int)$editTx['id'] ?></h5>
          <a class="btn btn-sm btn-outline-secondary ms-2" href="<?= url('/cash/index.php?from=' . urlencode($date_from) . '&to=' . urlencode($date_to)) ?>">إغلاق</a>
        </div>
        <div class="modal-body">
          <div class="row g-2">
            <div class="col-12 col-md-6">
              <div class="cash-field-row">
                <label class="cash-label">التاريخ</label>
                <div class="cash-control"><?= render_date_input('tx_date', $editTx['tx_date'] ?? date('Y-m-d')) ?></div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_edit_type">النوع</label>
                <div class="cash-control">
                  <select id="cash_edit_type" class="form-select selectpicker" data-width="100%" name="tx_type">
                    <option value="IN" <?= (($editTx['tx_type'] ?? '') === 'IN') ? 'selected' : '' ?>>وارد</option>
                    <option value="OUT" <?= (($editTx['tx_type'] ?? '') === 'OUT') ? 'selected' : '' ?>>منصرف</option>
                  </select>
                </div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_edit_amount">المبلغ</label>
                <div class="cash-control"><input id="cash_edit_amount" class="form-control" type="number" step="0.01" name="amount" required value="<?= h($editTx['amount'] ?? '') ?>"></div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="cash-field-row">
                <label class="cash-label" for="edit_cash_account_id">النقدية</label>
                <div class="cash-control"><div class="picker-with-action"><select id="edit_cash_account_id" class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" required name="cash_account_id" title="— اختر —">
                  <?php foreach($cashAcc as $a): ?>
                    <option value="<?= (int)$a['id'] ?>" <?= ((int)$a['id'] === (int)($editTx['cash_account_id'] ?? 0)) ? 'selected' : '' ?>><?= h($a['code'] . ' - ' . $a['name']) ?></option>
                  <?php endforeach; ?>
                </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="account" data-target="#edit_cash_account_id" title="إضافة حساب جديد"><i class="bi bi-plus-lg"></i></button></div></div>
              </div>
            </div>
            <div class="col-12">
              <div class="cash-field-row">
                <label class="cash-label" for="edit_counter_account_id">المقابل</label>
                <div class="cash-control"><div class="picker-with-action"><select id="edit_counter_account_id" class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" required name="counter_account_id" title="— اختر —">
                  <?php foreach($counterAcc as $a): ?>
                    <option value="<?= (int)$a['id'] ?>" <?= ((int)$a['id'] === (int)($editTx['counter_account_id'] ?? 0)) ? 'selected' : '' ?>><?= h($a['code'] . ' - ' . $a['name'] . ' (' . $a['type'] . ')') ?></option>
                  <?php endforeach; ?>
                </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="account" data-target="#edit_counter_account_id" title="إضافة حساب جديد"><i class="bi bi-plus-lg"></i></button></div></div>
              </div>
            </div>
            <div class="col-12">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_edit_memo">البيان</label>
                <div class="cash-control"><input id="cash_edit_memo" class="form-control" name="memo" placeholder="بيان مختصر للحركة" value="<?= h($editTx['memo'] ?? '') ?>"></div>
              </div>
            </div>
            <div class="col-12">
              <div class="cash-field-row">
                <label class="cash-label" for="cash_edit_attachment">المرفق</label>
                <div class="cash-control"><input id="cash_edit_attachment" class="form-control" type="file" name="attachment" accept=".pdf,image/*"></div>
              </div>
              <?php if(!empty($editTx['attachment'])): ?>
                <div class="cash-compact-note d-flex align-items-center gap-2 flex-wrap">
                  <span>يوجد مرفق حالي</span>
                  <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#attachmentModal" data-att-url="<?= url('/' . ltrim($editTx['attachment'], '/')) ?>"><i class="bi bi-eye"></i> معاينة</button>
                </div>
              <?php else: ?>
                <div class="cash-compact-note">PDF أو صورة - حتى 10MB</div>
              <?php endif; ?>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-save"></i> حفظ التعديل</button>
          <a class="btn btn-outline-secondary" href="<?= url('/cash/index.php?from=' . urlencode($date_from) . '&to=' . urlencode($date_to)) ?>">إلغاء</a>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif; ?>

<div class="modal fade modal-erp" id="attachmentModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">معاينة المرفق</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="attPreviewWrap" class="ratio ratio-16x9">
          <iframe id="attFrame" src="" style="width:100%;height:100%;" loading="lazy"></iframe>
        </div>
        <img id="attImg" src="" class="img-fluid d-none" alt="Attachment" style="max-height:58vh;cursor:zoom-in">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary d-none" id="attZoomBtn"><i class="bi bi-arrows-fullscreen"></i> معاينة</button>
        <a class="btn btn-dark" id="attDownload" href="#" target="_blank"><i class="bi bi-download"></i> تحميل</a>
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('click', function(e){
  const btn = e.target.closest('[data-att-url]');
  if(!btn) return;
  const url = btn.getAttribute('data-att-url');
  const ext = (url.split('.').pop() || '').toLowerCase();
  const frame = document.getElementById('attFrame');
  const img = document.getElementById('attImg');
  const wrap = document.getElementById('attPreviewWrap');
  const dl = document.getElementById('attDownload');
  const zoomBtn = document.getElementById('attZoomBtn');
  dl.href = url;
  frame.src = '';
  img.src = '';
  img.classList.add('d-none');
  wrap.classList.remove('d-none');
  zoomBtn.classList.add('d-none');
  zoomBtn.onclick = null;
  if(['jpg','jpeg','png','webp','gif','svg'].includes(ext)){
    wrap.classList.add('d-none');
    img.classList.remove('d-none');
    img.src = url;
    zoomBtn.classList.remove('d-none');
    zoomBtn.onclick = function(){ if(window.openErpImageViewer) window.openErpImageViewer(url, 'معاينة المرفق'); };
  } else {
    frame.src = url;
  }
});
document.getElementById('attImg')?.addEventListener('click', function(){
  if(this.src && window.openErpImageViewer) window.openErpImageViewer(this.src, 'معاينة المرفق');
});
</script>

<script>
window.quickSources = window.quickSources || {};
window.quickSources.accounts_optional = [{value:'', text:'— بدون —'}, <?php foreach($counterAcc as $a): ?>{value:'<?= (int)$a['id'] ?>', text:'<?= h($a['code'] . ' - ' . $a['name']) ?>'},<?php endforeach; ?>];
window.quickSources.revenue_accounts = [<?php foreach($counterAcc as $a): if($a['type'] !== 'REVENUE') continue; ?>{value:'<?= (int)$a['id'] ?>', text:'<?= h($a['code'] . ' - ' . $a['name']) ?>'},<?php endforeach; ?>];
</script>

<?php if($openModal === 'create'): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('cashCreateModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>

<?php if($editTx): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('cashEditModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>
<?php }); ?>
