<?php
/*
|--------------------------------------------------------------------------
| RadyoHost.BiZ / Profesyonel Radyo Hosting ve Web Tasarım Hizmetleri
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| Okey Platformu / Premium Okey ve Sohbet Platformu
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| Okey Platformu / Premium Okey Tanıtım ve Üyelik Sistemi
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| YETKİLENDİRME YÖNETİM DOSYASI
|--------------------------------------------------------------------------
| auth.php
| Okey Platformu Kullanıcı ve Yönetici Oturum Kontrol Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function user(): ?array
{
    if (!empty($_SESSION['user']) && is_array($_SESSION['user'])) {
        return $_SESSION['user'];
    }

    if (!empty($_SESSION['user_id'])) {
        return [
            'id'       => $_SESSION['user_id'],
            'name'     => $_SESSION['user_name'] ?? $_SESSION['admin_name'] ?? 'Kullanıcı',
            'username' => $_SESSION['user_username'] ?? $_SESSION['admin_username'] ?? '',
            'email'    => $_SESSION['user_email'] ?? $_SESSION['admin_email'] ?? '',
            'role'     => $_SESSION['user_role'] ?? $_SESSION['admin_role'] ?? 'user',
        ];
    }

    return null;
}

function admin(): ?array
{
    if (!empty($_SESSION['admin']) && is_array($_SESSION['admin'])) {
        return $_SESSION['admin'];
    }

    if (!empty($_SESSION['admin_id']) && !empty($_SESSION['admin_logged_in'])) {
        return [
            'id'       => $_SESSION['admin_id'],
            'name'     => $_SESSION['admin_name'] ?? 'Yönetici',
            'username' => $_SESSION['admin_username'] ?? '',
            'email'    => $_SESSION['admin_email'] ?? '',
            'role'     => $_SESSION['admin_role'] ?? 'admin',
            'image'    => $_SESSION['admin_image'] ?? '',
        ];
    }

    return null;
}

function is_user_logged_in(): bool
{
    return user() !== null;
}

function is_admin_logged_in(): bool
{
    return admin() !== null;
}

function require_user(): void
{
    if (!is_user_logged_in()) {
        header('Location: login.php');
        exit;
    }
}

function require_admin(): void
{
    if (!is_admin_logged_in()) {
        header('Location: login.php');
        exit;
    }
}

function redirect_if_admin_logged_in(): void
{
    if (is_admin_logged_in()) {
        header('Location: index.php');
        exit;
    }
}

function auth_login_admin(array $user): void
{
    session_regenerate_id(true);

    $_SESSION['admin'] = [
        'id'       => (int)($user['id'] ?? 0),
        'name'     => trim((string)($user['name'] ?? '')) !== '' ? (string)$user['name'] : (string)($user['username'] ?? 'Yönetici'),
        'username' => (string)($user['username'] ?? ''),
        'email'    => (string)($user['email'] ?? ''),
        'role'     => (string)($user['role'] ?? 'admin'),
        'image'    => (string)($user['image'] ?? ''),
    ];

    $_SESSION['admin_id']        = $_SESSION['admin']['id'];
    $_SESSION['user_id']         = $_SESSION['admin']['id'];
    $_SESSION['admin_name']      = $_SESSION['admin']['name'];
    $_SESSION['admin_username']  = $_SESSION['admin']['username'];
    $_SESSION['admin_email']     = $_SESSION['admin']['email'];
    $_SESSION['admin_role']      = $_SESSION['admin']['role'];
    $_SESSION['admin_image']     = $_SESSION['admin']['image'];
    $_SESSION['admin_logged_in'] = true;

    $_SESSION['_auth_last_activity'] = time();
    $_SESSION['_auth_regenerated']   = time();
}

function auth_logout(): void
{
    unset(
        $_SESSION['admin'],
        $_SESSION['user'],
        $_SESSION['admin_id'],
        $_SESSION['user_id'],
        $_SESSION['admin_name'],
        $_SESSION['admin_username'],
        $_SESSION['admin_email'],
        $_SESSION['admin_role'],
        $_SESSION['admin_image'],
        $_SESSION['admin_logged_in']
    );
}

function auth_csrf_token(): string
{
    if (empty($_SESSION['_auth_csrf'])) {
        $_SESSION['_auth_csrf'] = bin2hex(random_bytes(32));
    }

    return (string)$_SESSION['_auth_csrf'];
}

function auth_verify_csrf(string $token): bool
{
    return !empty($_SESSION['_auth_csrf']) && hash_equals((string)$_SESSION['_auth_csrf'], $token);
}

function auth_check_login_attempts(string $key = 'admin', int $max = 8, int $seconds = 900): bool
{
    $sessionKey = '_auth_attempt_' . md5($key . '_' . ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'));

    if (empty($_SESSION[$sessionKey])) {
        return true;
    }

    $data = $_SESSION[$sessionKey];

    if ((time() - (int)($data['time'] ?? 0)) > $seconds) {
        unset($_SESSION[$sessionKey]);
        return true;
    }

    return (int)($data['count'] ?? 0) < $max;
}

function auth_add_login_attempt(string $key = 'admin'): void
{
    $sessionKey = '_auth_attempt_' . md5($key . '_' . ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'));

    if (empty($_SESSION[$sessionKey])) {
        $_SESSION[$sessionKey] = [
            'count' => 1,
            'time'  => time(),
        ];
        return;
    }

    $_SESSION[$sessionKey]['count'] = (int)$_SESSION[$sessionKey]['count'] + 1;
}

function auth_clear_login_attempts(string $key = 'admin'): void
{
    $sessionKey = '_auth_attempt_' . md5($key . '_' . ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'));
    unset($_SESSION[$sessionKey]);
}