<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Jewelry ERP Secure Session — TEST
|--------------------------------------------------------------------------
| Test domain: test.jewellersbd.com
| Live ERP session থেকে সম্পূর্ণ আলাদা।
|--------------------------------------------------------------------------
*/

if (session_status() === PHP_SESSION_NONE) {
    $secure = (
        (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')
    );

    ini_set('session.use_only_cookies', '1');
    ini_set('session.use_strict_mode', '1');
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', 'Lax');
    ini_set('session.use_trans_sid', '0');

    /*
    |--------------------------------------------------------------------------
    | Test ERP-এর আলাদা session cookie
    |--------------------------------------------------------------------------
    */

    session_name('JEWELLERSERPTESTSESSID');

    /*
    |--------------------------------------------------------------------------
    | Host-only cookie
    |--------------------------------------------------------------------------
    | Domain খালি থাকায় এটি শুধু test.jewellersbd.com-এ কাজ করবে।
    |--------------------------------------------------------------------------
    */

    session_set_cookie_params(
        0,      // Browser বন্ধ হলে cookie শেষ
        '/',    // পুরো Test ERP-এর জন্য
        '',     // শুধু test.jewellersbd.com
        $secure,
        true
    );

    session_start();
}

/*
|--------------------------------------------------------------------------
| Session Timeout: 30 Minutes
|--------------------------------------------------------------------------
*/

$timeout = 1800;
$now = time();

if (
    isset($_SESSION['LAST_ACTIVITY'])
    && ($now - (int) $_SESSION['LAST_ACTIVITY']) > $timeout
) {
    $_SESSION = [];

    if ((bool) ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();

        setcookie(
            session_name(),
            '',
            $now - 42000,
            $params['path'],
            $params['domain'],
            (bool) $params['secure'],
            (bool) $params['httponly']
        );
    }

    session_destroy();
    session_id('');
    session_start();
}

$_SESSION['LAST_ACTIVITY'] = $now;

/**
 * User login করা আছে কিনা।
 */
function is_logged_in(): bool
{
    return isset($_SESSION['user_id'])
        && (int) $_SESSION['user_id'] > 0;
}

/**
 * বর্তমানে login করা user-এর তথ্য।
 */
function get_logged_in_user(): array
{
    return [
        'user_id'  => $_SESSION['user_id'] ?? null,
        'name'     => $_SESSION['user_name'] ?? null,
        'role'     => $_SESSION['user_role'] ?? ($_SESSION['role'] ?? null),
        'location' => $_SESSION['location_id'] ?? null,
    ];
}

/**
 * Login ছাড়া protected API ব্যবহার বন্ধ করে।
 */
function require_login(): void
{
    if (is_logged_in()) {
        return;
    }

    http_response_code(401);
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode([
        'status'  => false,
        'success' => false,
        'message' => 'লগইন প্রয়োজন',
        'data'    => null,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    exit;
}