<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap_public.php';
requireLogin();

$pdo = getPDO();

function fmtDateTime(?string $dt): string
{
    $dt = trim((string)$dt);
    return $dt !== '' ? $dt : '—';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();

    $id = (int)($_POST['id'] ?? 0);
    $action = (string)($_POST['action'] ?? '');

    if ($id > 0 && ($action === 'approve' || $action === 'reject')) {
        if ($action === 'approve') {
            $code = trim((string)($_POST['access_code'] ?? ''));

            // ✅ 6 digits by default
            if ($code === '') {
                $code = (string)random_int(100000, 999999);
            } else {
                // keep digits only if admin typed
                $code = preg_replace('/\D+/', '', $code) ?: $code;
            }

            $expiresHours = (int)($_POST['expires_hours'] ?? 24);
            if ($expiresHours <= 0) $expiresHours = 24;
            if ($expiresHours > 24 * 30) $expiresHours = 24 * 30; // max 30 days

            $st = $pdo->prepare("
                UPDATE sponsor_access_requests
                SET status='approved',
                    access_code=?,
                    code_expires_at=DATE_ADD(NOW(), INTERVAL ? HOUR),
                    approved_by_admin_id=?,
                    approved_at=NOW()
                WHERE id=?
            ");
            $st->execute([$code, $expiresHours, (int)currentAdmin()['id'], $id]);

            flashSuccess("تم اعتماد الطلب بنجاح. الكود: {$code} — انسخه وأرسله واتساب لمقدم الطلب.");
        } else {
            $st = $pdo->prepare("
                UPDATE sponsor_access_requests
                SET status='rejected',
                    rejected_by_admin_id=?,
                    rejected_at=NOW()
                WHERE id=?
            ");
            $st->execute([(int)currentAdmin()['id'], $id]);
            flashSuccess("تم رفض الطلب.");
        }
    }

    header('Location: admin_requests.php');
    exit;
}

$reqs = $pdo->query("
    SELECT r.*, b.full_name, b.file_number
    FROM sponsor_access_requests r
    JOIN beneficiaries b ON b.id = r.beneficiary_id
    WHERE b.beneficiary_type_id = 2
    ORDER BY r.id DESC
    LIMIT 200
")->fetchAll();

$flashHtml = renderFlash();
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <title>إدارة طلبات كفالة اليتيم</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="<?= ORPHAN_PUBLIC_BASE ?>/assets/style.css">
  <style>
    body{background:#f7f9fc}
    .topbar{
      display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;
      margin-bottom:10px
    }
    .title{
      margin:0;color:#0f2f5f;font-size:22px
    }
    .sub{margin:0;color:#5b6b7a;line-height:1.7}
    .table-wrap{overflow:auto;border-radius:16px;border:1px solid #e8eef7;background:#fff}
    table{width:100%;border-collapse:collapse;min-width:980px}
    th,td{padding:10px 10px;border-bottom:1px solid #eef2f7;text-align:right;vertical-align:top}
    th{background:#fbfdff;color:#0f2f5f;font-weight:900;position:sticky;top:0}
    tr:hover td{background:#fcfeff}
    .status{
      display:inline-flex;align-items:center;gap:6px;
      padding:4px 10px;border-radius:999px;font-weight:900;font-size:13px;border:1px solid transparent
    }
    .st-pending{background:#fff7ed;color:#9a3412;border-color:#fed7aa}
    .st-approved{background:#ecfdf5;color:#065f46;border-color:#a7f3d0}
    .st-rejected{background:#fef2f2;color:#991b1b;border-color:#fecaca}
    .actionsCell{min-width:270px}
    .miniForm{display:grid;gap:6px;margin:0}
    .miniForm input{padding:8px;border-radius:10px;border:1px solid #d8e2f0}
    .miniForm .row{display:grid;grid-template-columns:1fr 120px;gap:6px}
    .btn{cursor:pointer}
    .btn-sm{padding:8px 10px;border-radius:10px;font-weight:900}
    .btn-danger{
      background:#ef4444;color:#fff;border:0
    }
    .btn-ghost{
      background:#fff;border:1px solid #d8e2f0;color:#0f2f5f
    }
    .mutedSmall{color:#6b7280;font-size:12px;line-height:1.6}
    .codeBox{
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
      font-weight:900;
      padding:4px 8px;border-radius:10px;border:1px solid #e5e7eb;background:#fff
    }
  </style>
</head>
<body>
<div class="container">
  <div class="card">

    <div class="topbar">
      <div>
        <h2 class="title">إدارة طلبات كفالة اليتيم</h2>
        <p class="sub">اعتماد الطلبات وإصدار كود (يتم إرساله يدويًا عبر واتساب).</p>
      </div>
      <div class="actions">
        <a class="btn btn-light" href="<?= ORPHAN_PUBLIC_BASE ?>/index.php">واجهة الكفالة</a>
        <a class="btn btn-light" href="/zaka/admin/dashboard.php">لوحة النظام</a>
      </div>
    </div>

    <?= $flashHtml ?>

    <div class="table-wrap">
      <table>
        <tr>
          <th>#</th>
          <th>اليتيم</th>
          <th>رقم الملف</th>
          <th>اسم مقدم الطلب</th>
          <th>الجوال</th>
          <th>الحالة</th>
          <th>الكود</th>
          <th>انتهاء الكود</th>
          <th class="actionsCell">إجراءات</th>
        </tr>

        <?php foreach ($reqs as $r): ?>
          <?php
            $st = (string)$r['status'];
            $stCls = $st === 'approved' ? 'st-approved' : ($st === 'rejected' ? 'st-rejected' : 'st-pending');
          ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><?= e((string)$r['full_name']) ?></td>
            <td><?= (int)$r['file_number'] ?></td>
            <td><?= e((string)$r['requester_name']) ?></td>
            <td><?= e((string)$r['requester_phone']) ?></td>
            <td><span class="status <?= $stCls ?>"><?= e($st) ?></span></td>
            <td>
              <?php if (!empty($r['access_code'])): ?>
                <span class="codeBox"><?= e((string)$r['access_code']) ?></span>
              <?php else: ?>
                —
              <?php endif; ?>
            </td>
            <td><?= e(fmtDateTime($r['code_expires_at'] ?? null)) ?></td>
            <td class="actionsCell">
              <?php if ($st === 'pending'): ?>
                <form method="post" class="miniForm">
                  <?= csrfField() ?>
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <input type="hidden" name="action" value="approve">

                  <div class="row">
                    <input type="text" name="access_code" placeholder="اتركه فارغًا لتوليد كود تلقائي (6 أرقام)">
                    <input type="number" name="expires_hours" value="24" min="1" max="<?= 24*30 ?>">
                  </div>

                  <button class="btn btn-sm" type="submit">اعتماد وإظهار الكود</button>
                  <div class="mutedSmall">بعد الاعتماد: انسخ الكود وأرسله واتساب لمقدم الطلب.</div>
                </form>

                <form method="post" style="margin-top:8px">
                  <?= csrfField() ?>
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <input type="hidden" name="action" value="reject">
                  <button class="btn btn-sm btn-danger" type="submit" onclick="return confirm('رفض الطلب؟')">رفض الطلب</button>
                </form>
              <?php else: ?>
                <a class="btn btn-sm btn-ghost" target="_blank"
                   href="<?= ORPHAN_PUBLIC_BASE ?>/public/verify.php">صفحة التحقق</a>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>

        <?php if (!$reqs): ?>
          <tr><td colspan="9" class="mutedSmall">لا توجد طلبات.</td></tr>
        <?php endif; ?>
      </table>
    </div>

  </div>
</div>
</body>
</html>