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

// Role checking functions
function isAdmin() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

function isManager() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'manager';
}

function isEmployee() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'employee';
}

// Get current user's role
function getUserRole() {
    return $_SESSION['role'] ?? null;
}

// Get current user ID
function getUserId() {
    return $_SESSION['user_id'] ?? null;
}

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

// Check permission function
function hasPermission($permission_name, $pdo = null) {
    if (!isset($_SESSION['role'])) {
        return false;
    }
    
    // Admin has all permissions
    if ($_SESSION['role'] === 'admin') {
        return true;
    }
    
    // Manager also has permission to manage salary - ADDED THIS
    if ($_SESSION['role'] === 'manager' && $permission_name === 'manage_salary') {
        return true;
    }
    
    // If PDO connection is provided, check from database
    if ($pdo) {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as count 
                FROM role_permissions rp 
                JOIN permissions p ON rp.permission_id = p.id 
                WHERE rp.role = ? AND p.permission_name = ?
            ");
            $stmt->execute([$_SESSION['role'], $permission_name]);
            $result = $stmt->fetch();
            return $result['count'] > 0;
        } catch (PDOException $e) {
            error_log("Permission check error: " . $e->getMessage());
            return false;
        }
    }
    
    // Basic role-based permission check (fallback) - UPDATED
    $permissions = [
        'admin' => [
            'view_dashboard', 'manage_employees', 'view_employees', 'manage_attendance',
            'view_attendance', 'manage_leaves', 'apply_leaves', 'manage_interns',
            'view_reports', 'generate_reports', 'manage_users', 'manage_departments',
            'view_profile', 'edit_profile', 'view_salary', 'manage_salary',
            'approve_registrations'
        ],
        'manager' => [
            'view_dashboard', 'manage_employees', 'view_employees', 'manage_attendance',
            'view_attendance', 'manage_leaves', 'apply_leaves', 'manage_interns',
            'view_reports', 'generate_reports', 'view_profile', 'edit_profile',
            'view_salary', 'manage_salary'  // Added manage_salary permission for managers
        ],
        'employee' => [
            'view_dashboard', 'view_employees', 'view_attendance', 'apply_leaves',
            'view_profile', 'edit_profile'
        ]
    ];
    
    return isset($permissions[$_SESSION['role']]) && 
           in_array($permission_name, $permissions[$_SESSION['role']]);
}

// Redirect based on role after login
function redirectBasedOnRole() {
    if (isLoggedIn()) {
        switch ($_SESSION['role']) {
            case 'admin':
            case 'manager':
            case 'employee':
                header('Location: dashboard.php');
                break;
            default:
                header('Location: login.php');
        }
        exit();
    }
}

// Check page access - UPDATED to include pending_approvals and salary_update
function checkPageAccess($page) {
    $allowed_pages = [
        'admin' => ['overview', 'employees', 'attendance', 'leave', 'interns', 
                   'reports', 'profile', 'users', 'departments', 'settings',
                   'pending_approvals', 'salary_update'], // Added salary_update
        'manager' => ['overview', 'employees', 'attendance', 'leave', 'interns', 
                     'reports', 'profile', 'salary_update'], // Added salary_update
        'employee' => ['overview', 'attendance', 'leave', 'profile']
    ];
    
    $role = $_SESSION['role'] ?? '';
    
    // Debug: Check if role exists and page is in allowed pages
    if (empty($role)) {
        error_log("DEBUG: Role is empty in session");
        return false;
    }
    
    if (!isset($allowed_pages[$role])) {
        error_log("DEBUG: Role '$role' not found in allowed_pages array");
        return false;
    }
    
    $has_access = in_array($page, $allowed_pages[$role]);
    
    if (!$has_access) {
        error_log("DEBUG: Page '$page' not allowed for role '$role'. Allowed: " . implode(', ', $allowed_pages[$role]));
    }
    
    return $has_access;
}

// Initialize session with default values
function initializeSession($user_id, $username, $role, $email = '', $full_name = '', $department = '') {
    $_SESSION['user_id'] = $user_id;
    $_SESSION['username'] = $username;
    $_SESSION['role'] = $role;
    $_SESSION['email'] = $email;
    $_SESSION['full_name'] = $full_name;
    $_SESSION['department'] = $department;
    $_SESSION['login_time'] = time();
    $_SESSION['last_activity'] = time();
}

// Check session timeout (30 minutes)
function checkSessionTimeout() {
    $timeout = 1800; // 30 minutes in seconds
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
        session_destroy();
        header('Location: login.php?timeout=1');
        exit();
    }
    $_SESSION['last_activity'] = time();
}

// Get session department safely
function getSessionDepartment() {
    return $_SESSION['department'] ?? '';
}

// Get session full name safely
function getSessionFullName() {
    return $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'User';
}

// Debug function to check session
function debugSession() {
    echo "<pre>Session Data:\n";
    print_r($_SESSION);
    echo "</pre>";
}

// Check if admin can access pending approvals
function canAccessPendingApprovals() {
    return isAdmin();
}

// Add employee_id to session if not set
function setEmployeeIdInSession($pdo) {
    if (!isset($_SESSION['employee_id']) && isset($_SESSION['user_id'])) {
        try {
            $stmt = $pdo->prepare("SELECT id FROM employees WHERE user_id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $employee = $stmt->fetch();
            
            if ($employee) {
                $_SESSION['employee_id'] = $employee['id'];
            }
        } catch (Exception $e) {
            error_log("Error setting employee_id in session: " . $e->getMessage());
        }
    }
}
?>