<?php
require_once 'config.php';

// Login function
function login($email, $password) {
    global $conn;
    
    $email = $conn->real_escape_string($email);
    $sql = "SELECT * FROM users WHERE email = '$email'";
    $result = $conn->query($sql);
    
    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['employee_id'] = $user['employee_id'];
            $_SESSION['full_name'] = $user['full_name'];
            $_SESSION['email'] = $user['email'];
            $_SESSION['role'] = $user['role'];
            return true;
        }
    }
    return false;
}

// Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Check if user is admin (sectional_head, vice_principal, or principal)
function isAdmin() {
    if (!isLoggedIn()) {
        return false;
    }
    $role = $_SESSION['role'];
    return in_array($role, ['sectional_head', 'vice_principal', 'principal']);
}

// Check user role
function hasRole($role) {
    if (!isLoggedIn()) {
        return false;
    }
    return $_SESSION['role'] === $role;
}

// Get approval authority based on role
function getApprovalLimit($role) {
    switch ($role) {
        case 'sectional_head':
            return 10;
        case 'vice_principal':
            return 20;
        case 'principal':
            return PHP_INT_MAX;
        default:
            return 0;
    }
}

// Check if admin can approve based on leave count
function canApproveLeave($adminRole, $employeeLeaveCount) {
    $limit = getApprovalLimit($adminRole);
    return $employeeLeaveCount <= $limit;
}

// Logout function
function logout() {
    session_destroy();
    header('Location: login.php');
    exit();
}

// Redirect if not logged in
function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit();
    }
}

// Redirect if not admin
function requireAdmin() {
    requireLogin();
    if (!isAdmin()) {
        header('Location: user_dashboard.php');
        exit();
    }
}
?>
