<?php
$page_title = 'الدفعات | Payments';
require_once __DIR__ . '/finance_bootstrap.php';
require_once __DIR__ . '/finance_payment_lib.php';

require_login('login.php');
if (function_exists('require_perm')) require_perm('can_pay_invoices');
billing_backfill_collection_ledger($conn);

$msg = '';
$err = '';
if (empty($_SESSION['finance_payments_csrf'])) $_SESSION['finance_payments_csrf'] = bin2hex(random_bytes(24));
$csrf = (string)$_SESSION['finance_payments_csrf'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_payment') {
  if (!hash_equals($csrf, (string)($_POST['csrf_token'] ?? ''))) {
    $err = 'انتهت صلاحية الطلب. حدّث الصفحة ثم أعد المحاولة.';
  }
  $invoice_id = (int)($_POST['invoice_id'] ?? 0);
  $subscriber_id = (int)($_POST['subscriber_id'] ?? 0);
  $payment_kind = strtolower(trim((string)($_POST['payment_kind'] ?? 'invoice')));
  $amount = (float)($_POST['amount'] ?? 0);
  $method = trim($_POST['method'] ?? 'cash');
  $ref = trim($_POST['reference'] ?? '');
  $note = trim($_POST['note'] ?? '');

  if ($err === '' && $amount <= 0) {
    $err = 'المبلغ غير صحيح.';
  } elseif ($err === '' && $payment_kind === 'invoice' && $invoice_id <= 0) {
    $err = 'اختر رقم فاتورة صالحاً.';
  } elseif ($err === '' && $payment_kind === 'advance' && $subscriber_id <= 0) {
    $err = 'اختر المشترك لإضافة الدفعة المقدمة.';
  } else {
    // Respect month closing (payment date is NOW())
    $y = (int)date('Y');
    $m = (int)date('n');
    if (finance_is_month_closed($conn, $y, $m)) {
      $err = 'هذا الشهر مُغلق محاسبيًا. لا يمكن إضافة دفعات ضمن شهر مُغلق.';
    }

    // Respect daily cashbox closing
    if ($err === '' && finance_is_day_closed($conn, date('Y-m-d'))) {
      $err = 'هذا اليوم مُقفل في الصندوق. لا يمكن إضافة دفعات بتاريخ اليوم بعد الإقفال.';
    }

    if ($err === '') {
      if ($payment_kind === 'advance') {
        $result = finance_add_subscriber_credit($conn, $subscriber_id, $amount, [
          'method'=>$method,
          'reference'=>$ref,
          'note'=>$note !== '' ? $note : 'دفعة مقدمة للمشترك',
          'channel'=>'desktop',
        ]);
      } else {
        $result = finance_pay_invoice($conn, $invoice_id, [
          'amount'=>$amount,
          'method'=>$method,
          'reference'=>$ref,
          'note'=>$note,
          'channel'=>'desktop',
        ]);
      }
      if (!($result['ok'] ?? false)) {
        $err = (string)($result['error'] ?? 'فشل إضافة الدفعة.');
      } else {
        if (!empty($result['warning'])) $_SESSION['flash_warning'] = (string)$result['warning'];
        $redirect = 'finance_payments.php?added=1';
        if ($payment_kind === 'invoice' && !empty($result['auto_print'])) $redirect .= '&auto_print_invoice=' . $invoice_id;
        header('Location: ' . $redirect);
        exit;
      }
    }
  }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_payment') {
  if (!hash_equals($csrf, (string)($_POST['csrf_token'] ?? ''))) {
    $err = 'انتهت صلاحية الطلب. حدّث الصفحة ثم أعد المحاولة.';
  }
  $id = (int)($_POST['id'] ?? 0);
  if ($id > 0) {
    $d = null;
    $rsInv = $conn->query("SELECT COALESCE(paid_at, created_at) AS d FROM payments WHERE id={$id} LIMIT 1");
    if ($rsInv && ($rr=$rsInv->fetch_assoc())) $d = $rr['d'];

    // Prevent delete in closed month (by paid_at/created_at)
    if ($d) {
      $ts = strtotime($d);
      if ($ts !== false) {
        $yy = (int)date('Y', $ts);
        $mm = (int)date('n', $ts);
        if (finance_is_month_closed($conn, $yy, $mm)) {
          $err = 'هذا الشهر مُغلق محاسبيًا. لا يمكن حذف دفعة ضمن شهر مُغلق.';
        }
      }
    }

    if ($err === '') {
      $result = finance_delete_payment_row($conn, $id);
      if (($result['ok'] ?? false)) {
        header('Location: finance_payments.php?deleted=1');
        exit;
      } else {
        $err = (string)($result['error'] ?? 'فشل حذف الدفعة.');
      }
    }
  }
}



$rows = [];

// Optional filters for deep-links (e.g. from vouchers)
$filter_payment_id = (int)($_GET['payment_id'] ?? ($_GET['id'] ?? 0));
$filter_ref = trim((string)($_GET['ref'] ?? ($_GET['reference'] ?? '')));
$filter_invoice_id = (int)($_GET['invoice_id'] ?? 0);

$where = ["COALESCE(payment_status,'POSTED')='POSTED'"];
if ($filter_payment_id > 0) $where[] = 'id=' . $filter_payment_id;
if ($filter_invoice_id > 0) $where[] = 'invoice_id=' . $filter_invoice_id;
if ($filter_ref !== '') $where[] = "(reference='".$conn->real_escape_string($filter_ref)."' OR ref='".$conn->real_escape_string($filter_ref)."')";

$sql = "SELECT id, invoice_id, subscriber_id, amount, method, reference, note, created_by, payment_status,
  collection_source_type,collection_source_ref,collection_source_name,collection_channel,created_at FROM payments";
if ($where) $sql .= " WHERE " . implode(' AND ', $where);
$sql .= " ORDER BY id DESC LIMIT 200";

$res = $conn->query($sql);
if ($res) {
  while ($r = $res->fetch_assoc()) $rows[] = $r;
}
$collectionBalances = billing_collection_balances($conn);
$subscriberOptions = [];
$subscriberResult = @$conn->query("SELECT id,full_name,ppp_username FROM subscribers WHERE COALESCE(is_deleted,0)=0 ORDER BY full_name,id LIMIT 3000");
if ($subscriberResult) while ($subscriberRow = $subscriberResult->fetch_assoc()) $subscriberOptions[] = $subscriberRow;

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidFinancePayments = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidFinancePayments) $UA_PAGE_CSS = ['assets/css/android_finance_payments.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

$finance_active = 'payments';
$finance_group = 'movement';
if(isset($_GET['added'])) $msg='تمت إضافة الدفعة بنجاح.';
if(isset($_GET['deleted'])) $msg='تم إلغاء الدفعة.';
$flash_warning = (string)($_SESSION['flash_warning'] ?? '');
unset($_SESSION['flash_warning']);
if ($uaAndroidFinancePayments) {
  require __DIR__ . '/android_finance_payments.php';
  include __DIR__ . '/footer.php';
  return;
}
?>
<div class="content-wrapper ua-extracted-page ua-subscriber-child-page ua-sub-child-finance-payments">
  <section class="content">
    <div class="ua-page-v2">
      <header class="ua-page-head">
        <div class="ua-page-title">
          <h1>الدفعات | Payments</h1>
          <p>إضافة الدفعات ومراجعة آخر الحركات المالية المرتبطة بالفواتير.</p>
        </div>
        <?php if ($filter_payment_id || $filter_ref !== '' || $filter_invoice_id): ?>
          <div class="ua-page-actions">
            <span class="badge badge-info">عرض مُفلتر</span>
            <?php if ($filter_payment_id): ?><span class="badge badge-secondary">Payment #<?= (int)$filter_payment_id ?></span><?php endif; ?>
            <?php if ($filter_invoice_id): ?><span class="badge badge-secondary">Invoice #<?= (int)$filter_invoice_id ?></span><?php endif; ?>
            <?php if ($filter_ref !== ''): ?><span class="badge badge-secondary">Ref: <?= h($filter_ref) ?></span><?php endif; ?>
            <a class="btn btn-sm btn-outline-secondary" href="finance_payments.php">إلغاء الفلترة</a>
          </div>
        <?php endif; ?>
      </header>
      
      <?php include __DIR__ . '/finance_tabs.php'; ?>
<?php
if(isset($_GET['added'])) $msg='تمت إضافة الدفعة بنجاح.';
if(isset($_GET['deleted'])) $msg='تم إلغاء الدفعة.';
$flash_warning = (string)($_SESSION['flash_warning'] ?? '');
unset($_SESSION['flash_warning']);
?>
<?php if ($msg): ?>
        <div class="ua-alert alert-success"><?= h($msg) ?></div>
      <?php endif; ?>
      <?php if ($flash_warning): ?>
        <div class="ua-alert alert-warning"><?= h($flash_warning) ?></div>
      <?php endif; ?>
      <?php if ($err): ?>
        <div class="ua-alert alert-danger"><?= h($err) ?></div>
      <?php endif; ?>

      <section class="ua-panel-v2">
        <div class="ua-panel-head"><h3 class="card-title">أرصدة التحصيل حسب النسخة</h3></div>
        <div class="ua-panel-body">
          <div class="row g-3">
            <?php foreach ($collectionBalances as $account): ?>
              <div class="col-md-4 col-lg-3">
                <div class="border rounded p-3 h-100">
                  <div class="text-muted"><?= h($account['account_type'] === 'main' ? 'الرصيد الرئيسي' : ($account['account_type'] === 'agent' ? 'رصيد المعتمد' : 'رصيد النسخة الفرعية')) ?></div>
                  <strong><?= h($account['account_name'] ?? $account['account_key']) ?></strong>
                  <div class="h4 mt-2 mb-0"><?= number_format((float)($account['balance'] ?? 0), 2) ?></div>
                </div>
              </div>
            <?php endforeach; ?>
            <?php if (!$collectionBalances): ?><div class="col-12 text-muted">تظهر الحسابات هنا عند تسجيل أول دفعة.</div><?php endif; ?>
          </div>
        </div>
      </section>

      <section class="ua-panel-v2">
        <div class="ua-panel-head"><h3 class="card-title">إضافة دفعة | Add Payment</h3></div>
        <div class="ua-panel-body">
          <form method="post">
            <input type="hidden" name="action" value="add_payment">
            <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
            <div class="ua-form-grid ua-payment-form-grid">
              <div class="ua-payment-field">
                <label>نوع الدفعة</label>
                <select class="form-control" name="payment_kind" id="paymentKind"><option value="invoice">تسديد فاتورة</option><option value="advance">دفعة مقدمة</option></select>
              </div>
              <div class="ua-payment-field" id="invoiceField">
                <label>رقم الفاتورة</label>
                <input class="form-control" name="invoice_id" type="number" min="1">
              </div>
              <div class="ua-payment-field ua-payment-field-wide" id="subscriberField" hidden>
                <label>المشترك</label>
                <select class="form-control" name="subscriber_id"><option value="0">اختر المشترك</option><?php foreach ($subscriberOptions as $subscriberOption): ?><option value="<?= (int)$subscriberOption['id'] ?>">#<?= (int)$subscriberOption['id'] ?> — <?= h($subscriberOption['full_name'] ?: $subscriberOption['ppp_username']) ?></option><?php endforeach; ?></select>
              </div>
              <div class="ua-payment-field">
                <label>المبلغ</label>
                <input class="form-control" name="amount" type="number" step="0.01" min="0" required>
              </div>
              <div class="ua-payment-field">
                <label>طريقة الدفع</label>
                <select class="form-control" name="method">
                  <option value="cash">نقدي</option>
                  <option value="transfer">تحويل</option>
                  <option value="card">بطاقة</option>
                  <option value="other">أخرى</option>
                </select>
              </div>
              <div class="ua-payment-field ua-payment-field-wide">
                <label>المرجع</label>
                <input class="form-control" name="reference" placeholder="#">
              </div>
              <div class="ua-payment-field ua-payment-field-wide">
                <label>ملاحظة</label>
                <input class="form-control" name="note" placeholder="...">
              </div>
            </div>
            <div class="ua-form-actions">
              <button class="btn btn-primary">حفظ | Save</button>
            </div>
          </form>
        </div>
      </section>

      <section class="ua-panel-v2">
        <div class="ua-panel-head"><h3 class="card-title">آخر الدفعات | Recent Payments</h3></div>
        <div class="ua-panel-body">
          <div class="ua-table-wrap">
          <table class="ua-table">
            <thead>
              <tr>
                <th>#</th><th>الفاتورة/المشترك</th><th>Amount</th><th>Method</th><th>المصدر</th><th>Reference</th><th>By</th><th>Date</th><th></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($rows as $r): ?>
                <tr>
                  <td><?= (int)$r['id'] ?></td>
                  <td><?= (int)$r['invoice_id'] > 0 ? ('فاتورة #' . (int)$r['invoice_id']) : ('مشترك #' . (int)$r['subscriber_id']) ?></td>
                  <td><?= h($r['amount']) ?></td>
                  <td><?= h($r['method']) ?></td>
                  <td><?= h($r['collection_source_name'] ?: ($r['collection_source_type'] ?? '-')) ?></td>
                  <td><?= h($r['reference']) ?></td>
                  <td><?= h($r['created_by']) ?></td>
                  <td><?= h($r['created_at']) ?></td>
                  <td>
                    <form class="ua-u-inline" method="post" onsubmit="return confirm('إلغاء الدفعة؟');">
                      <input type="hidden" name="action" value="delete_payment">
                      <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                      <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                      <button class="btn btn-danger btn-sm ua-icon-btn" title="إلغاء" aria-label="إلغاء"><i class="fa fa-ban"></i></button>
                    </form>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (empty($rows)): ?>
                <tr><td colspan="9" class="text-center text-muted">لا يوجد بيانات</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
          </div>
        </div>
      </section>

    </div>
  </section>
</div>
<script>
(function(){
  const kind=document.getElementById('paymentKind');
  const invoice=document.getElementById('invoiceField');
  const subscriber=document.getElementById('subscriberField');
  function sync(){const advance=kind&&kind.value==='advance';if(invoice)invoice.hidden=advance;if(subscriber)subscriber.hidden=!advance}
  if(kind){kind.addEventListener('change',sync);sync()}
})();
</script>
<?php finance_render_auto_print($conn, (int)($_GET['auto_print_invoice'] ?? 0)); ?>
<?php include __DIR__ . '/footer.php'; ?>
