<?php

$page_title = 'أرصدة المعتمدين';
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/agent_service.php';

require_login();
$conn = ensure_db(true);
if (function_exists('require_any_perm')) require_any_perm(['can_manage_agent_balances','can_manage_agents']);
ua_agent_schema_migrate($conn);
$actorId = (int)($_SESSION['admin_id'] ?? $_SESSION['admin_user_id'] ?? 0);
$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!ua_csrf_verify()) {
    $err = 'انتهت صلاحية الطلب.';
  } else {
    $agentId = (int)($_POST['agent_id'] ?? 0);
    $amount = round((float)($_POST['amount'] ?? 0), 2);
    $note = trim((string)($_POST['note'] ?? ''));
    $reference = trim((string)($_POST['reference'] ?? '')) ?: ('ADMIN-' . date('YmdHis') . '-' . $agentId);
    $action = (string)($_POST['action'] ?? '');
    if ($agentId <= 0 || $amount <= 0) {
      $err = 'اختر المعتمد وأدخل مبلغاً أكبر من صفر.';
    } elseif ($action === 'receipt') {
      $result = ua_agent_service_post_receipt($conn, $agentId, $amount, $reference, $note, ['type'=>'admin','id'=>$actorId]);
      $result['ok'] ? $msg = 'تم تسجيل القبض وتخفيض الرصيد المستحق.' : $err = $result['error'];
    } elseif (in_array($action, ['debit_adjustment','credit_adjustment'], true)) {
      $result = ua_agent_ledger_post($conn, [
        'agent_id'=>$agentId,
        'direction'=>$action === 'debit_adjustment' ? 'DEBIT' : 'CREDIT',
        'entry_type'=>'ADMIN_ADJUSTMENT',
        'amount'=>$amount,
        'idempotency_key'=>'ADMIN_ADJUSTMENT:' . $reference,
        'source_type'=>'admin_adjustment',
        'source_id'=>$reference,
        'description'=>$note,
        'created_by_type'=>'admin',
        'created_by_id'=>$actorId,
      ]);
      $result['ok'] ? $msg = 'تم تسجيل التسوية المالية.' : $err = $result['error'];
    }
  }
}

$agentId = (int)($_GET['agent_id'] ?? 0);
$agents = ua_agent_repo_list($conn);
$totals = ['due'=>0.0,'debit'=>0.0,'credit'=>0.0,'agents'=>count($agents)];
foreach ($agents as &$agent) {
  $agent['ledger_balance'] = ua_agent_ledger_balance($conn, (int)$agent['id']);
  $totals['due'] += $agent['ledger_balance'];
}
unset($agent);
$where = $agentId > 0 ? 'WHERE l.agent_id=' . $agentId : '';
$entries = [];
$rs = @$conn->query("SELECT l.*,a.full_name agent_name,a.code agent_code FROM agent_ledger_entries l LEFT JOIN agents a ON a.id=l.agent_id {$where} ORDER BY l.occurred_at DESC,l.id DESC LIMIT 500");
if ($rs) while ($row = $rs->fetch_assoc()) {
  $entries[] = $row;
  if (in_array($row['status'], ['POSTED','REVERSED'], true)) {
    if ($row['direction'] === 'DEBIT') $totals['debit'] += (float)$row['amount'];
    if ($row['direction'] === 'CREDIT') $totals['credit'] += (float)$row['amount'];
  }
}

$uaAndroidAgentBalances = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidAgentBalances) $UA_PAGE_CSS = ['assets/css/android_agents_balances.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
if ($uaAndroidAgentBalances) {
  require __DIR__ . '/android_agents_balances.php';
  include __DIR__ . '/footer.php';
  return;
}
?>
<div class="content-wrapper ua-extracted-page ua-agents-page">
  <section class="content-header"><div class="container-fluid"><h1 class="mb-1">أرصدة المعتمدين</h1><div class="text-muted">كشف حساب مترابط مع الفواتير والمدفوعات والمبيعات</div><?php include __DIR__ . '/agents_nav.php'; ?></div></section>
  <section class="content"><div class="container-fluid">
    <?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?><?php if ($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>
    <div class="ua-agent-kpis"><div class="ua-agent-kpi"><div class="label">إجمالي المستحق</div><div class="value"><?= number_format($totals['due'],2) ?></div></div><div class="ua-agent-kpi"><div class="label">إجمالي القيود المدينة</div><div class="value"><?= number_format($totals['debit'],2) ?></div></div><div class="ua-agent-kpi"><div class="label">إجمالي القيود الدائنة</div><div class="value"><?= number_format($totals['credit'],2) ?></div></div><div class="ua-agent-kpi"><div class="label">عدد المعتمدين</div><div class="value"><?= (int)$totals['agents'] ?></div></div></div>
    <div class="ua-agent-balances-layout">
      <div class="card ua-agent-adjustment-card">
        <div class="card-header ua-agent-card-heading"><div class="ua-agent-card-title"><i class="fa fa-balance-scale"></i><div><strong>قبض أو تسوية</strong><small>تسجيل حركة مالية مباشرة على حساب المعتمد</small></div></div></div>
        <form method="post">
          <div class="card-body ua-agent-adjustment-form"><?php ua_csrf_field(); ?>
            <div class="form-group ua-span-2"><label>المعتمد</label><select required class="form-control" name="agent_id"><option value="">اختر</option><?php foreach ($agents as $agent): ?><option value="<?= (int)$agent['id'] ?>"><?= h($agent['full_name'] ?: $agent['name']) ?> (<?= number_format($agent['ledger_balance'],2) ?>)</option><?php endforeach; ?></select></div>
            <div class="form-group"><label>المبلغ</label><input required class="form-control" type="number" min="0.01" step="0.01" name="amount"></div>
            <div class="form-group"><label>المرجع</label><input class="form-control" name="reference"></div>
            <div class="form-group ua-span-2"><label>البيان</label><textarea class="form-control" name="note" rows="2"></textarea></div>
          </div>
          <div class="card-footer ua-agent-command-bar">
            <span class="text-muted">اختر نوع الحركة</span>
            <div class="ua-agent-command-actions">
              <button class="btn btn-success ua-agent-icon-btn" name="action" value="receipt" title="تسجيل قبض" aria-label="تسجيل قبض"><i class="fa fa-money"></i></button>
              <button class="btn btn-outline-danger ua-agent-icon-btn" name="action" value="debit_adjustment" title="تسوية مدينة" aria-label="تسوية مدينة"><i class="fa fa-minus-circle"></i></button>
              <button class="btn btn-outline-primary ua-agent-icon-btn" name="action" value="credit_adjustment" title="تسوية دائنة" aria-label="تسوية دائنة"><i class="fa fa-plus-circle"></i></button>
            </div>
          </div>
        </form>
      </div>
      <div class="card ua-agent-ledger-card">
        <div class="card-header ua-agent-ledger-toolbar">
          <div class="ua-agent-card-title"><i class="fa fa-book"></i><div><strong>كشف حساب المعتمد</strong><small><?= count($entries) ?> قيد معروض</small></div></div>
          <form method="get" class="ua-agent-ledger-filter">
            <select class="form-control" name="agent_id" aria-label="المعتمد"><option value="0">كل المعتمدين</option><?php foreach ($agents as $agent): ?><option value="<?= (int)$agent['id'] ?>" <?= $agentId===(int)$agent['id']?'selected':'' ?>><?= h($agent['full_name'] ?: $agent['name']) ?></option><?php endforeach; ?></select>
            <button class="btn btn-outline-primary ua-agent-icon-btn" title="عرض كشف الحساب" aria-label="عرض كشف الحساب"><i class="fa fa-eye"></i></button>
          </form>
        </div>
        <div class="card-body p-0"><div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th>التاريخ</th><th>المعتمد</th><th>النوع</th><th>مدين</th><th>دائن</th><th>الرصيد بعد</th><th>البيان</th></tr></thead><tbody><?php if (!$entries): ?><tr><td colspan="7" class="text-center text-muted p-5">لا توجد قيود مالية.</td></tr><?php endif; ?><?php foreach ($entries as $entry): ?><tr><td class="text-nowrap"><?= h($entry['occurred_at']) ?></td><td><?= h($entry['agent_name']) ?></td><td><?= h($entry['entry_type']) ?></td><td class="ua-agent-ledger-debit"><?= $entry['direction']==='DEBIT'?number_format((float)$entry['amount'],2):'' ?></td><td class="ua-agent-ledger-credit"><?= $entry['direction']==='CREDIT'?number_format((float)$entry['amount'],2):'' ?></td><td><?= number_format((float)$entry['balance_after'],2) ?></td><td><?= h($entry['description']) ?></td></tr><?php endforeach; ?></tbody></table></div></div>
      </div>
    </div>
  </div></section>
</div>
<?php include __DIR__ . '/footer.php'; ?>

