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

if (!function_exists('is_logged_in')) {
    function is_logged_in() {
        $CI =& get_instance();
        return $CI->session->userdata('logged_in') === TRUE;
    }
}

if (!function_exists('require_login')) {
    function require_login($redirect = 'auth/login') {
        if (!is_logged_in()) {
            redirect($redirect);
        }
    }
}

if (!function_exists('require_profile_complete')) {
    function require_profile_complete() {
        $CI =& get_instance();
        $CI->load->model('User_model');
        $profile = $CI->User_model->get_profile($CI->session->userdata('user_id'));
        
        if (!$profile || !$profile->is_complete) {
            redirect('profile/bio-data');
        }
    }
}

if (!function_exists('generate_application_number')) {
    function generate_application_number() {
        return 'APP' . date('Ymd') . strtoupper(bin2hex(random_bytes(4)));
    }
}

if (!function_exists('validate_file_upload')) {
    function validate_file_upload($file, $max_size = 2097152, $allowed_types = ['pdf', 'jpg', 'jpeg', 'png']) {
        $CI =& get_instance();
        $CI->load->library('upload');
        
        if ($file['size'] > $max_size) {
            return ['success' => false, 'error' => 'File size exceeds limit'];
        }
        
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed_types)) {
            return ['success' => false, 'error' => 'Invalid file type'];
        }
        
        return ['success' => true];
    }
}

if (!function_exists('calculate_eligibility_score')) {
    function calculate_eligibility_score($marks, $specialization) {
        $base_score = $marks;
        
        // Bonus for science stream
        if ($specialization == 'science') {
            $base_score += 5;
        }
        
        return min(100, $base_score);
    }
}

if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $CI =& get_instance();
        return $CI->security->xss_clean(strip_tags(trim($data)));
    }
}