<?php
if (session_status() === PHP_SESSION_NONE) { @session_start(); }
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/api_common.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';


function super_admin_force_logout_json(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();
  }
  out(['ok'=>false, 'logout'=>true, 'redirect'=>$redirect], 401);
}

require_login();
$conn = ensure_db(true);

$action = (string)($_GET['action'] ?? '');
$go = super_admin_sanitize_go((string)($_REQUEST['go'] ?? ''));

if ($action === 'status') {
  out(['ok'=>true, 'confirmed'=>($go !== '' ? super_admin_peek_ok($go) : false)]);
}

$pass = trim((string)($_POST['password'] ?? ''));
if ($pass === '') out(['ok'=>false, 'message'=>'كلمة المرور مطلوبة.'], 400);
if ($go === '') out(['ok'=>false, 'message'=>'الرابط المطلوب غير صالح.'], 400);

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

$ok = false;
$hash = (string)setting_get($conn, 'super_admin_pass_hash', '');
if ($hash === '') $hash = (string)setting_get($conn, 'super_admin_password_hash', '');
if ($hash === '') $hash = (string)setting_get($conn, 'super_admin_pass', '');

if ($hash !== '' && function_exists('verify_any_password')) {
  $ok = verify_any_password($pass, $hash);
} elseif ($hash !== '') {
  $ok = (strpos($hash, '$2y$') === 0 || strpos($hash, '$argon2') === 0) ? password_verify($pass, $hash) : hash_equals($hash, $pass);
}

if (!$ok) {
  $res = @$conn->query("SELECT password, password_hash FROM admin_users WHERE id=1 LIMIT 1");
  if ($res && $res->num_rows) {
    $row = $res->fetch_assoc();
    $plain = (string)($row['password'] ?? '');
    $dbhash = (string)($row['password_hash'] ?? '');

    if ($dbhash !== '' && function_exists('verify_any_password')) {
      $ok = verify_any_password($pass, $dbhash);
    } elseif ($dbhash !== '') {
      $ok = (strpos($dbhash, '$2y$') === 0 || strpos($dbhash, '$argon2') === 0) ? password_verify($pass, $dbhash) : hash_equals($dbhash, $pass);
    }

    if (!$ok && $plain !== '' && function_exists('verify_any_password')) {
      $ok = verify_any_password($pass, $plain);
    } elseif (!$ok && $plain !== '') {
      $ok = (strpos($plain, '$2y$') === 0 || strpos($plain, '$argon2') === 0) ? password_verify($pass, $plain) : hash_equals($plain, $pass);
    }
  }
}

if (!$ok) {
  $_SESSION['super_admin_fail_count'] = (int)($_SESSION['super_admin_fail_count'] ?? 0) + 1;
  if ((int)$_SESSION['super_admin_fail_count'] >= $maxAttempts) {
    super_admin_force_logout_json('login.php');
  }
  $remaining = $maxAttempts - (int)$_SESSION['super_admin_fail_count'];
  out(['ok'=>false, 'message'=>'كلمة مرور السوبر أدمن غير صحيحة. المحاولات المتبقية: ' . $remaining], 403);
}

$_SESSION['super_admin_fail_count'] = 0;
super_admin_mark_ok($go);
out(['ok'=>true, 'confirmed'=>true, 'go'=>$go]);
