<?php
declare(strict_types=1);

/**
 * /public_html/test_erp/api/auth/me.php
 * Current Login User Information — TEST Environment
 */

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

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

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

$user = null;

if ($loggedIn) {
    if (function_exists('get_logged_in_user')) {
        $currentUser = get_logged_in_user();

        $user = [
            'user_id' => isset($currentUser['user_id'])
                ? (int) $currentUser['user_id']
                : null,

            'name' => isset($currentUser['name'])
                ? (string) $currentUser['name']
                : null,

            'role' => isset($currentUser['role'])
                ? (string) $currentUser['role']
                : null,

            'location' => isset($currentUser['location'])
                ? (int) $currentUser['location']
                : null,
        ];
    } else {
        $user = [
            'user_id' => isset($_SESSION['user_id'])
                ? (int) $_SESSION['user_id']
                : null,

            'name' => isset($_SESSION['user_name'])
                ? (string) $_SESSION['user_name']
                : null,

            'role' => isset($_SESSION['user_role'])
                ? (string) $_SESSION['user_role']
                : (
                    isset($_SESSION['role'])
                        ? (string) $_SESSION['role']
                        : null
                ),

            'location' => isset($_SESSION['location_id'])
                ? (int) $_SESSION['location_id']
                : null,
        ];
    }
}

http_response_code(200);

echo json_encode([
    'status'    => true,
    'success'   => true,
    'ok'        => true,
    'code'      => 200,
    'logged_in' => $loggedIn,
    'message'   => $loggedIn
        ? 'ইউজার লগইন করা আছে'
        : 'ইউজার লগইন করা নেই',
    'user'      => $user,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

exit;