<?php
$cfg = is_array($billing_request_config ?? null) ? $billing_request_config : [];
$actionType = strtoupper((string)($cfg['action_type'] ?? ''));
$page_title = (string)($cfg['page_title'] ?? 'طلبات دورة الفوترة');
$pretty = (string)($cfg['action_label'] ?? 'التنفيذ');
$buttonClass = (string)($cfg['button_class'] ?? 'btn-primary');
$finance_active = (string)($cfg['finance_active'] ?? '');
$finance_group = 'billing';
$UA_FORCE_DESIGN_V2 = true;

require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/billing_cycle_lib.php';

ensure_db(true);
$conn = $GLOBALS['conn'] ?? ($conn ?? null);
if (!($conn instanceof mysqli)) {
  echo "<div class='content-wrapper'><section class='content p-3'><div class='alert alert-danger'>خطأ: اتصال قاعدة البيانات غير جاهز.</div></section></div>";
  require_once __DIR__ . '/footer.php';
  exit;
}
if (function_exists('require_login')) require_login('login.php');
if (!billing_is_super_admin_actor()) {
  http_response_code(403);
  echo "<div class='content-wrapper'><section class='content p-3'><div class='alert alert-danger'>اعتماد هذه العمليات محصور بالسوبر أدمن.</div></section></div>";
  require_once __DIR__ . '/footer.php';
  exit;
}
if (!in_array($actionType, ['REMINDER', 'LIMIT', 'CUT'], true)) {
  http_response_code(422);
  exit('نوع طلب غير صالح');
}

if (empty($_SESSION['billing_request_csrf'])) {
  $_SESSION['billing_request_csrf'] = bin2hex(random_bytes(24));
}
$csrf = (string)$_SESSION['billing_request_csrf'];
$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $submittedCsrf = (string)($_POST['csrf_token'] ?? '');
  if (!hash_equals($csrf, $submittedCsrf)) {
    $flash = ['type' => 'danger', 'msg' => 'انتهت صلاحية الطلب. حدّث الصفحة ثم أعد المحاولة.'];
  } else {
    $ids = isset($_POST['ids']) && is_array($_POST['ids'])
      ? array_values(array_filter(array_map('intval', $_POST['ids']), fn($v) => $v > 0))
      : [];
    $approveAll = !empty($_POST['approve_all']);
    if (!$approveAll && !$ids) {
      $flash = ['type' => 'warning', 'msg' => 'حدد مشتركاً واحداً على الأقل أو استخدم تحديد الكل.'];
    } else {
      $approvedBy = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
      $result = billing_approve_requests($conn, $actionType, $approveAll ? [] : $ids, $approvedBy);
      $flash = [
        'type' => !empty($result['failed']) ? 'warning' : 'success',
        'msg' => 'تم ' . $pretty . ' لـ ' . (int)($result['success'] ?? 0) . ' حالة'
          . (!empty($result['failed']) ? ('، وفشل ' . (int)$result['failed'] . ' حالة') : '') . '.',
      ];
    }
  }
}
$rows = billing_get_pending_requests($conn, $actionType, 1000);
if (!function_exists('billing_request_h')) {
  function billing_request_h($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
  }
}
?>
<style>
.ua-billing-requests-page .ua-billing-requests-card .card-body{display:flex;flex-direction:column;min-height:0}
.ua-billing-requests-page .ua-billing-requests-scroll{max-height:calc(100dvh - 430px);min-height:260px;overflow:auto;border:1px solid rgba(148,163,184,.28);border-radius:10px}
.ua-billing-requests-page .ua-billing-requests-scroll .table-responsive{overflow:visible}
.ua-billing-requests-page .ua-billing-requests-scroll table{margin-bottom:0}
.ua-billing-requests-page .ua-billing-requests-scroll thead th{position:sticky;top:0;z-index:2}
@media (max-height:760px){.ua-billing-requests-page .ua-billing-requests-scroll{max-height:calc(100dvh - 350px);min-height:180px}}
</style>
<div class="content-wrapper ua-extracted-page ua-billing-requests-page">
  <section class="content-header">
    <div class="container-fluid d-flex justify-content-between align-items-center flex-wrap gap-2">
      <h1 class="mb-0"><?= billing_request_h($page_title) ?></h1>
      <a href="dashboard.php" class="btn btn-outline-light"><i class="fa fa-arrow-right"></i> العودة إلى الرئيسية</a>
    </div>
  </section>
  <section class="content">
    <div class="container-fluid">
      <?php include __DIR__ . '/finance_tabs.php'; ?>
      <?php if ($flash): ?>
        <div class="alert alert-<?= billing_request_h($flash['type']) ?>"><?= billing_request_h($flash['msg']) ?></div>
      <?php endif; ?>
      <div class="alert alert-light border ua-u-fw-700">
        لا تُنفّذ هذه المرحلة تلقائياً. تبقى الطلبات معلقة حتى يراجعها السوبر أدمن ويعتمدها.
      </div>
      <div class="card ua-billing-requests-card">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
            <div>
              <div class="ua-u-fw-800">عدد الطلبات الحالية: <?= count($rows) ?></div>
              <div class="ua-u-op-80 ua-u-fs-13">راجع المبالغ والأسماء ثم اعتمد فردياً أو جماعياً.</div>
            </div>
            <div class="d-flex gap-2 flex-wrap">
              <button type="button" class="btn btn-secondary btn-sm" id="checkAllBtn">تحديد الكل</button>
              <button type="button" class="btn btn-outline-secondary btn-sm" id="uncheckAllBtn">إلغاء التحديد</button>
            </div>
          </div>
          <?php if (!$rows): ?>
            <div class="alert alert-info mb-0">لا توجد طلبات معلقة حالياً.</div>
          <?php else: ?>
            <form method="post" id="bulkForm">
              <input type="hidden" name="csrf_token" value="<?= billing_request_h($csrf) ?>">
              <div class="ua-billing-requests-scroll">
                <div class="table-responsive">
                  <table class="table table-bordered table-striped table-hover">
                    <thead>
                      <tr>
                        <th class="ua-u-w-44"><input type="checkbox" id="masterCheck"></th>
                        <th>#</th><th>المشترك</th><th>الهاتف</th><th>اسم PPPoE</th>
                        <th>الدورة</th><th>الاستحقاق</th><th>الأيام</th><th>المتبقي</th><th>السبب</th>
                        <th class="ua-u-w-170">إجراء</th>
                      </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($rows as $row): ?>
                      <tr>
                        <td><input type="checkbox" name="ids[]" value="<?= (int)$row['id'] ?>" class="row-check"></td>
                        <td><?= (int)$row['id'] ?></td>
                        <td><?= billing_request_h($row['full_name'] ?? '-') ?></td>
                        <td><?= billing_request_h($row['phone'] ?? '-') ?></td>
                        <td><?= billing_request_h($row['ppp_username'] ?? '-') ?></td>
                        <td><?= billing_request_h($row['invoice_cycle_label'] ?? '-') ?></td>
                        <td><?= billing_request_h($row['due_date'] ?? '-') ?></td>
                        <td><?= (int)($row['effective_days'] ?? 0) ?></td>
                        <td><?= number_format((float)($row['remaining_amount'] ?? 0), 2) ?></td>
                        <td><?= billing_request_h($row['reason'] ?? '-') ?></td>
                        <td><button type="submit" class="btn btn-sm <?= billing_request_h($buttonClass) ?>" name="ids[]" value="<?= (int)$row['id'] ?>" onclick="return confirm('تأكيد <?= billing_request_h($pretty) ?> لهذا المشترك؟');"><?= billing_request_h($pretty) ?></button></td>
                      </tr>
                    <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
              </div>
              <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mt-3">
                <label class="mb-0 ua-u-fw-700"><input type="checkbox" name="approve_all" value="1"> اعتماد كل الطلبات الظاهرة</label>
                <button type="submit" class="btn <?= billing_request_h($buttonClass) ?>" onclick="return confirm('تأكيد اعتماد الطلبات المحددة؟');">اعتماد المحدد</button>
              </div>
            </form>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </section>
</div>
<script>
(function(){
  const master=document.getElementById('masterCheck');
  const checks=Array.from(document.querySelectorAll('.row-check'));
  const allBtn=document.getElementById('checkAllBtn');
  const noneBtn=document.getElementById('uncheckAllBtn');
  function setAll(value){checks.forEach(ch=>ch.checked=value);if(master)master.checked=value&&checks.length>0}
  if(master)master.addEventListener('change',()=>setAll(master.checked));
  if(allBtn)allBtn.addEventListener('click',()=>setAll(true));
  if(noneBtn)noneBtn.addEventListener('click',()=>setAll(false));
})();
</script>
<?php require_once __DIR__ . '/footer.php'; ?>
