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

$pdo = db();
$svc = new AccountingService($pdo);
$cid = (int)$_SESSION['company_id'];
$uid = (int)($_SESSION['user_id'] ?? 0);
$today = date('Y-m-d');
$err = '';

$advanceAccountId = account_id_by_code($pdo, $cid, '1130');
if (!$advanceAccountId) {
  $seed = $pdo->prepare("SELECT id FROM accounts WHERE company_id=? AND code='1130'");
  $seed->execute([$cid]);
  $advanceAccountId = (int)($seed->fetchColumn() ?: 0);
}

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

$emps = $pdo->prepare("SELECT DISTINCT id, full_name FROM employees WHERE company_id=? ORDER BY full_name");
$emps->execute([$cid]);
$emps = $emps->fetchAll(PDO::FETCH_ASSOC);
$seenEmpIds = [];
$emps = array_values(array_filter($emps, function($row) use (&$seenEmpIds){
  $id = (int)($row['id'] ?? 0);
  if($id <= 0 || isset($seenEmpIds[$id])) return false;
  $seenEmpIds[$id] = true;
  return true;
}));

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

function upload_file_local(string $field, string $destDir): ?string {
  if (empty($_FILES[$field]['name'])) return null;
  if (!is_dir($destDir)) mkdir($destDir, 0775, true);
  $name = basename($_FILES[$field]['name']);
  $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
  $allowed = ['pdf','jpg','jpeg','png','webp'];
  if (!in_array($ext, $allowed, true)) throw new Exception('نوع الملف غير مدعوم');
  $safe = uniqid('adv_', true) . '.' . $ext;
  $to = rtrim($destDir, '/').'/'.$safe;
  if (!move_uploaded_file($_FILES[$field]['tmp_name'], $to)) throw new Exception('تعذر رفع الملف');
  return $to;
}

function getAdvanceRow(PDO $pdo, int $cid, int $advanceId): ?array {
  $sql = "SELECT a.*, e.full_name,
    IFNULL((SELECT SUM(s.amount) FROM employee_advance_settlements s WHERE s.company_id=a.company_id AND s.advance_id=a.id),0) AS settled_amount,
    IFNULL((SELECT SUM(t.amount) FROM employee_advance_transfers t WHERE t.company_id=a.company_id AND t.source_advance_id=a.id),0) AS transferred_out,
    IFNULL((SELECT SUM(t.amount) FROM employee_advance_transfers t WHERE t.company_id=a.company_id AND t.target_advance_id=a.id),0) AS transferred_in,
    EXISTS(SELECT 1 FROM cash_tx_journal_map m WHERE m.cash_tx_id=a.cash_tx_id) AS is_posted,
    ct.cash_account_id AS cash_account_id
  FROM employee_advances a
  JOIN employees e ON e.id=a.employee_id
  LEFT JOIN cash_transactions ct ON ct.id=a.cash_tx_id AND ct.company_id=a.company_id
  WHERE a.company_id=? AND a.id=? LIMIT 1";
  $st = $pdo->prepare($sql);
  $st->execute([$cid, $advanceId]);
  $row = $st->fetch(PDO::FETCH_ASSOC);
  if (!$row) return null;
  $row['remaining_amount'] = max(0, (float)$row['amount'] - (float)$row['settled_amount'] - (float)$row['transferred_out']);
  return $row;
}

function refreshAdvanceStatus(PDO $pdo, int $cid, int $advanceId): void {
  $row = getAdvanceRow($pdo, $cid, $advanceId);
  if (!$row) return;
  $status = ($row['remaining_amount'] <= 0.009) ? 'SETTLED' : 'OPEN';
  $pdo->prepare("UPDATE employee_advances SET status=? WHERE company_id=? AND id=?")->execute([$status, $cid, $advanceId]);
}

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

  if ($action === 'create' && !$err) {
    $employee_id = (int)($_POST['employee_id'] ?? 0);
    $tx_date = $_POST['tx_date'] ?? $today;
    $amount = (float)($_POST['amount'] ?? 0);
    $cash_account_id = (int)($_POST['cash_account_id'] ?? 0);
    $memo = trim($_POST['memo'] ?? '');

    if (!$employee_id) $err = 'اختر الموظف';
    elseif ($amount <= 0) $err = 'المبلغ غير صحيح';
    elseif (!$cash_account_id) $err = 'اختر حساب الخزنة/الصندوق';
    elseif ($tx_date > $today) $err = 'لا يجوز إنشاء حركة بتاريخ أحدث من اليوم';

    try {
      $attach = upload_file_local('attachment', __DIR__.'/../uploads/advances/'.date('Y/m'));
    } catch (Exception $e) {
      $err = $e->getMessage();
    }

    if (!$err) {
      $pdo->beginTransaction();
      try {
        $cashTxId = $svc->createCashTxDraft([
          'company_id' => $cid,
          'tx_date' => $tx_date,
          'tx_type' => 'OUT',
          'cash_account_id' => $cash_account_id,
          'counter_account_id' => $advanceAccountId,
          'amount' => $amount,
          'memo' => 'صرف عهدة موظف: '.$memo,
          'attachment' => $attach ? str_replace(__DIR__.'/../','', $attach) : null,
          'created_by' => $uid,
        ]);

        $st = $pdo->prepare("INSERT INTO employee_advances (company_id, employee_id, tx_date, amount, memo, attachment_path, cash_tx_id, created_by)
                             VALUES (?,?,?,?,?,?,?,?)");
        $st->execute([$cid, $employee_id, $tx_date, $amount, $memo ?: null, $attach ? str_replace(__DIR__.'/../','', $attach) : null, $cashTxId, $uid]);
        $pdo->commit();
        flash_set('تمت إضافة عهدة جديدة بنجاح');
        header('Location: advances.php'); exit;
      } catch (Throwable $e) {
        $pdo->rollBack();
        $err = $e->getMessage();
      }
    }
  }

  if ($action === 'edit' && !$err) {
    $advance_id = (int)($_POST['advance_id'] ?? 0);
    $employee_id = (int)($_POST['employee_id'] ?? 0);
    $tx_date = $_POST['tx_date'] ?? $today;
    $amount = (float)($_POST['amount'] ?? 0);
    $cash_account_id = (int)($_POST['cash_account_id'] ?? 0);
    $memo = trim($_POST['memo'] ?? '');

    $adv = getAdvanceRow($pdo, $cid, $advance_id);
    if (!$adv) $err = 'العهدة غير موجودة';
    elseif ((float)$adv['settled_amount'] > 0 || (float)$adv['transferred_out'] > 0 || (float)$adv['transferred_in'] > 0) $err = 'لا يمكن تعديل عهدة تم تسويتها أو تحويلها';
    elseif ((int)$adv['is_posted'] === 1) $err = 'لا يمكن تعديل عهدة تم ترحيلها';
    elseif (!$employee_id) $err = 'اختر الموظف';
    elseif ($amount <= 0) $err = 'المبلغ غير صحيح';
    elseif (!$cash_account_id) $err = 'اختر حساب الخزنة/الصندوق';
    elseif ($tx_date > $today) $err = 'لا يجوز إنشاء حركة بتاريخ أحدث من اليوم';

    if (!$err) {
      $pdo->beginTransaction();
      try {
        $pdo->prepare("UPDATE employee_advances SET employee_id=?, tx_date=?, amount=?, memo=? WHERE company_id=? AND id=?")
            ->execute([$employee_id, $tx_date, $amount, $memo ?: null, $cid, $advance_id]);
        if (!empty($adv['cash_tx_id'])) {
          $pdo->prepare("UPDATE cash_transactions SET tx_date=?, cash_account_id=?, amount=?, memo=? WHERE company_id=? AND id=?")
              ->execute([$tx_date, $cash_account_id, $amount, 'صرف عهدة موظف: '.$memo, $cid, (int)$adv['cash_tx_id']]);
        }
        $pdo->commit();
        flash_set('تم تعديل العهدة بنجاح');
        header('Location: advances.php'); exit;
      } catch (Throwable $e) {
        $pdo->rollBack();
        $err = $e->getMessage();
      }
    }
  }

  if ($action === 'delete' && !$err) {
    $advance_id = (int)($_POST['advance_id'] ?? 0);

    $adv = getAdvanceRow($pdo, $cid, $advance_id);
    if (!$adv) $err = 'العهدة غير موجودة';
    elseif ((float)$adv['settled_amount'] > 0) $err = 'لا يمكن حذف عهدة تم تسجيل تسوية عليها';
    elseif ((float)$adv['transferred_out'] > 0 || (float)$adv['transferred_in'] > 0) $err = 'لا يمكن حذف عهدة مرتبطة بتحويلات';
    elseif ((int)$adv['is_posted'] === 1) $err = 'لا يمكن حذف عهدة تم ترحيلها';
    else {
      $pdo->beginTransaction();
      try {
        if (!empty($adv['cash_tx_id'])) {
          $pdo->prepare("DELETE FROM cash_transactions WHERE company_id=? AND id=?")
              ->execute([$cid, (int)$adv['cash_tx_id']]);
        }
        $pdo->prepare("DELETE FROM employee_advances WHERE company_id=? AND id=?")
            ->execute([$cid, $advance_id]);
        $pdo->commit();
        flash_set('تم حذف العهدة بنجاح');
        header('Location: advances.php'); exit;
      } catch (Throwable $e) {
        $pdo->rollBack();
        $err = $e->getMessage();
      }
    }
  }


  if ($action === 'settle' && !$err) {
    $advance_id = (int)($_POST['advance_id'] ?? 0);
    $kind = $_POST['kind'] ?? 'EXPENSE';
    $settle_date = $_POST['settle_date'] ?? $today;
    $amount = (float)($_POST['settle_amount'] ?? 0);
    $expense_account_id = (int)($_POST['expense_account_id'] ?? 0);
    $cash_account_id = (int)($_POST['cash_account_id2'] ?? 0);
    $memo = trim($_POST['memo2'] ?? '');

    $adv = getAdvanceRow($pdo, $cid, $advance_id);
    if (!$adv) $err = 'العهدة غير موجودة';
    elseif ($settle_date > $today) $err = 'لا يجوز إنشاء حركة بتاريخ أحدث من اليوم';
    elseif ($amount <= 0) $err = 'المبلغ غير صحيح';
    elseif ($amount > (float)$adv['remaining_amount'] + 0.001) $err = 'المبلغ أكبر من المتبقي في العهدة';
    elseif ($kind === 'EXPENSE' && !$expense_account_id) $err = 'اختر حساب المصروف';
    elseif ($kind === 'RETURN' && !$cash_account_id) $err = 'اختر حساب الخزنة/الصندوق';

    try {
      $attach = upload_file_local('attachment2', __DIR__.'/../uploads/advances/'.date('Y/m'));
    } catch (Exception $e) {
      $err = $e->getMessage();
    }

    if (!$err) {
      $pdo->beginTransaction();
      try {
        $cashTxId = null;
        if ($kind === 'EXPENSE') {
          $ref = 'ADV-EXP-'.$advance_id.'-'.time();
          $svc->createManualJournal($cid, $settle_date, $ref, 'تسوية عهدة بمصروف', [
            ['account_id'=>$expense_account_id, 'debit'=>$amount, 'credit'=>0, 'description'=>'مصروف تسوية عهدة'],
            ['account_id'=>$advanceAccountId, 'debit'=>0, 'credit'=>$amount, 'description'=>'تسوية عهدة الموظف'],
          ], $uid, 'ADV_SETTLE', $advance_id);
        } else {
          $cashTxId = $svc->createCashTxDraft([
            'company_id' => $cid,
            'tx_date' => $settle_date,
            'tx_type' => 'IN',
            'cash_account_id' => $cash_account_id,
            'counter_account_id' => $advanceAccountId,
            'amount' => $amount,
            'memo' => 'رد عهدة للخزنة'.($memo ? ' - '.$memo : ''),
            'attachment' => $attach ? str_replace(__DIR__.'/../','', $attach) : null,
            'created_by' => $uid,
          ]);
        }

        $st = $pdo->prepare("INSERT INTO employee_advance_settlements (company_id, advance_id, settle_date, kind, amount, expense_account_id, memo, attachment_path, cash_tx_id, created_by)
                             VALUES (?,?,?,?,?,?,?,?,?,?)");
        $st->execute([$cid, $advance_id, $settle_date, $kind, $amount, $expense_account_id ?: null, $memo ?: null, $attach ? str_replace(__DIR__.'/../','', $attach) : null, $cashTxId, $uid]);
        refreshAdvanceStatus($pdo, $cid, $advance_id);
        $pdo->commit();
        flash_set($kind === 'RETURN' ? 'تمت تسوية العهدة برد للخزنة' : 'تمت تسوية العهدة كمصروف');
        header('Location: advances.php'); exit;
      } catch (Throwable $e) {
        $pdo->rollBack();
        $err = $e->getMessage();
      }
    }
  }

  if ($action === 'transfer' && !$err) {
    $source_advance_id = (int)($_POST['source_advance_id'] ?? 0);
    $to_employee_id = (int)($_POST['to_employee_id'] ?? 0);
    $transfer_date = $_POST['transfer_date'] ?? $today;
    $amount = (float)($_POST['transfer_amount'] ?? 0);
    $memo = trim($_POST['transfer_memo'] ?? '');

    $source = getAdvanceRow($pdo, $cid, $source_advance_id);
    if (!$source) $err = 'العهدة المصدر غير موجودة';
    elseif (!$to_employee_id) $err = 'اختر الموظف المحول إليه';
    elseif ($to_employee_id === (int)$source['employee_id']) $err = 'لا يمكن التحويل إلى نفس الموظف';
    elseif ($amount <= 0) $err = 'المبلغ غير صحيح';
    elseif ($amount > (float)$source['remaining_amount'] + 0.001) $err = 'المبلغ أكبر من المتبقي في العهدة';
    elseif ($transfer_date > $today) $err = 'لا يجوز إنشاء حركة بتاريخ أحدث من اليوم';

    if (!$err) {
      $pdo->beginTransaction();
      try {
        $noteTo = 'محولة من العهدة #'.$source_advance_id.($memo ? ' - '.$memo : '');
        $st = $pdo->prepare("INSERT INTO employee_advances (company_id, employee_id, tx_date, amount, memo, cash_tx_id, created_by)
                             VALUES (?,?,?,?,?,?,?)");
        $st->execute([$cid, $to_employee_id, $transfer_date, $amount, $noteTo, null, $uid]);
        $targetAdvanceId = (int)$pdo->lastInsertId();

        $st = $pdo->prepare("INSERT INTO employee_advance_transfers (company_id, source_advance_id, target_advance_id, from_employee_id, to_employee_id, transfer_date, amount, memo, created_by)
                             VALUES (?,?,?,?,?,?,?,?,?)");
        $st->execute([$cid, $source_advance_id, $targetAdvanceId, (int)$source['employee_id'], $to_employee_id, $transfer_date, $amount, $memo ?: null, $uid]);

        refreshAdvanceStatus($pdo, $cid, $source_advance_id);
        refreshAdvanceStatus($pdo, $cid, $targetAdvanceId);
        $pdo->commit();
        flash_set('تم تحويل العهدة بنجاح');
        header('Location: advances.php'); exit;
      } catch (Throwable $e) {
        $pdo->rollBack();
        $err = $e->getMessage();
      }
    }
  }
}

$employeeRows = $pdo->prepare("SELECT e.id, e.full_name,
  COUNT(a.id) AS advances_count,
  IFNULL(SUM(a.amount),0) AS total_amount,
  IFNULL(SUM((SELECT IFNULL(SUM(s.amount),0) FROM employee_advance_settlements s WHERE s.company_id=a.company_id AND s.advance_id=a.id)),0) AS settled_amount,
  IFNULL(SUM((SELECT IFNULL(SUM(t.amount),0) FROM employee_advance_transfers t WHERE t.company_id=a.company_id AND t.source_advance_id=a.id)),0) AS transferred_out
FROM employees e
JOIN employee_advances a ON a.employee_id=e.id AND a.company_id=e.company_id
WHERE e.company_id=?
GROUP BY e.id, e.full_name
ORDER BY e.full_name");
$employeeRows->execute([$cid]);
$employeeRows = $employeeRows->fetchAll(PDO::FETCH_ASSOC);

$advRows = $pdo->prepare("SELECT a.*, e.full_name,
  IFNULL((SELECT SUM(s.amount) FROM employee_advance_settlements s WHERE s.company_id=a.company_id AND s.advance_id=a.id),0) AS settled_amount,
  IFNULL((SELECT SUM(t.amount) FROM employee_advance_transfers t WHERE t.company_id=a.company_id AND t.source_advance_id=a.id),0) AS transferred_out,
  IFNULL((SELECT SUM(t.amount) FROM employee_advance_transfers t WHERE t.company_id=a.company_id AND t.target_advance_id=a.id),0) AS transferred_in,
  EXISTS(SELECT 1 FROM cash_tx_journal_map m WHERE m.cash_tx_id=a.cash_tx_id) AS is_posted,
  ct.cash_account_id AS cash_account_id
FROM employee_advances a
JOIN employees e ON e.id=a.employee_id
LEFT JOIN cash_transactions ct ON ct.id=a.cash_tx_id AND ct.company_id=a.company_id
WHERE a.company_id=?
ORDER BY e.full_name, a.id DESC");
$advRows->execute([$cid]);
$advRows = $advRows->fetchAll(PDO::FETCH_ASSOC);

$advanceIds = array_map(fn($r)=>(int)$r['id'], $advRows);
$advByEmployee = [];
foreach ($advRows as $r) {
  $r['remaining_amount'] = max(0, (float)$r['amount'] - (float)$r['settled_amount'] - (float)$r['transferred_out']);
  $advByEmployee[(int)$r['employee_id']][] = $r;
}

$settlementsByAdvance = [];
$transfersBySource = [];
$transfersByTarget = [];
if ($advanceIds) {
  $in = implode(',', array_fill(0, count($advanceIds), '?'));
  $sqlSet = "SELECT s.*, a.code AS expense_code, a.name AS expense_name
             FROM employee_advance_settlements s
             LEFT JOIN accounts a ON a.id=s.expense_account_id
             WHERE s.company_id=? AND s.advance_id IN ($in)
             ORDER BY s.id DESC";
  $st = $pdo->prepare($sqlSet);
  $st->execute(array_merge([$cid], $advanceIds));
  foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $settlementsByAdvance[(int)$row['advance_id']][] = $row;
  }

  $sqlTr = "SELECT t.*, ef.full_name AS from_name, et.full_name AS to_name
            FROM employee_advance_transfers t
            JOIN employees ef ON ef.id=t.from_employee_id
            JOIN employees et ON et.id=t.to_employee_id
            WHERE t.company_id=? AND (t.source_advance_id IN ($in) OR t.target_advance_id IN ($in))
            ORDER BY t.id DESC";
  $st = $pdo->prepare($sqlTr);
  $st->execute(array_merge([$cid], $advanceIds, $advanceIds));
  foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $transfersBySource[(int)$row['source_advance_id']][] = $row;
    $transfersByTarget[(int)$row['target_advance_id']][] = $row;
  }
}

render_layout('عهد الموظفين','الموارد البشرية <span class="mx-1">/</span> عهد الموظفين', function() use ($emps,$cashAccounts,$expenseAccounts,$employeeRows,$advByEmployee,$settlementsByAdvance,$transfersBySource,$transfersByTarget,$err,$today) {
?>
<div class="container-fluid mt-3">
  <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
    <div>
      <div class="fw-bold fs-4">إدارة عهد الموظفين</div>
      <div class="text-secondary small">إضافة وتعديل وتسوية وتحويل العهد من خلال نوافذ سريعة داخل الصفحة.</div>
    </div>
    <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#advanceCreateModal"><i class="bi bi-plus-circle"></i> صرف عهدة جديدة</button>
  </div>

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

  <div class="card cardx">
    <div class="p-3 border-bottom d-flex justify-content-between align-items-center flex-wrap gap-2">
      <div class="fw-bold">الموظفون الذين لديهم عهد</div>
      <div class="text-secondary small">اضغط على الموظف لعرض العهد، واضغط على العهدة لعرض تفاصيل الصرف والتسوية والتحويل.</div>
    </div>
    <div class="table-responsive">
      <table class="table align-middle mb-0 adv-table">
        <thead>
          <tr class="text-secondary small">
            <th style="width:42px"></th>
            <th>الموظف</th>
            <th class="text-end">إجمالي العهد</th>
            <th class="text-end">التسويات</th>
            <th class="text-end">المتبقي</th>
            <th class="text-center">عدد العهد</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($employeeRows as $emp): 
          $empId = (int)$emp['id'];
          $remainingEmp = (float)$emp['total_amount'] - (float)$emp['settled_amount'] - (float)$emp['transferred_out'];
        ?>
          <tr class="employee-row" data-bs-toggle="collapse" data-bs-target="#empRow<?= $empId ?>" aria-expanded="false" style="cursor:pointer">
            <td><button class="btn btn-sm btn-light"><i class="bi bi-chevron-down"></i></button></td>
            <td class="fw-semibold"><?= h($emp['full_name']) ?></td>
            <td class="text-end fw-semibold"><?= number_format((float)$emp['total_amount'],2) ?></td>
            <td class="text-end"><?= number_format((float)$emp['settled_amount'],2) ?></td>
            <td class="text-end"><span class="badge text-bg-light border"><?= number_format($remainingEmp,2) ?></span></td>
            <td class="text-center"><?= (int)$emp['advances_count'] ?></td>
          </tr>
          <tr class="collapse bg-body-tertiary" id="empRow<?= $empId ?>">
            <td colspan="6" class="p-0">
              <div class="p-3">
                <div class="table-responsive">
                  <table class="table table-sm align-middle mb-0">
                    <thead>
                      <tr class="text-secondary small">
                        <th style="width:42px"></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(($advByEmployee[$empId] ?? []) as $adv): ?>
                      <tr>
                        <td><button class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#advDetails<?= (int)$adv['id'] ?>"><i class="bi bi-list-ul"></i></button></td>
                        <td class="fw-semibold">#<?= (int)$adv['id'] ?></td>
                        <td><?= h($adv['tx_date']) ?></td>
                        <td class="text-end"><?= number_format((float)$adv['amount'],2) ?></td>
                        <td class="text-end fw-semibold"><?= number_format((float)$adv['remaining_amount'],2) ?></td>
                        <td>
                          <?php if((float)$adv['remaining_amount'] > 0.009): ?>
                            <span class="badge bg-warning-subtle text-warning border border-warning-subtle">مفتوحة</span>
                          <?php else: ?>
                            <span class="badge bg-success-subtle text-success border border-success-subtle">مسوّاة</span>
                          <?php endif; ?>
                          <?php if((int)$adv['is_posted'] === 1): ?><span class="badge bg-primary-subtle text-primary border border-primary-subtle">مُرحّلة</span><?php endif; ?>
                        </td>
                        <td class="text-end">
                          <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-primary js-open-edit-advance"
                              data-id="<?= (int)$adv['id'] ?>"
                              data-employee="<?= (int)$adv['employee_id'] ?>"
                              data-date="<?= h($adv['tx_date']) ?>"
                              data-amount="<?= h($adv['amount']) ?>"
                              data-cash-account="<?= h((string)($adv['cash_account_id'] ?? '')) ?>"
                              data-memo="<?= h((string)$adv['memo']) ?>"
                              data-posted="<?= (int)$adv['is_posted'] ?>"
                              data-remaining="<?= h((string)$adv['remaining_amount']) ?>"
                              <?= ((float)$adv['settled_amount'] > 0 || (float)$adv['transferred_out'] > 0 || (float)$adv['transferred_in'] > 0 || (int)$adv['is_posted'] === 1) ? 'disabled' : '' ?>><i class="bi bi-pencil"></i></button>
                            <button class="btn btn-outline-success js-open-settle-advance"
                              data-id="<?= (int)$adv['id'] ?>"
                              data-remaining="<?= h((string)$adv['remaining_amount']) ?>"
                              data-bs-toggle="modal" data-bs-target="#advanceSettleModal"
                              <?= ((float)$adv['remaining_amount'] <= 0.009) ? 'disabled' : '' ?>><i class="bi bi-check2-circle"></i></button>
                            <button class="btn btn-outline-dark js-open-transfer-advance"
                              data-id="<?= (int)$adv['id'] ?>"
                              data-employee="<?= (int)$adv['employee_id'] ?>"
                              data-remaining="<?= h((string)$adv['remaining_amount']) ?>"
                              data-bs-toggle="modal" data-bs-target="#advanceTransferModal"
                              <?= ((float)$adv['remaining_amount'] <= 0.009) ? 'disabled' : '' ?>><i class="bi bi-arrow-left-right"></i></button>
                            <button class="btn btn-outline-danger js-open-delete-advance"
                              data-id="<?= (int)$adv['id'] ?>"
                              data-bs-toggle="modal" data-bs-target="#advanceDeleteModal"
                              <?= ((float)$adv['settled_amount'] > 0 || (float)$adv['transferred_out'] > 0 || (float)$adv['transferred_in'] > 0 || (int)$adv['is_posted'] === 1) ? 'disabled' : '' ?>><i class="bi bi-trash"></i></button>
                          </div>
                        </td>
                      </tr>
                      <tr class="collapse" id="advDetails<?= (int)$adv['id'] ?>">
                        <td colspan="7" class="bg-light-subtle">
                          <div class="p-3">
                            <div class="row g-3">
                              <div class="col-lg-6">
                                <div class="fw-bold mb-2">تفاصيل التسويات والصرف</div>
                                <div class="list-group small shadow-sm">
                                  <?php foreach(($settlementsByAdvance[(int)$adv['id']] ?? []) as $s): ?>
                                    <div class="list-group-item">
                                      <div class="d-flex justify-content-between gap-2 flex-wrap">
                                        <div>
                                          <span class="badge <?= $s['kind']==='RETURN' ? 'text-bg-primary' : 'text-bg-success' ?>"><?= $s['kind']==='RETURN' ? 'رد للخزنة' : 'مصروف' ?></span>
                                          <span class="ms-1"><?= h($s['settle_date']) ?></span>
                                        </div>
                                        <div class="fw-semibold"><?= number_format((float)$s['amount'],2) ?></div>
                                      </div>
                                      <div class="mt-1 text-secondary">
                                        <?php if($s['kind']==='EXPENSE' && $s['expense_name']): ?>اتصرفت في: <?= h(($s['expense_code'] ? $s['expense_code'].' - ' : '').$s['expense_name']) ?><br><?php endif; ?>
                                        <?= h((string)$s['memo']) ?>
                                      </div>
                                    </div>
                                  <?php endforeach; ?>
                                  <?php if(empty($settlementsByAdvance[(int)$adv['id']])): ?>
                                    <div class="list-group-item text-secondary">لا توجد تسويات حتى الآن.</div>
                                  <?php endif; ?>
                                </div>
                              </div>
                              <div class="col-lg-6">
                                <div class="fw-bold mb-2">تفاصيل التحويلات</div>
                                <div class="list-group small shadow-sm">
                                  <?php foreach(($transfersBySource[(int)$adv['id']] ?? []) as $t): ?>
                                    <div class="list-group-item">
                                      <div class="d-flex justify-content-between gap-2 flex-wrap">
                                        <div><span class="badge text-bg-dark">تحويل صادر</span> <?= h($t['transfer_date']) ?></div>
                                        <div class="fw-semibold"><?= number_format((float)$t['amount'],2) ?></div>
                                      </div>
                                      <div class="mt-1 text-secondary">إلى الموظف: <?= h($t['to_name']) ?><?= $t['memo'] ? ' — '.h($t['memo']) : '' ?></div>
                                    </div>
                                  <?php endforeach; ?>
                                  <?php foreach(($transfersByTarget[(int)$adv['id']] ?? []) as $t): ?>
                                    <div class="list-group-item">
                                      <div class="d-flex justify-content-between gap-2 flex-wrap">
                                        <div><span class="badge text-bg-info">تحويل وارد</span> <?= h($t['transfer_date']) ?></div>
                                        <div class="fw-semibold"><?= number_format((float)$t['amount'],2) ?></div>
                                      </div>
                                      <div class="mt-1 text-secondary">من الموظف: <?= h($t['from_name']) ?><?= $t['memo'] ? ' — '.h($t['memo']) : '' ?></div>
                                    </div>
                                  <?php endforeach; ?>
                                  <?php if(empty($transfersBySource[(int)$adv['id']]) && empty($transfersByTarget[(int)$adv['id']])): ?>
                                    <div class="list-group-item text-secondary">لا توجد تحويلات مرتبطة بهذه العهدة.</div>
                                  <?php endif; ?>
                                </div>
                              </div>
                            </div>
                          </div>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                    <?php if(empty($advByEmployee[$empId])): ?>
                      <tr><td colspan="7" class="text-center text-secondary py-3">لا توجد عهد لهذا الموظف.</td></tr>
                    <?php endif; ?>
                    </tbody>
                  </table>
                </div>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if(!count($employeeRows)): ?>
          <tr><td colspan="6" class="text-center py-5 text-secondary">لا توجد عهد موظفين حتى الآن.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Create Modal -->
<div class="modal fade" id="advanceCreateModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="create">
        <div class="modal-header"><h5 class="modal-title">صرف عهدة جديدة</h5><button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button></div>
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">الموظف</label>
              <select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" data-dropup-auto="false" title="اختر الموظف" required id="adv_employee_id" name="employee_id">
                <?php foreach($emps as $e): ?>
                  <option value="<?= (int)$e['id'] ?>"><?= h($e['full_name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-3"><label class="form-label">التاريخ</label><?= render_date_input('tx_date', $today) ?></div>
            <div class="col-md-3"><label class="form-label">المبلغ</label><input class="form-control" type="number" step="0.01" name="amount" required></div>
            <div class="col-md-6">
              <label class="form-label">الخزنة/الصندوق</label>
              <select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" data-dropup-auto="false" title="اختر الخزنة/الصندوق" required id="adv_cash_account_id" name="cash_account_id">
                <?php foreach($cashAccounts as $a): ?>
                  <option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6"><label class="form-label">بيان</label><input class="form-control" name="memo" placeholder="مثال: عهدة تشغيلية / بنزين"></div>
            <div class="col-12"><label class="form-label">مرفق</label><input class="form-control" type="file" name="attachment" accept=".pdf,.jpg,.jpeg,.png,.webp"></div>
          </div>
        </div>
        <div class="modal-footer"><button class="btn btn-dark">حفظ وصرف العهدة</button></div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="advanceEditModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="advance_id" id="edit_advance_id">
        <div class="modal-header"><h5 class="modal-title">تعديل عهدة</h5><button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button></div>
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6"><label class="form-label">الموظف</label><select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" data-dropup-auto="false" title="اختر الموظف" required id="edit_employee_id" name="employee_id"><?php foreach($emps as $e): ?><option value="<?= (int)$e['id'] ?>"><?= h($e['full_name']) ?></option><?php endforeach; ?></select></div>
            <div class="col-md-3"><label class="form-label">التاريخ</label><input class="form-control datepick" type="text" id="edit_tx_date" name="tx_date" value="<?= h($today) ?>"></div>
            <div class="col-md-3"><label class="form-label">المبلغ</label><input class="form-control" type="number" step="0.01" id="edit_amount" name="amount" required></div>
            <div class="col-md-6"><label class="form-label">الخزنة/الصندوق</label><select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" data-dropup-auto="false" title="اختر الخزنة/الصندوق" id="edit_cash_account_id" name="cash_account_id" required><?php foreach($cashAccounts as $a): ?><option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option><?php endforeach; ?></select></div><div class="col-md-6"><label class="form-label">بيان</label><input class="form-control" id="edit_memo" name="memo"></div>
            <div class="col-12 text-secondary small">التعديل متاح فقط قبل وجود تسويات/تحويلات وقبل الترحيل.</div>
          </div>
        </div>
        <div class="modal-footer"><button class="btn btn-primary">حفظ التعديلات</button></div>
      </form>
    </div>
  </div>
</div>

<!-- Settle Modal -->
<div class="modal fade" id="advanceSettleModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="settle">
        <input type="hidden" name="advance_id" id="settle_advance_id">
        <div class="modal-header"><h5 class="modal-title">تسوية عهدة</h5><button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button></div>
        <div class="modal-body">
          <div class="alert alert-light border small mb-3">المتبقي في العهدة: <span class="fw-bold" id="settle_remaining">0.00</span></div>
          <div class="row g-3">
            <div class="col-md-4"><label class="form-label">التاريخ</label><input class="form-control datepick" type="text" name="settle_date" value="<?= h($today) ?>"></div>
            <div class="col-md-4"><label class="form-label">المبلغ</label><input class="form-control" type="number" step="0.01" name="settle_amount" id="settle_amount" required></div>
            <div class="col-md-4"><label class="form-label">النوع</label><select class="form-select" name="kind" id="kindSel"><option value="EXPENSE">تسوية كمصروف</option><option value="RETURN">رد للخزنة</option></select></div>

            <div class="col-12" id="expenseBox">
              <label class="form-label">حساب المصروف</label>
              <select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" data-dropup-auto="false" title="اختر حساب المصروف" id="expense_account_id" name="expense_account_id">
                <?php foreach($expenseAccounts as $a): ?>
                  <option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-12 d-none" id="cashBox">
              <label class="form-label">الخزنة/الصندوق</label>
              <select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" data-dropup-auto="false" title="اختر الخزنة/الصندوق" id="cash_account_id2" name="cash_account_id2">
                <?php foreach($cashAccounts as $a): ?>
                  <option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-12"><label class="form-label">بيان</label><input class="form-control" name="memo2"></div>
            <div class="col-12"><label class="form-label">مرفق</label><input class="form-control" type="file" name="attachment2" accept=".pdf,.jpg,.jpeg,.png,.webp"></div>
          </div>
        </div>
        <div class="modal-footer"><button class="btn btn-success">تسجيل التسوية</button></div>
      </form>
    </div>
  </div>
</div>

<!-- Transfer Modal -->
<div class="modal fade" id="advanceTransferModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="transfer">
        <input type="hidden" name="source_advance_id" id="transfer_advance_id">
        <div class="modal-header"><h5 class="modal-title">تحويل عهدة إلى موظف آخر</h5><button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button></div>
        <div class="modal-body">
          <div class="alert alert-light border small mb-3">المتبقي القابل للتحويل: <span class="fw-bold" id="transfer_remaining">0.00</span></div>
          <div class="row g-3">
            <div class="col-md-4"><label class="form-label">التاريخ</label><input class="form-control datepick" type="text" name="transfer_date" value="<?= h($today) ?>"></div>
            <div class="col-md-4"><label class="form-label">المبلغ</label><input class="form-control" type="number" step="0.01" name="transfer_amount" id="transfer_amount" required></div>
            <div class="col-md-4">
              <label class="form-label">الموظف المحول إليه</label>
              <select
                class="selectpicker"
                data-style="form-select"
                data-live-search="true"
                data-size="8"
                data-width="100%"
                data-dropup-auto="false"
                title="اختر الموظف المحول إليه"
                name="to_employee_id"
                id="transfer_to_employee"
                required
              >
                <?php foreach($emps as $e): ?>
                  <option value="<?= (int)$e['id'] ?>"><?= h($e['full_name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-12"><label class="form-label">ملاحظات التحويل</label><input class="form-control" name="transfer_memo" placeholder="مثال: تم تحويل العهدة لاستكمال مهمة لدى موظف آخر"></div>
          </div>
        </div>
        <div class="modal-footer"><button class="btn btn-dark">تحويل العهدة</button></div>
      </form>
    </div>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="advanceDeleteModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="delete">
        <input type="hidden" name="advance_id" id="delete_advance_id">
        <div class="modal-header"><h5 class="modal-title">حذف العهدة</h5><button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button></div>
        <div class="modal-body py-3">تأكيد حذف العهدة</div>
        <div class="modal-footer">
          <button type="button" class="btn btn-light border" data-bs-dismiss="modal">إلغاء</button>
          <button class="btn btn-danger">حذف العهدة</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const editModalEl = document.getElementById('advanceEditModal');
  const editModal = editModalEl ? new bootstrap.Modal(editModalEl) : null;

  const transferSelectEl = document.getElementById('transfer_to_employee');
  const $transferSelect = window.jQuery ? window.jQuery(transferSelectEl) : null;

  const settleAdvanceIdEl = document.getElementById('settle_advance_id');
  const settleRemainingEl = document.getElementById('settle_remaining');
  const settleAmountEl = document.getElementById('settle_amount');

  const transferAdvanceIdEl = document.getElementById('transfer_advance_id');
  const transferRemainingEl = document.getElementById('transfer_remaining');
  const transferAmountEl = document.getElementById('transfer_amount');
  const deleteAdvanceIdEl = document.getElementById('delete_advance_id');

  const editAdvanceIdEl = document.getElementById('edit_advance_id');
  const editTxDateEl = document.getElementById('edit_tx_date');
  const editAmountEl = document.getElementById('edit_amount');
  const editMemoEl = document.getElementById('edit_memo');

  const kindEl = document.getElementById('kindSel');
  const expenseBoxEl = document.getElementById('expenseBox');
  const cashBoxEl = document.getElementById('cashBox');

  function refreshPicker(selector) {
    if (!window.jQuery) return;
    const $el = window.jQuery(selector);
    if ($el.length && typeof $el.selectpicker === 'function') {
      $el.selectpicker('refresh');
    }
  }

  function setPickerValue(selector, value) {
    if (!window.jQuery) return;
    const $el = window.jQuery(selector);
    if ($el.length && typeof $el.selectpicker === 'function') {
      $el.selectpicker('val', value || '');
      $el.selectpicker('render');
    }
  }

  function resetTransferEmployees(currentEmp) {
    if (!transferSelectEl || !$transferSelect || typeof $transferSelect.selectpicker !== 'function') return;

    Array.from(transferSelectEl.options).forEach(function (opt) {
      opt.disabled = !!currentEmp && String(opt.value) === String(currentEmp);
      opt.selected = false;
    });

    $transferSelect.selectpicker('val', '');
    $transferSelect.selectpicker('render');
  }

  function syncKind() {
    if (!kindEl || !expenseBoxEl || !cashBoxEl) return;

    if (kindEl.value === 'RETURN') {
      expenseBoxEl.classList.add('d-none');
      cashBoxEl.classList.remove('d-none');
      refreshPicker('#cash_account_id2');
    } else {
      cashBoxEl.classList.add('d-none');
      expenseBoxEl.classList.remove('d-none');
      refreshPicker('#expense_account_id');
    }
  }

  document.querySelectorAll('.js-open-edit-advance').forEach(function (btn) {
    btn.addEventListener('click', function () {
      if (btn.disabled) return;

      if (editAdvanceIdEl) editAdvanceIdEl.value = btn.dataset.id || '';
      if (editTxDateEl) editTxDateEl.value = btn.dataset.date || '';
      if (editAmountEl) editAmountEl.value = btn.dataset.amount || '';
      if (editMemoEl) editMemoEl.value = btn.dataset.memo || '';

      setPickerValue('#edit_employee_id', btn.dataset.employee || '');
      setPickerValue('#edit_cash_account_id', btn.dataset.cashAccount || '');

      if (editModal) editModal.show();
    });
  });

  document.querySelectorAll('.js-open-settle-advance').forEach(function (btn) {
    btn.addEventListener('click', function () {
      if (settleAdvanceIdEl) settleAdvanceIdEl.value = btn.dataset.id || '';
      if (settleRemainingEl) settleRemainingEl.textContent = btn.dataset.remaining || '0.00';
      if (settleAmountEl) settleAmountEl.value = btn.dataset.remaining || '';
    });
  });

  document.querySelectorAll('.js-open-transfer-advance').forEach(function (btn) {
    btn.addEventListener('click', function () {
      if (transferAdvanceIdEl) transferAdvanceIdEl.value = btn.dataset.id || '';
      if (transferRemainingEl) transferRemainingEl.textContent = btn.dataset.remaining || '0.00';
      if (transferAmountEl) transferAmountEl.value = btn.dataset.remaining || '';

      resetTransferEmployees(btn.dataset.employee || '');
    });
  });

  document.querySelectorAll('.js-open-delete-advance').forEach(function (btn) {
    btn.addEventListener('click', function () {
      if (deleteAdvanceIdEl) deleteAdvanceIdEl.value = btn.dataset.id || '';
    });
  });

  const transferModalEl = document.getElementById('advanceTransferModal');
  if (transferModalEl) {
    transferModalEl.addEventListener('hidden.bs.modal', function () {
      resetTransferEmployees('');
    });
  }

  if (kindEl) {
    kindEl.addEventListener('change', syncKind);
    syncKind();
  }

  refreshPicker('#adv_employee_id');
  refreshPicker('#adv_cash_account_id');
  refreshPicker('#edit_employee_id');
  refreshPicker('#edit_cash_account_id');
  refreshPicker('#expense_account_id');
  refreshPicker('#cash_account_id2');
  refreshPicker('#transfer_to_employee');
});
</script>
<?php }); ?>