<?php
require_once __DIR__ . '/firebase-rtdb-admin.php';

function sa_json_response($statusCode, $payload) {
    if (!headers_sent()) {
        header('Content-Type: application/json; charset=UTF-8');
    }
    http_response_code($statusCode);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

function sa_require_post_json() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') sa_json_response(405, ['status' => 'error', 'message' => 'Method not allowed']);
    $raw = file_get_contents('php://input');
    $body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
    if (!is_array($body)) sa_json_response(400, ['status' => 'error', 'message' => 'Invalid JSON']);
    return $body;
}

function sa_load_bootstrap() {
    $bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
    if (!is_readable($bootPath)) sa_json_response(503, ['status' => 'error', 'message' => 'Missing firebase-admin-bootstrap.local.php']);
    $boot = include $bootPath;
    if (!is_array($boot)) sa_json_response(503, ['status' => 'error', 'message' => 'Invalid firebase-admin-bootstrap.local.php']);
    $saPath = trim((string)($boot['service_account_json_path'] ?? ''));
    $dbUrl = trim((string)($boot['firebase_database_url'] ?? ''));
    $webKey = trim((string)($boot['firebase_web_api_key'] ?? ''));
    if ($saPath === '' || $dbUrl === '' || $webKey === '') sa_json_response(503, ['status' => 'error', 'message' => 'Bootstrap config incomplete']);
    return [$saPath, $dbUrl, $webKey];
}

function sa_load_super_admin_cfg() {
    $cfgPath = __DIR__ . '/super-admin.local.php';
    if (!is_readable($cfgPath)) sa_json_response(503, ['status' => 'error', 'message' => 'Missing super-admin.local.php']);
    $cfg = include $cfgPath;
    if (!is_array($cfg)) sa_json_response(503, ['status' => 'error', 'message' => 'Invalid super-admin.local.php']);
    return $cfg;
}

function sa_session_start_secure($cfg = null) {
    if (session_status() === PHP_SESSION_ACTIVE) return;
    $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || ((int)($_SERVER['SERVER_PORT'] ?? 0) === 443);
    $cookiePath = '/';
    if (is_array($cfg)) {
        $p = trim((string)($cfg['session_cookie_path'] ?? ''));
        if ($p !== '') {
            $cookiePath = $p;
        }
    }
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => $cookiePath,
        'domain' => '',
        'secure' => $isHttps,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    session_start();
    if (is_array($cfg)) {
        $timeout = (int)($cfg['session_timeout_seconds'] ?? 3600);
        $now = time();
        if (!empty($_SESSION['super_admin_last_seen']) && ($now - (int)$_SESSION['super_admin_last_seen']) > $timeout) {
            $_SESSION = [];
            if (session_id() !== '' && function_exists('session_destroy')) session_destroy();
            session_start();
        }
        $_SESSION['super_admin_last_seen'] = $now;
    }
}

function sa_current_admin() {
    $cfg = sa_load_super_admin_cfg();
    sa_session_start_secure($cfg);
    if (empty($_SESSION['is_super_admin']) || empty($_SESSION['super_admin_email'])) {
        sa_json_response(403, ['status' => 'error', 'message' => 'Unauthorized']);
    }
    return [
        'uid' => (string)($_SESSION['super_admin_uid'] ?? 'session-admin'),
        'email' => (string)$_SESSION['super_admin_email'],
        'cfg' => $cfg,
    ];
}

function sa_require_super_admin_session_with_db() {
    $admin = sa_current_admin();
    [$saPath, $dbUrl, $webKey] = sa_load_bootstrap();
    $tok = firebase_service_account_access_token($saPath);
    if (isset($tok['error'])) sa_json_response(503, ['status' => 'error', 'message' => 'Admin token error: ' . $tok['error']]);
    return [$admin['uid'], $admin['email'], $dbUrl, $tok['access_token'], $admin['cfg'], $webKey];
}

function sa_record_failed_login_attempt() {
    sa_session_start_secure();
    $ip = (string)($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    $key = 'super_admin_failed_' . $ip;
    $now = time();
    $state = isset($_SESSION[$key]) && is_array($_SESSION[$key]) ? $_SESSION[$key] : ['count' => 0, 'blocked_until' => 0];
    if ($state['blocked_until'] > $now) return $state;
    $state['count'] = (int)$state['count'] + 1;
    if ($state['count'] >= 5) {
        $state['blocked_until'] = $now + 120;
        $state['count'] = 0;
    }
    $_SESSION[$key] = $state;
    return $state;
}

function sa_is_login_temporarily_blocked() {
    sa_session_start_secure();
    $ip = (string)($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    $key = 'super_admin_failed_' . $ip;
    $now = time();
    $state = isset($_SESSION[$key]) && is_array($_SESSION[$key]) ? $_SESSION[$key] : null;
    if (!$state) return 0;
    $blockedUntil = (int)($state['blocked_until'] ?? 0);
    return $blockedUntil > $now ? ($blockedUntil - $now) : 0;
}

function sa_clear_failed_login_attempts() {
    sa_session_start_secure();
    $ip = (string)($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    $key = 'super_admin_failed_' . $ip;
    unset($_SESSION[$key]);
}

function sa_audit_log($dbUrl, $accessToken, $actorUid, $actorEmail, $action, $targetClientId, $meta = []) {
    $logId = 'log_' . time() . '_' . substr(bin2hex(random_bytes(6)), 0, 8);
    $payload = [
        'actorUid' => $actorUid,
        'actorEmail' => $actorEmail,
        'action' => $action,
        'targetClientId' => $targetClientId,
        'meta' => $meta,
        'createdAt' => time() * 1000,
    ];
    firebase_rtdb_put($dbUrl, 'superAdminLogs/' . $logId, $accessToken, $payload);
}
