<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/finance_payment_lib.php';

ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) { http_response_code(500); exit('Database connection error'); }
require_login('login.php');
if (function_exists('require_perm')) require_perm('can_pay_invoices');
finance_ensure_payments_table($conn);

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$subscriber = null;
if ($id > 0) {
  $result = @$conn->query("SELECT id,full_name,phone,ppp_username FROM subscribers WHERE id={$id} AND COALESCE(is_deleted,0)=0 LIMIT 1");
  $subscriber = $result ? $result->fetch_assoc() : null;
}
$error = $subscriber ? '' : 'المشترك غير موجود.';
$success = '';
if (empty($_SESSION['subscriber_credit_csrf'])) $_SESSION['subscriber_credit_csrf'] = bin2hex(random_bytes(24));
$csrf = (string)$_SESSION['subscriber_credit_csrf'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $subscriber) {
  if (!hash_equals($csrf, (string)($_POST['csrf_token'] ?? ''))) {
    $error = 'انتهت صلاحية الطلب. حدّث الصفحة ثم أعد المحاولة.';
  } else {
    $amount = round((float)($_POST['amount'] ?? 0), 2);
    $method = trim((string)($_POST['method'] ?? 'نقدي'));
    $note = trim((string)($_POST['note'] ?? 'دفعة مقدمة للمشترك'));
    $result = finance_add_subscriber_credit($conn, $id, $amount, [
      'method' => $method,
      'note' => $note,
      'channel' => 'desktop',
    ]);
    if (empty($result['ok'])) {
      $error = (string)($result['error'] ?? 'تعذر تسجيل الدفعة المقدمة.');
    } else {
      $success = 'تم تسجيل الدفعة، وتوزيع ' . number_format((float)($result['allocated'] ?? 0), 2)
        . ' على الفواتير. الرصيد المتبقي: ' . number_format((float)($result['balance'] ?? 0), 2) . '.';
    }
  }
}

$balance = $subscriber ? billing_credit_balance($conn, $id) : 0.0;
$outstanding = $subscriber ? billing_subscriber_outstanding($conn, $id) : 0.0;
$history = [];
if ($subscriber) {
  $rows = @$conn->query("SELECT direction,entry_type,amount,balance_after,note,created_at
    FROM subscriber_credit_ledger WHERE subscriber_id={$id} ORDER BY id DESC LIMIT 30");
  if ($rows) while ($row = $rows->fetch_assoc()) $history[] = $row;
}

$page_title = 'الرصيد المقدم للمشترك';
$UA_FORCE_DESIGN_V2 = true;
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header"><div class="container-fluid"><h1 class="mb-0">الرصيد المقدم</h1></div></section>
  <section class="content"><div class="container-fluid">
    <?php if ($error): ?><div class="alert alert-danger"><?= h($error) ?></div><?php endif; ?>
    <?php if ($success): ?><div class="alert alert-success"><?= h($success) ?></div><?php endif; ?>
    <?php if ($subscriber): ?>
      <div class="card"><div class="card-body">
        <div class="row g-3 mb-3">
          <div class="col-md-4"><strong>المشترك:</strong> <?= h($subscriber['full_name'] ?? '-') ?></div>
          <div class="col-md-4"><strong>الرصيد المتاح:</strong> <?= number_format($balance, 2) ?></div>
          <div class="col-md-4"><strong>إجمالي المستحق:</strong> <?= number_format($outstanding, 2) ?></div>
        </div>
        <form method="post">
          <input type="hidden" name="id" value="<?= $id ?>">
          <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
          <div class="row g-3 align-items-end">
            <div class="col-md-3"><label class="form-label">المبلغ</label><input class="form-control" type="number" name="amount" min="0.01" step="0.01" required></div>
            <div class="col-md-3"><label class="form-label">طريقة الدفع</label><select class="form-control" name="method"><option>نقدي</option><option>تحويل</option><option>بطاقة</option></select></div>
            <div class="col-md-4"><label class="form-label">ملاحظة</label><input class="form-control" name="note" value="دفعة مقدمة للمشترك"></div>
            <div class="col-md-2"><button class="btn btn-success w-100" type="submit"><i class="fa fa-plus-circle"></i> إضافة الرصيد</button></div>
          </div>
        </form>
      </div></div>
      <div class="card mt-3"><div class="card-body">
        <h5>حركة الرصيد</h5>
        <div class="table-responsive"><table class="table table-striped table-bordered mb-0">
          <thead><tr><th>التاريخ</th><th>الحركة</th><th>المبلغ</th><th>الرصيد بعدها</th><th>الملاحظة</th></tr></thead>
          <tbody>
          <?php if (!$history): ?><tr><td colspan="5" class="text-center">لا توجد حركات بعد.</td></tr><?php endif; ?>
          <?php foreach ($history as $row): ?><tr>
            <td><?= h($row['created_at'] ?? '') ?></td>
            <td><?= ($row['direction'] ?? '') === 'CREDIT' ? 'إضافة' : 'خصم آلي' ?></td>
            <td><?= number_format((float)($row['amount'] ?? 0), 2) ?></td>
            <td><?= number_format((float)($row['balance_after'] ?? 0), 2) ?></td>
            <td><?= h($row['note'] ?? '') ?></td>
          </tr><?php endforeach; ?>
          </tbody>
        </table></div>
      </div></div>
    <?php endif; ?>
  </div></section>
</div>
<?php include __DIR__ . '/footer.php'; ?>
