<?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__ . '/settings_store.php';
require_once __DIR__ . '/super_admin_guard.php';

require_login('index.php?login=1');

if (function_exists('ensure_db')) { ensure_db(true); }
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) { http_response_code(500); die('Database connection error'); }

function super_admin_force_logout_page(string $redirect = 'login.php'): void {
  $_SESSION = [];
  if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
      $params['path'] ?? '/',
      $params['domain'] ?? '',
      (bool)($params['secure'] ?? false),
      (bool)($params['httponly'] ?? false)
    );
  }
  if (session_status() === PHP_SESSION_ACTIVE) {
    session_destroy();
  }
  header('Location: ' . $redirect);
  exit;
}

function super_admin_confirm_password_ok(mysqli $conn, string $pass): bool {
  $pass = (string)$pass;
  if ($pass === '') return false;

  $candidates = [];
  foreach (['super_admin_pass_hash', 'super_admin_password_hash', 'super_admin_pass'] as $key) {
    try {
      $v = (string)setting_get($conn, $key, '');
      if ($v !== '') $candidates[] = $v;
    } catch (Throwable $e) {}
  }

  $res = @$conn->query("SELECT password, password_hash FROM admin_users WHERE id=1 LIMIT 1");
  if ($res && $res->num_rows) {
    $row = $res->fetch_assoc();
    foreach (['password_hash', 'password'] as $k) {
      $v = (string)($row[$k] ?? '');
      if ($v !== '') $candidates[] = $v;
    }
  }

  foreach (array_unique($candidates) as $stored) {
    if ($stored === '') continue;
    if (function_exists('verify_any_password') && verify_any_password($pass, $stored)) return true;
    $looksHash = str_starts_with($stored, '$2y$') || str_starts_with($stored, '$2a$') || str_starts_with($stored, '$argon2');
    if ($looksHash && function_exists('password_verify') && password_verify($pass, $stored)) return true;
    if (!$looksHash && hash_equals($stored, $pass)) return true;
  }
  return false;
}

$go = (string)($_GET['go'] ?? ($_POST['go'] ?? ''));
$go = super_admin_sanitize_go($go);
if ($go === '') { http_response_code(400); die('Bad request'); }
$uaAndroidSuperConfirm = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false || str_contains($go, 'ua_android=1');

$error = '';
$max_attempts = 3;
if (!isset($_SESSION['super_admin_fail_count']) || !is_numeric($_SESSION['super_admin_fail_count'])) {
  $_SESSION['super_admin_fail_count'] = 0;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $pass = trim((string)($_POST['password'] ?? ''));

  if (super_admin_confirm_password_ok($conn, $pass)) {
    $_SESSION['super_admin_fail_count'] = 0;
    super_admin_mark_ok($go);
    header('Location: ' . $go);
    exit;
  }

  $_SESSION['super_admin_fail_count'] = (int)($_SESSION['super_admin_fail_count'] ?? 0) + 1;
  if ((int)$_SESSION['super_admin_fail_count'] >= $max_attempts) {
    super_admin_force_logout_page('login.php');
  }

  $remaining = $max_attempts - (int)$_SESSION['super_admin_fail_count'];
  $error = 'كلمة مرور السوبر أدمن غير صحيحة. المحاولات المتبقية: ' . $remaining;
}

$close_to = function_exists('ua_parent_page_url') ? ua_parent_page_url('subscribers.php') : 'subscribers.php';
$goEsc = htmlspecialchars($go, ENT_QUOTES, 'UTF-8');
$closeEsc = htmlspecialchars($close_to, ENT_QUOTES, 'UTF-8');
$errorEsc = htmlspecialchars($error, ENT_QUOTES, 'UTF-8');
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>تأكيد السوبر أدمن</title>
  <?php $ua_sa_css_v = @filemtime(__DIR__ . '/assets/css/ua_program_unified.css') ?: 1; ?>
  <link rel="stylesheet" href="assets/css/ua_program_unified.css?v=<?= (int)$ua_sa_css_v ?>">
  <?php if($uaAndroidSuperConfirm): $uaAndroidSaCssV=@filemtime(__DIR__.'/assets/css/android_super_admin_confirm.css')?:1; ?><link rel="stylesheet" href="assets/css/android_super_admin_confirm.css?v=<?= (int)$uaAndroidSaCssV ?>"><?php endif; ?>
  <style>
    body.ua-super-admin-confirm-page{
      min-height:100vh;
      margin:0;
      overflow:hidden;
      background:rgba(15,23,42,.10);
      font-family:Tahoma,Arial,sans-serif;
    }
    body.ua-super-admin-confirm-page .ua-sa-wrap{
      position:fixed;
      inset:0;
      display:grid;
      place-items:center;
      padding:18px;
      background:
        radial-gradient(circle at 50% 42%, rgba(15,127,216,.12), transparent 30%),
        rgba(241,246,250,.86);
      backdrop-filter:blur(2px);
    }
    body.ua-super-admin-confirm-page .ua-sa-card{
      width:min(360px, calc(100vw - 36px));
      border-radius:16px;
      background:#fff;
      color:#0f172a;
      border:1px solid rgba(148,163,184,.30);
      box-shadow:0 22px 70px rgba(15,23,42,.18);
      overflow:hidden;
      animation:uaSaPop .14s ease-out both;
    }
    body.ua-super-admin-confirm-page .ua-sa-head{
      height:44px;
      display:flex;
      align-items:center;
      justify-content:space-between;
      background:#102033;
      border:0;
    }
    body.ua-super-admin-confirm-page .ua-sa-title{
      padding-inline:14px;
      color:#fff;
      font-size:14px;
      font-weight:900;
    }
    body.ua-super-admin-confirm-page .ua-sa-x{
      width:44px;
      height:44px;
      color:rgba(255,255,255,.82);
      text-decoration:none;
      display:flex;
      align-items:center;
      justify-content:center;
      font-size:22px;
      line-height:1;
    }
    body.ua-super-admin-confirm-page .ua-sa-x:hover{
      background:#c42b1c;
      color:#fff;
    }
    body.ua-super-admin-confirm-page .ua-sa-body{
      padding:18px 18px 16px;
      text-align:right;
    }
    body.ua-super-admin-confirm-page .ua-sa-note{
      margin:0 0 13px;
      color:#64748b;
      font-size:13px;
      font-weight:700;
      line-height:1.65;
    }
    body.ua-super-admin-confirm-page .ua-sa-label{
      display:block;
      margin-bottom:7px;
      color:#243244;
      font-size:13px;
      font-weight:900;
    }
    body.ua-super-admin-confirm-page .ua-sa-input{
      width:100%;
      height:38px;
      border-radius:10px;
      border:1px solid #dbe5ee;
      background:#f7fafc;
      color:#0f172a;
      padding:0 11px;
      font-size:13px;
      outline:0;
      box-shadow:none;
    }
    body.ua-super-admin-confirm-page .ua-sa-input:focus{
      border-color:rgba(15,127,216,.72);
      background:#fff;
      box-shadow:0 0 0 3px rgba(15,127,216,.12);
    }
    body.ua-super-admin-confirm-page .ua-sa-actions{
      display:flex;
      gap:8px;
      margin-top:12px;
    }
    body.ua-super-admin-confirm-page .ua-sa-btn{
      height:38px;
      border-radius:10px;
      padding:0 14px;
      font-size:13px;
      font-weight:900;
      text-decoration:none;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      border:0;
      cursor:pointer;
    }
    body.ua-super-admin-confirm-page .ua-sa-btn.gold{
      flex:1;
      background:linear-gradient(180deg,#0f7fd8,#0967b3);
      color:#fff;
      box-shadow:0 10px 22px rgba(15,127,216,.20);
    }
    body.ua-super-admin-confirm-page .ua-sa-btn.gray{
      background:#eef4f8;
      color:#334155;
      border:1px solid #dbe5ee;
    }
    body.ua-super-admin-confirm-page .ua-sa-err{
      margin:0 0 10px;
      padding:8px 10px;
      border-radius:10px;
      color:#991b1b;
      background:#fff1f2;
      border:1px solid #fecaca;
      font-size:12px;
      font-weight:800;
    }
    body.ua-super-admin-confirm-page .ua-sa-small{
      display:none;
    }
  </style>
</head>
<body class="ua-super-admin-confirm-page <?= $uaAndroidSuperConfirm?'ua-android-super-confirm':'' ?> <?= h(function_exists('super_admin_theme_body_class') ? super_admin_theme_body_class() : 'ua-design-v2 ua-theme-armoury_dark') ?>">
  <main class="ua-sa-wrap" id="uaSaWrap">
    <section class="ua-sa-card" role="dialog" aria-modal="true" aria-labelledby="uaSaTitle">
      <div class="ua-sa-head">
        <div class="ua-sa-title" id="uaSaTitle">تأكيد كلمة مرور السوبر أدمن</div>
        <a class="ua-sa-x" href="<?= $closeEsc ?>" title="إغلاق" aria-label="إغلاق">×</a>
      </div>
      <div class="ua-sa-body">
        <p class="ua-sa-note">للأمان، أدخل كلمة مرور السوبر أدمن لإكمال العملية المحمية.</p>
        <?php if ($error !== ''): ?><div class="ua-sa-err"><?= $errorEsc ?></div><?php endif; ?>
        <form method="post" autocomplete="off">
          <input type="hidden" name="go" value="<?= $goEsc ?>">
          <label class="ua-sa-label" for="uaSaPassword">كلمة المرور</label>
          <input id="uaSaPassword" type="password" name="password" class="ua-sa-input" required autofocus autocomplete="current-password" placeholder="أدخل كلمة المرور">
          <div class="ua-sa-actions">
            <button class="ua-sa-btn gold" type="submit">متابعة</button>
            <a class="ua-sa-btn gray" href="<?= $closeEsc ?>">إلغاء</a>
          </div>
        </form>
        <div class="ua-sa-small">هذه النافذة لا تفتح سايدبار ولا تبقى كطبقة عالقة بعد الإغلاق.</div>
      </div>
    </section>
  </main>
  <script>
    (function(){
      try{ document.getElementById('uaSaPassword').focus({preventScroll:true}); }catch(e){}
      document.addEventListener('keydown',function(e){ if(e.key==='Escape') location.href=<?= json_encode($close_to, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>; });
      if(window.parent && window.parent!==window){
        try{ window.parent.document.body.classList.remove('ua-modal-open'); }catch(e){}
      }
    })();
  </script>
</body>
</html>
