<?php
function safe_session_start( )   {
    if ( session_status() === PHP_SESSION_NONE ){
        session_start();
    }
}

function is_logged_in( ) {
    safe_session_start();
    return isset($_SESSION['user_id']);
}

function is_admin( ){
    safe_session_start();
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
}

function get_current_user_data( ) {
    safe_session_start();

    $uid = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;   
    if (!$uid){ return null; }

    require_once 'db_config.php';
    $db = getDBConnection();

    $q = "SELECT id, name, email, phone, adress, role FROM users WHERE id = ?";
    $st = $db->prepare($q);
    $st->execute([$uid]);
    $row = $st->fetch(PDO::FETCH_ASSOC);

    if ($row){
        $res = [
            'id'      => $row['id'],
            'name'    => $row['name'],
            'email'   => $row['email'],
            'phone'   => $row['phone'],
            'address' => $row['adress'],
            'role'    => $row['role']
        ];
        return $res;  
    }

    return null;   
}
?>