<?php
// Session helper functions
function get_logged_in_user() {
    if (!isset($_SESSION['user_id'])) {
        return null;
    }
    
    // Handle array user_id (if stored as array)
    $user_id = is_array($_SESSION['user_id']) ? $_SESSION['user_id'][0] : $_SESSION['user_id'];
    
    // Database connection kontrolü
    if (!isset($GLOBALS['con']) || $GLOBALS['con']->connect_error) {
        return null;
    }
    
    $con = $GLOBALS['con'];
    $sql = "SELECT username, email, role, first_name, last_name, created_at, last_login FROM users WHERE id = $user_id";
    $result = $con->query($sql);
    return $result ? $result->fetch_assoc() : null;
}

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

function require_login() {
    if (!is_logged_in()) {
        header('Location: index.php');
        exit();
    }
}

function require_admin() {
    require_login();
    $user = get_logged_in_user();
    if (!$user || $user['role'] !== 'admin') {
        header('Location: dashboard.php');
        exit();
    }
}
?>
