<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * Check if user is logged in
 * Redirects to login if not authenticated
 */
if (!function_exists('check_auth')) {
    function check_auth()
    {
        $CI =& get_instance();

        if (!$CI->session->userdata('logged_in')) {
            $CI->session->set_flashdata('error_message', 'Please login to access this page');
            redirect('admin/login');
        }
    }
}

/**
 * Check if user is admin
 * Redirects to login if not admin
 */
if (!function_exists('check_admin')) {
    function check_admin()
    {
        $CI =& get_instance();

        if (!$CI->session->userdata('logged_in') || $CI->session->userdata('userType') !== 'admin') {
            $CI->session->set_flashdata('error_message', 'Admin access required');
            redirect('admin/login');
        }
    }
}

/**
 * Get logged in user data
 * 
 * @param string|null $key Specific key to get, or null for all data
 * @return mixed
 */
if (!function_exists('get_user_data')) {
    function get_user_data($key = null)
    {
        $CI =& get_instance();

        if ($key) {
            return $CI->session->userdata($key);
        }

        return [
            'user_id' => $CI->session->userdata('user_id'),
            'email' => $CI->session->userdata('email'),
            'name' => $CI->session->userdata('name'),
            'userType' => $CI->session->userdata('userType')
        ];
    }
}

/**
 * Check if user is logged in (boolean)
 * 
 * @return bool
 */
if (!function_exists('is_logged_in')) {
    function is_logged_in()
    {
        $CI =& get_instance();
        return (bool) $CI->session->userdata('logged_in');
    }
}