<?php
$page_title = 'المدفوعات الخارجة';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidExpenses = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/finance_expenses.css'];
require_once __DIR__ . '/finance_expense_lib.php';
require_login('login.php');
if (function_exists('require_perm')) require_perm('can_view_reports');

$msg = '';
$err = '';
$actorId = (int)($_SESSION['admin_id'] ?? 0);
$channel = $uaAndroidExpenses ? 'android' : 'desktop';

$migration = finance_expense_backfill_ledger($conn, 5000);
if (!empty($migration['failed'])) {
  $err = 'توجد ' . (int)$migration['failed'] . ' حركة قديمة لم تُرحّل إلى الصناديق بسبب عدم كفاية الرصيد أو نقص بيانات الصندوق. لم تُعدّل هذه الحركات جزئياً.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (function_exists('ua_csrf_verify') && !ua_csrf_verify()) {
    $err = 'انتهت صلاحية الطلب. أعد تحميل الصفحة وحاول مجدداً.';
  } else {
    $action = (string)($_POST['action'] ?? '');
    if ($action === 'add_expense') {
      $result = finance_expense_record($conn, [
        'type_name'=>(string)($_POST['type_name'] ?? ''),
        'account_key'=>(string)($_POST['account_key'] ?? ''),
        'amount'=>(float)($_POST['amount'] ?? 0),
        'spent_at'=>(string)($_POST['spent_at'] ?? date('Y-m-d')),
        'reference'=>(string)($_POST['reference'] ?? ''),
        'note'=>(string)($_POST['note'] ?? ''),
        'created_by'=>$actorId,
        'channel'=>$channel,
      ]);
      if (!empty($result['ok'])) {
        header('Location: finance_expenses.php?added=1');
        exit;
      }
      $err = (string)($result['error'] ?? 'تعذر تسجيل المدفوعات الخارجة.');
    } elseif ($action === 'reverse_expense') {
      $result = finance_expense_reverse($conn, (int)($_POST['id'] ?? 0), $actorId);
      if (!empty($result['ok'])) {
        header('Location: finance_expenses.php?reversed=1');
        exit;
      }
      $err = (string)($result['error'] ?? 'تعذر عكس القيد.');
    }
  }
}

if (isset($_GET['added'])) $msg = 'تم تسجيل المدفوعات وخصمها من الصندوق المختار بقيد محاسبي مكتمل.';
if (isset($_GET['reversed'])) $msg = 'تم عكس القيد وإعادة قيمته إلى الصندوق مع الاحتفاظ بسجل التدقيق.';

$from = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($_GET['from'] ?? '')) ? (string)$_GET['from'] : date('Y-m-01');
$to = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($_GET['to'] ?? '')) ? (string)$_GET['to'] : date('Y-m-t');
if ($from > $to) [$from, $to] = [$to, $from];
$typeId = max(0, (int)($_GET['type_id'] ?? 0));
$accountFilter = trim((string)($_GET['account'] ?? 'all')) ?: 'all';
$statusFilter = strtoupper(trim((string)($_GET['status'] ?? 'POSTED')));
if (!in_array($statusFilter, ['POSTED','REVERSED','ALL'], true)) $statusFilter = 'POSTED';

$types = finance_expense_types($conn);
$accounts = finance_expense_accounts($conn);
$typeLabels = ['main'=>'رئيسية','branch'=>'فرعية','agent'=>'مندوب'];
$accountNames = [];
foreach ($accounts as $account) $accountNames[(string)$account['account_key']] = (string)$account['account_name'];

$sql = "SELECT e.id,e.amount,DATE(COALESCE(e.spent_at,e.expense_date)) spent_day,e.note,e.reference,
  COALESCE(t.name,NULLIF(e.category,''),'غير مصنف') type_name,e.expense_type_id,
  COALESCE(NULLIF(e.collection_account_key,''),'MAIN') account_key,
  COALESCE(NULLIF(e.collection_source_name,''),a.account_name,'النسخة الرئيسية') account_name,
  COALESCE(e.expense_status,'POSTED') expense_status,e.created_at,e.reversed_at
  FROM expenses e LEFT JOIN expense_types t ON t.id=e.expense_type_id
  LEFT JOIN collection_accounts a ON BINARY a.account_key=BINARY COALESCE(NULLIF(e.collection_account_key,''),'MAIN')
  WHERE DATE(COALESCE(e.spent_at,e.expense_date)) BETWEEN ? AND ?
    AND (?=0 OR e.expense_type_id=?)
    AND (?='all' OR COALESCE(NULLIF(e.collection_account_key,''),'MAIN')=?)
    AND (?='ALL' OR COALESCE(e.expense_status,'POSTED')=?)
  ORDER BY spent_day DESC,e.id DESC LIMIT 2000";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssiissss', $from,$to,$typeId,$typeId,$accountFilter,$accountFilter,$statusFilter,$statusFilter);
$stmt->execute();
$rs = $stmt->get_result();
$entries = [];
while ($rs && ($row = $rs->fetch_assoc())) $entries[] = $row;
$stmt->close();

$summarySql = "SELECT COALESCE(t.name,NULLIF(e.category,''),'غير مصنف') type_name,COUNT(*) entry_count,
  COALESCE(SUM(e.amount),0) total,COALESCE(AVG(e.amount),0) average
  FROM expenses e LEFT JOIN expense_types t ON t.id=e.expense_type_id
  WHERE DATE(COALESCE(e.spent_at,e.expense_date)) BETWEEN ? AND ?
    AND COALESCE(e.expense_status,'POSTED')='POSTED'
    AND (?=0 OR e.expense_type_id=?)
    AND (?='all' OR COALESCE(NULLIF(e.collection_account_key,''),'MAIN')=?)
  GROUP BY type_name ORDER BY total DESC";
$stmt = $conn->prepare($summarySql);
$stmt->bind_param('ssiiss', $from,$to,$typeId,$typeId,$accountFilter,$accountFilter);
$stmt->execute();$rs=$stmt->get_result();$byType=[];
while ($rs && ($row=$rs->fetch_assoc())) $byType[]=$row;
$stmt->close();
$postedTotal = array_sum(array_map(static fn($row)=>(float)$row['total'],$byType));
$postedCount = array_sum(array_map(static fn($row)=>(int)$row['entry_count'],$byType));
$largestType = $byType[0]['type_name'] ?? '—';

include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
$finance_active = 'expenses';
$finance_group = 'movement';
?>
<div class="content-wrapper ua-extracted-page fin-expenses"><section class="content"><div class="container-fluid">
  <?php include __DIR__ . '/finance_tabs.php'; ?>

  <header class="fex-hero">
    <div><span>Outgoing payments</span><h1>المدفوعات الخارجة</h1><p>خصم موثّق من صندوق محدد، وتصنيفات مرنة تتكوّن من بياناتك وتدخل مباشرة في التقارير والمحصّلات.</p></div>
    <div class="fex-hero-actions"><a href="finance_daily_balances.php"><i class="fa fa-archive"></i> أرصدة الصناديق</a><a href="finance_reports.php"><i class="fa fa-line-chart"></i> الملخص المحاسبي</a></div>
  </header>

  <?php if ($msg): ?><div class="fex-alert is-success"><i class="fa fa-check-circle"></i><span><?= h($msg) ?></span></div><?php endif; ?>
  <?php if ($err): ?><div class="fex-alert is-danger"><i class="fa fa-exclamation-triangle"></i><span><?= h($err) ?></span></div><?php endif; ?>

  <section class="fex-entry-panel">
    <header><div><span>New payment</span><h2>تسجيل مدفوعات خارجة</h2></div><small>يُنشأ النوع تلقائياً عند استخدامه أول مرة</small></header>
    <form method="post" autocomplete="off" data-ua-android-native-layout>
      <?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?>
      <input type="hidden" name="action" value="add_expense">
      <label class="fex-field"><span>الصندوق الذي سيُخصم منه</span><select name="account_key" required><option value="">اختر الصندوق</option><?php foreach($accounts as $account): ?><option value="<?= h($account['account_key']) ?>"><?= h($account['account_name']) ?> · <?= h($typeLabels[$account['account_type']] ?? $account['account_type']) ?> · الرصيد <?= number_format((float)$account['balance'],2) ?></option><?php endforeach; ?></select></label>
      <label class="fex-field"><span>نوع المصروف</span><input name="type_name" list="expense-types" maxlength="120" placeholder="اكتب نوع المصروف" required><datalist id="expense-types"><?php foreach($types as $type): ?><option value="<?= h($type['name']) ?>"><?php endforeach; ?></datalist></label>
      <label class="fex-field"><span>القيمة</span><input type="number" name="amount" min="0.01" step="0.01" inputmode="decimal" required></label>
      <label class="fex-field"><span>التاريخ</span><input type="date" name="spent_at" value="<?= h(date('Y-m-d')) ?>" required></label>
      <label class="fex-field"><span>المرجع</span><input name="reference" maxlength="120" placeholder="رقم سند أو مرجع اختياري"></label>
      <label class="fex-field fex-field--wide"><span>البيان</span><input name="note" maxlength="255" placeholder="تفاصيل إضافية اختيارية"></label>
      <button class="fex-submit" type="submit"><i class="fa fa-check"></i><span>تثبيت القيد وخصم المبلغ</span></button>
    </form>
  </section>

  <form class="fex-filter" method="get">
    <label><span>من</span><input type="date" name="from" value="<?= h($from) ?>"></label>
    <label><span>إلى</span><input type="date" name="to" value="<?= h($to) ?>"></label>
    <label><span>نوع المصروف</span><select name="type_id"><option value="0">جميع الأنواع</option><?php foreach($types as $type): ?><option value="<?= (int)$type['id'] ?>" <?= $typeId===(int)$type['id']?'selected':'' ?>><?= h($type['name']) ?></option><?php endforeach; ?></select></label>
    <label><span>الصندوق</span><select name="account"><option value="all">جميع الصناديق</option><?php foreach($accounts as $account): ?><option value="<?= h($account['account_key']) ?>" <?= $accountFilter===$account['account_key']?'selected':'' ?>><?= h($account['account_name']) ?></option><?php endforeach; ?></select></label>
    <label><span>حالة القيد</span><select name="status"><option value="POSTED" <?= $statusFilter==='POSTED'?'selected':'' ?>>مثبت</option><option value="REVERSED" <?= $statusFilter==='REVERSED'?'selected':'' ?>>معكوس</option><option value="ALL" <?= $statusFilter==='ALL'?'selected':'' ?>>الكل</option></select></label>
    <button><i class="fa fa-filter"></i> تطبيق</button><a href="finance_expenses.php">هذا الشهر</a>
  </form>

  <section class="fex-kpis">
    <article><i class="fa fa-arrow-circle-up"></i><span>إجمالي المدفوعات المثبتة</span><strong dir="ltr"><?= number_format($postedTotal,2) ?></strong><small><?= h($from) ?> — <?= h($to) ?></small></article>
    <article><i class="fa fa-list-ol"></i><span>عدد القيود</span><strong><?= (int)$postedCount ?></strong><small>بعد تطبيق الفلاتر</small></article>
    <article><i class="fa fa-tags"></i><span>الأنواع المستخدمة</span><strong><?= count($byType) ?></strong><small>تُستخرج من القيود المسجلة</small></article>
    <article><i class="fa fa-bar-chart"></i><span>أعلى نوع إنفاقاً</span><strong class="is-text"><?= h($largestType) ?></strong><small><?= $byType ? number_format((float)$byType[0]['total'],2) : '0.00' ?></small></article>
  </section>

  <div class="fex-grid">
    <section class="fex-panel fex-panel--types"><header><div><span>Expense analysis</span><h2>تحليل الإنفاق حسب النوع</h2></div><b><?= count($byType) ?></b></header><div class="fex-table-wrap"><table><thead><tr><th>نوع المصروف</th><th>العمليات</th><th>المتوسط</th><th>الإجمالي</th><th>النسبة</th></tr></thead><tbody><?php foreach($byType as $row): $share=$postedTotal>0?(float)$row['total']/$postedTotal*100:0; ?><tr><td><strong><?= h($row['type_name']) ?></strong></td><td><?= (int)$row['entry_count'] ?></td><td dir="ltr"><?= number_format((float)$row['average'],2) ?></td><td dir="ltr"><b><?= number_format((float)$row['total'],2) ?></b></td><td><div class="fex-share"><i style="width:<?= number_format($share,2,'.','') ?>%"></i><span><?= number_format($share,1) ?>%</span></div></td></tr><?php endforeach; ?><?php if(!$byType): ?><tr><td colspan="5" class="fex-empty">لا توجد مدفوعات مثبتة ضمن الفترة المحددة.</td></tr><?php endif; ?></tbody></table></div></section>

    <section class="fex-panel fex-panel--ledger"><header><div><span>Audit ledger</span><h2>سجل المدفوعات</h2></div><b><?= count($entries) ?></b></header><div class="fex-table-wrap"><table><thead><tr><th>#</th><th>التاريخ</th><th>النوع</th><th>الصندوق</th><th>القيمة</th><th>المرجع والبيان</th><th>الحالة</th><th>الإجراء</th></tr></thead><tbody><?php foreach($entries as $row): $posted=strtoupper((string)$row['expense_status'])==='POSTED'; ?><tr class="<?= $posted?'':'is-reversed' ?>"><td><?= (int)$row['id'] ?></td><td dir="ltr"><?= h($row['spent_day']) ?></td><td><strong><?= h($row['type_name']) ?></strong></td><td><?= h($row['account_name']) ?><small dir="ltr"><?= h($row['account_key']) ?></small></td><td dir="ltr"><b><?= number_format((float)$row['amount'],2) ?></b></td><td><?= h($row['reference'] ?: '—') ?><small><?= h($row['note'] ?: 'دون بيان') ?></small></td><td><span class="fex-status <?= $posted?'is-posted':'is-reversed' ?>"><?= $posted?'مثبت':'معكوس' ?></span></td><td><?php if($posted): ?><form method="post" onsubmit="return confirm('عكس هذا القيد وإعادة قيمته إلى الصندوق؟ سيبقى القيد محفوظاً في سجل التدقيق.');"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="action" value="reverse_expense"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><button class="fex-reverse" title="عكس القيد"><i class="fa fa-undo"></i><span>عكس</span></button></form><?php else: ?><span class="fex-muted">—</span><?php endif; ?></td></tr><?php endforeach; ?><?php if(!$entries): ?><tr><td colspan="8" class="fex-empty">لا توجد قيود مطابقة للفلاتر.</td></tr><?php endif; ?></tbody></table></div></section>
  </div>
</div></section></div>
<?php include __DIR__ . '/footer.php'; ?>
