<?php
declare(strict_types=1);

/**
 * /public_html/test_erp/api/auth/check_session.php
 *
 * Protected API Session Guard — TEST Environment
 *
 * Login থাকলে কোনো output দেবে না।
 * Login না থাকলে 401 JSON response দিয়ে request বন্ধ করবে।
 */

require_once __DIR__ . '/../../config/session.php';

/*
|--------------------------------------------------------------------------
| Login Verification
|--------------------------------------------------------------------------
*/

$isAuthenticated = function_exists('is_logged_in')
    ? is_logged_in()
    : (
        isset($_SESSION['user_id'])
        && (int) $_SESSION['user_id'] > 0
    );

if (!$isAuthenticated) {
    http_response_code(401);

    header('Content-Type: application/json; charset=UTF-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');

    echo json_encode([
        'status'  => false,
        'success' => false,
        'ok'      => false,
        'code'    => 401,
        'error'   => 'Unauthorized',
        'message' => 'লগইন করুন',
        'data'    => null,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    exit;
}

/*
|--------------------------------------------------------------------------
| Current User Helper Functions
|--------------------------------------------------------------------------
|
| পুরোনো API compatibility-এর জন্য function-এর নাম অপরিবর্তিত রাখা হয়েছে।
|--------------------------------------------------------------------------
*/

/**
 * Login করা user-এর ID।
 */
if (!function_exists('currentUserId')) {
    function currentUserId(): int
    {
        return (int) ($_SESSION['user_id'] ?? 0);
    }
}

/**
 * Login করা user-এর role।
 */
if (!function_exists('currentUserRole')) {
    function currentUserRole(): string
    {
        return (string) (
            $_SESSION['user_role']
            ?? $_SESSION['role']
            ?? 'staff'
        );
    }
}

/**
 * Login করা user-এর নাম।
 */
if (!function_exists('currentUserName')) {
    function currentUserName(): string
    {
        return (string) (
            $_SESSION['user_name']
            ?? 'Unknown'
        );
    }
}