<?php
$parties = $parties ?? [];
$q = $q ?? '';
$type = $type ?? 'all';
$edit_party = $edit_party ?? null;
$page = $page ?? 1;
$total_rows = $total_rows ?? count($parties);
$total_pages = $total_pages ?? 1;
$canEdit = can_manage_parties();
$filters = [
  'all' => 'الكل',
  'customer' => 'عملاء',
  'supplier' => 'موردون',
  'both' => 'عميل + مورد',
];
$baseParams = [];
if ($q !== '') $baseParams['q'] = $q;
$modalTitle = $edit_party ? 'تعديل طرف' : 'إضافة طرف جديد';
$base_index_url = url($base_index_url ?? '/parties');
$party_view_base_url = url($party_view_base_url ?? '/parties/view?id=');
$party_edit_base_url = $party_edit_base_url ?? ($base_index_url . '?edit=');
?>
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
  <div>
    <h3 class="mb-1"><?= e($type === 'customer' ? 'العملاء' : ($type === 'supplier' ? 'الموردون' : 'الأطراف')) ?></h3>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e($base_index_url) ?>">تحديث</a>
    <?php if ($canEdit): ?>
      <button type="button" class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#partyModal" id="openPartyModalBtn">إضافة طرف جديد</button>
    <?php endif; ?>
  </div>
</div>

<div class="card shadow-sm border-0 parties-list-card">
  <div class="card-header bg-white border-0 pb-0">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
      <strong class="fs-5">قائمة الأطراف</strong>
      <span class="badge rounded-pill text-bg-light"><?= (int)$total_rows ?> سجل</span>
    </div>
    <form class="row g-2 align-items-end parties-search-form" method="get">
      <?php if ($type === 'all'): ?>
      <div class="col-12 col-lg-3">
        <label class="form-label">التصنيف</label>
        <select class="form-select" name="type">
          <?php foreach ($filters as $key => $label): ?>
            <option value="<?= e($key) ?>" <?= $type === $key ? 'selected' : '' ?>><?= e($label) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-12 col-lg-7">
      <?php else: ?>
      <div class="col-12 col-lg-10">
      <?php endif; ?>
        <label class="form-label">بحث</label>
        <input class="form-control" name="q" placeholder="ابحث بالاسم أو الهاتف أو الكود" value="<?= e($q) ?>">
      </div>
      <div class="col-12 col-lg-2 d-flex gap-2">
        <button class="btn btn-primary flex-fill">بحث</button>
        <a class="btn btn-outline-secondary" href="<?= e($base_index_url) ?>">إلغاء</a>
      </div>
    </form>
  </div>
  <div class="card-body pt-3">
    <div class="table-responsive">
      <table class="table table-hover align-middle table-sm mb-0 table-clean">
        <thead class="table-light">
          <tr>
            <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 foreach ($parties as $p): ?>
            <tr>
              <td><?= (int)$p['id'] ?></td>
              <td><?= e((string)($p['code'] ?? '-')) ?></td>
              <td><a class="text-decoration-none fw-semibold" href="<?= e(str_replace('id=0', 'id=' . (int)$p['id'], $party_view_base_url)) ?>"><?= e((string)$p['name']) ?></a></td>
              <td>
                <?php if ((int)($p['is_customer'] ?? 0) === 1): ?><span class="badge text-bg-secondary">عميل</span><?php endif; ?>
                <?php if ((int)($p['is_supplier'] ?? 0) === 1): ?><span class="badge text-bg-primary">مورد</span><?php endif; ?>
              </td>
              <td><?= e((string)($p['phone'] ?? '-')) ?></td>
              <td class="text-end"><?= format_money($p['opening_balance'] ?? 0) ?></td>
              <td class="text-end"><?= format_money($p['credit_limit'] ?? 0) ?></td>
              <td><?php if ((int)$p['is_active'] === 1): ?><span class="badge text-bg-success">نشط</span><?php else: ?><span class="badge text-bg-secondary">موقوف</span><?php endif; ?></td>
              <td class="text-end text-nowrap">
                <a class="btn btn-sm btn-outline-secondary" href="<?= e(str_replace('id=0', 'id=' . (int)$p['id'], $party_view_base_url)) ?>">عرض</a>
                <?php if ($canEdit): ?>
                  <button type="button" class="btn btn-sm btn-outline-dark js-edit-party"
                    data-bs-toggle="modal" data-bs-target="#partyModal"
                    data-id="<?= (int)$p['id'] ?>"
                    data-code="<?= e((string)($p['code'] ?? '')) ?>"
                    data-name="<?= e((string)($p['name'] ?? '')) ?>"
                    data-phone="<?= e((string)($p['phone'] ?? '')) ?>"
                    data-phone2="<?= e((string)($p['phone2'] ?? '')) ?>"
                    data-email="<?= e((string)($p['email'] ?? '')) ?>"
                    data-address="<?= e((string)($p['address'] ?? '')) ?>"
                    data-tax_no="<?= e((string)($p['tax_no'] ?? '')) ?>"
                    data-notes="<?= e((string)($p['notes'] ?? '')) ?>"
                    data-opening_balance="<?= e((string)($p['opening_balance'] ?? '0')) ?>"
                    data-credit_limit="<?= e((string)($p['credit_limit'] ?? '0')) ?>"
                    data-is_customer="<?= (int)($p['is_customer'] ?? 0) ?>"
                    data-is_supplier="<?= (int)($p['is_supplier'] ?? 0) ?>"
                    data-is_active="<?= (int)($p['is_active'] ?? 0) ?>">تعديل</button>
                  <form method="post" class="d-inline" onsubmit="return confirm('تأكيد حذف الطرف؟')">
                    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                    <button type="submit" class="btn btn-sm btn-outline-danger">حذف</button>
                  </form>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$parties): ?>
            <tr><td colspan="9" class="text-center text-muted py-4">لا توجد بيانات</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <?php if ($total_pages > 1): ?>
      <nav class="mt-3">
        <ul class="pagination justify-content-center flex-wrap mb-0">
          <?php $prev = max(1, $page - 1); $next = min($total_pages, $page + 1); ?>
          <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
            <a class="page-link" href="<?= e($base_index_url . ((str_contains($base_index_url, '?') ? '&' : '?') . http_build_query($baseParams + ['page' => $prev]))) ?>">السابق</a>
          </li>
          <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <?php if ($i === 1 || $i === $total_pages || abs($i - $page) <= 2): ?>
              <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                <a class="page-link" href="<?= e($base_index_url . ((str_contains($base_index_url, '?') ? '&' : '?') . http_build_query($baseParams + ['page' => $i]))) ?>"><?= $i ?></a>
              </li>
            <?php elseif (abs($i - $page) === 3): ?>
              <li class="page-item disabled"><span class="page-link">…</span></li>
            <?php endif; ?>
          <?php endfor; ?>
          <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
            <a class="page-link" href="<?= e($base_index_url . ((str_contains($base_index_url, '?') ? '&' : '?') . http_build_query($baseParams + ['page' => $next]))) ?>">التالي</a>
          </li>
        </ul>
      </nav>
    <?php endif; ?>
  </div>
</div>

<?php if ($canEdit): ?>
<div class="modal fade" id="partyModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable party-modal-dialog">
    <div class="modal-content party-modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="partyModalTitle"><?= e($modalTitle) ?></h5>
        <button type="button" class="btn-close" id="partyModalClose" aria-label="Close"></button>
      </div>
      <form method="post" class="party-form" id="partyForm">
        <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
        <div class="modal-body">
          <input type="hidden" name="action" id="partyAction" value="<?= $edit_party ? 'update' : 'create' ?>">
          <input type="hidden" name="id" id="partyId" value="<?= (int)($edit_party['id'] ?? 0) ?>">
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label">الكود</label>
              <input class="form-control" name="code" id="partyCode" placeholder="اتركه فارغًا للتوليد التلقائي" value="<?= e((string)($edit_party['code'] ?? '')) ?>">
            </div>
            <div class="col-md-8">
              <label class="form-label">الاسم</label>
              <input class="form-control" name="name" id="partyName" required value="<?= e((string)($edit_party['name'] ?? '')) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">هاتف</label>
              <input class="form-control" name="phone" id="partyPhone" value="<?= e((string)($edit_party['phone'] ?? '')) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">هاتف إضافي</label>
              <input class="form-control" name="phone2" id="partyPhone2" value="<?= e((string)($edit_party['phone2'] ?? '')) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">البريد الإلكتروني</label>
              <input class="form-control" name="email" id="partyEmail" type="email" value="<?= e((string)($edit_party['email'] ?? '')) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">الرقم الضريبي</label>
              <input class="form-control" name="tax_no" id="partyTaxNo" value="<?= e((string)($edit_party['tax_no'] ?? '')) ?>">
            </div>
            <div class="col-12">
              <label class="form-label">العنوان</label>
              <input class="form-control" name="address" id="partyAddress" value="<?= e((string)($edit_party['address'] ?? '')) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">رصيد افتتاحي</label>
              <input class="form-control" name="opening_balance" id="partyOpeningBalance" type="number" step="0.01" value="<?= e((string)($edit_party['opening_balance'] ?? '0')) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">حد ائتماني</label>
              <input class="form-control" name="credit_limit" id="partyCreditLimit" type="number" step="0.01" value="<?= e((string)($edit_party['credit_limit'] ?? '0')) ?>">
            </div>
            <div class="col-12">
              <label class="form-label">ملاحظات</label>
              <textarea class="form-control" name="notes" id="partyNotes" rows="3"><?= e((string)($edit_party['notes'] ?? '')) ?></textarea>
            </div>
            <div class="col-12">
              <div class="d-flex flex-wrap gap-3 pt-2">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" name="is_customer" id="partyIsCustomer" <?= $edit_party ? (((int)($edit_party['is_customer'] ?? 0)===1) ? 'checked' : '') : 'checked' ?>>
                  <label class="form-check-label" for="partyIsCustomer">عميل</label>
                </div>
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" name="is_supplier" id="partyIsSupplier" <?= $edit_party ? (((int)($edit_party['is_supplier'] ?? 0)===1) ? 'checked' : '') : '' ?>>
                  <label class="form-check-label" for="partyIsSupplier">مورد</label>
                </div>
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" name="is_active" id="partyIsActive" <?= $edit_party ? (((int)($edit_party['is_active'] ?? 1)===1) ? 'checked' : '') : 'checked' ?>>
                  <label class="form-check-label" for="partyIsActive">نشط</label>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer sticky-bottom bg-white">
          <button type="button" class="btn btn-outline-secondary" id="partyModalCancel">إلغاء</button>
          <button class="btn btn-dark"><?= $edit_party ? 'حفظ التعديلات' : 'إضافة الطرف' ?></button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const modalEl = document.getElementById('partyModal');
  if (!modalEl || typeof bootstrap === 'undefined') return;
  const modal = new bootstrap.Modal(modalEl);
  const form = document.getElementById('partyForm');
  const title = document.getElementById('partyModalTitle');
  const actionInput = document.getElementById('partyAction');
  const idInput = document.getElementById('partyId');
  let dirty = false;
  let suppressDirty = false;

  const fields = {
    code: document.getElementById('partyCode'),
    name: document.getElementById('partyName'),
    phone: document.getElementById('partyPhone'),
    phone2: document.getElementById('partyPhone2'),
    email: document.getElementById('partyEmail'),
    tax_no: document.getElementById('partyTaxNo'),
    address: document.getElementById('partyAddress'),
    opening_balance: document.getElementById('partyOpeningBalance'),
    credit_limit: document.getElementById('partyCreditLimit'),
    notes: document.getElementById('partyNotes'),
    is_customer: document.getElementById('partyIsCustomer'),
    is_supplier: document.getElementById('partyIsSupplier'),
    is_active: document.getElementById('partyIsActive')
  };

  function setDirtyTracking() {
    form.querySelectorAll('input, textarea, select').forEach(el => {
      el.addEventListener('input', () => { if (!suppressDirty) dirty = true; });
      el.addEventListener('change', () => { if (!suppressDirty) dirty = true; });
    });
  }

  function fillForm(data) {
    suppressDirty = true;
    actionInput.value = data.id ? 'update' : 'create';
    idInput.value = data.id || '';
    title.textContent = data.id ? 'تعديل طرف' : 'إضافة طرف جديد';
    fields.code.value = data.code || '';
    fields.name.value = data.name || '';
    fields.phone.value = data.phone || '';
    fields.phone2.value = data.phone2 || '';
    fields.email.value = data.email || '';
    fields.tax_no.value = data.tax_no || '';
    fields.address.value = data.address || '';
    fields.opening_balance.value = data.opening_balance || '0';
    fields.credit_limit.value = data.credit_limit || '0';
    fields.notes.value = data.notes || '';
    fields.is_customer.checked = String(data.is_customer ?? '1') === '1';
    fields.is_supplier.checked = String(data.is_supplier ?? '0') === '1';
    fields.is_active.checked = String(data.is_active ?? '1') === '1';
    dirty = false;
    suppressDirty = false;
  }

  function confirmClose() {
    if (!dirty) return true;
    return confirm('هناك تغييرات لم يتم حفظها. هل تريد إغلاق النافذة؟');
  }

  document.getElementById('openPartyModalBtn')?.addEventListener('click', () => fillForm({is_customer: 1, is_supplier: 0, is_active: 1}));
  document.querySelectorAll('.js-edit-party').forEach(btn => {
    btn.addEventListener('click', () => fillForm(btn.dataset));
  });

  document.getElementById('partyModalClose')?.addEventListener('click', function () {
    if (confirmClose()) modal.hide();
  });
  document.getElementById('partyModalCancel')?.addEventListener('click', function () {
    if (confirmClose()) modal.hide();
  });
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && modalEl.classList.contains('show')) {
      e.preventDefault();
      if (confirmClose()) modal.hide();
    }
  });
  modalEl.addEventListener('hide.bs.modal', function (e) {
    if (!confirmClose()) e.preventDefault();
  });
  form.addEventListener('submit', function(){ dirty = false; });
  setDirtyTracking();
  <?php if ($edit_party): ?>
    fillForm(<?= json_encode([
      'id' => (int)$edit_party['id'], 'code' => (string)($edit_party['code'] ?? ''), 'name' => (string)($edit_party['name'] ?? ''),
      'phone' => (string)($edit_party['phone'] ?? ''), 'phone2' => (string)($edit_party['phone2'] ?? ''), 'email' => (string)($edit_party['email'] ?? ''),
      'tax_no' => (string)($edit_party['tax_no'] ?? ''), 'address' => (string)($edit_party['address'] ?? ''), 'opening_balance' => (string)($edit_party['opening_balance'] ?? '0'),
      'credit_limit' => (string)($edit_party['credit_limit'] ?? '0'), 'notes' => (string)($edit_party['notes'] ?? ''),
      'is_customer' => (int)($edit_party['is_customer'] ?? 0), 'is_supplier' => (int)($edit_party['is_supplier'] ?? 0), 'is_active' => (int)($edit_party['is_active'] ?? 1)
    ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>);
    modal.show();
  <?php endif; ?>
});
</script>
<?php endif; ?>
