<?php
/**
 * HVAC Template Security Handler
 * 
 * Centralized security and access control for template system
 * 
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

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

class HVAC_Template_Security {
    
    /**
     * Check if current user has access to a page
     * 
     * @param array $page_config Page configuration
     * @return bool
     */
    public static function check_page_access($page_config) {
        // Always allow access if no restrictions
        if (empty($page_config['required_capability']) && empty($page_config['required_role'])) {
            return true;
        }
        
        // Must be logged in for restricted pages
        if (!is_user_logged_in()) {
            return false;
        }
        
        $user = wp_get_current_user();
        
        // Check capability if specified
        if (!empty($page_config['required_capability'])) {
            if (!current_user_can($page_config['required_capability'])) {
                return false;
            }
        }
        
        // Check role if specified
        if (!empty($page_config['required_role'])) {
            $required_roles = (array) $page_config['required_role'];
            $user_roles = $user->roles;
            
            // Check if user has any of the required roles
            if (empty(array_intersect($required_roles, $user_roles))) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * Get access requirements for a page based on slug
     * 
     * @param string $page_slug
     * @return array
     */
    public static function get_page_requirements($page_slug) {
        // Define page access requirements
        $requirements = [
            // Trainer pages
            'trainer/dashboard' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/profile' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/profile/edit' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/certificate-reports' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/generate-certificates' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/venue/list' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/venue/manage' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/organizer/list' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/organizer/manage' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/event/create' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/event/edit' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/event/manage' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/event/summary' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/email-attendees' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/communication-templates' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/communication-schedules' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/profile/training-leads' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/announcements' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/resources' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            'trainer/documentation' => ['required_role' => ['hvac_trainer', 'hvac_master_trainer']],
            
            // Master trainer pages
            'master-trainer/master-dashboard' => ['required_role' => ['hvac_master_trainer']],
            'master-trainer/announcements' => ['required_role' => ['hvac_master_trainer']],
            'master-trainer/manage-announcements' => ['required_role' => ['hvac_master_trainer']],
            
            // Public pages (no requirements)
            'community-login' => [],
            'trainer/registration' => [],
            'registration-pending' => [],
            'find-a-trainer' => [],
            
            // Status pages (logged in users only)
            'trainer/account-pending' => ['logged_in' => true],
            'trainer/account-disabled' => ['logged_in' => true]
        ];
        
        return $requirements[$page_slug] ?? [];
    }
    
    /**
     * Handle access denied scenarios
     * 
     * @param string $page_slug
     * @param array $page_config
     */
    public static function handle_access_denied($page_slug, $page_config) {
        if (!is_user_logged_in()) {
            // Redirect to login
            wp_safe_redirect(home_url('/community-login/?redirect_to=' . urlencode($_SERVER['REQUEST_URI'])));
            exit;
        }
        
        // Check user status for trainer pages
        if (strpos($page_slug, 'trainer/') === 0) {
            $user_status = get_user_meta(get_current_user_id(), 'hvac_account_status', true);
            
            switch ($user_status) {
                case 'pending':
                    wp_safe_redirect(home_url('/trainer/account-pending/'));
                    exit;
                    
                case 'disabled':
                    wp_safe_redirect(home_url('/trainer/account-disabled/'));
                    exit;
                    
                default:
                    // Generic access denied
                    wp_die(__('You do not have permission to access this page.', 'hvac-community-events'));
                    break;
            }
        }
        
        // Generic access denied
        wp_die(__('Access denied.', 'hvac-community-events'));
    }
    
    /**
     * Validate nonce for form submissions
     * 
     * @param string $action
     * @param string $nonce_field
     * @return bool
     */
    public static function validate_nonce($action, $nonce_field = '_wpnonce') {
        return wp_verify_nonce($_POST[$nonce_field] ?? $_GET[$nonce_field] ?? '', $action);
    }
    
    /**
     * Check if current user can edit a specific trainer profile
     * 
     * @param int $trainer_id
     * @return bool
     */
    public static function can_edit_trainer_profile($trainer_id) {
        $current_user_id = get_current_user_id();
        
        // Own profile
        if ($current_user_id == $trainer_id) {
            return true;
        }
        
        // Master trainers can edit other profiles
        $user = wp_get_current_user();
        if (in_array('hvac_master_trainer', $user->roles)) {
            return true;
        }
        
        // Administrators can edit all profiles
        if (current_user_can('manage_options')) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Sanitize and validate user input
     * 
     * @param mixed $input
     * @param string $type
     * @return mixed
     */
    public static function sanitize_input($input, $type = 'text') {
        switch ($type) {
            case 'email':
                return sanitize_email($input);
                
            case 'url':
                return esc_url_raw($input);
                
            case 'int':
                return intval($input);
                
            case 'float':
                return floatval($input);
                
            case 'textarea':
                return sanitize_textarea_field($input);
                
            case 'html':
                return wp_kses_post($input);
                
            case 'text':
            default:
                return sanitize_text_field($input);
        }
    }
}