<?php
/**
 * Aysa Authentication Helper Functions
 * 
 * @package Aysa
 * @since 1.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Check if current user can access Aysa dashboard
 * This replaces the need for manage_options capability
 * 
 * @return bool True if user is authenticated with Aysa
 */
function aysa_current_user_can_access() {
    // First check if user is logged into WordPress
    if (!is_user_logged_in()) {
        return false;
    }
    
    // Check Aysa authentication
    if (class_exists('Aysa_Auth_Manager')) {
        $auth_manager = Aysa_Auth_Manager::get_instance();
        $auth_status = $auth_manager->is_authenticated();
        return $auth_status['authenticated'];
    }
    
    return false;
}

/**
 * Check if current user can access Aysa OR has WordPress admin permissions
 * This is for backward compatibility and admin-level functions
 * 
 * @return bool True if user has Aysa auth or WordPress admin permissions
 */
function aysa_current_user_can_access_or_admin() {
    return aysa_current_user_can_access() || current_user_can('manage_options');
}

/**
 * WordPress capability filter to handle custom Aysa capabilities
 */
function aysa_map_meta_cap($caps, $cap, $user_id, $args) {
    if ($cap === 'access_aysa_dashboard') {
        if (aysa_current_user_can_access()) {
            return array('read'); // Grant access with basic read capability
        } else {
            return array('do_not_allow'); // Deny access
        }
    }
    
    return $caps;
}

// Add the capability filter
add_filter('map_meta_cap', 'aysa_map_meta_cap', 10, 4); 