<?php
/**
 * HVAC Role Consolidator
 * 
 * Handles consolidation of duplicate roles and ensures proper permissions
 *
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

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

class HVAC_Role_Consolidator {
    
    /**
     * Run the role consolidation process
     */
    public static function consolidate_roles() {
        $results = array();
        
        // Step 1: Migrate users from event_trainer to hvac_trainer
        $results['migration'] = self::migrate_users_from_legacy_role();
        
        // Step 2: Remove the duplicate event_trainer role
        $results['removal'] = self::remove_legacy_role();
        
        // Step 3: Ensure proper capabilities for hvac_trainer role
        $results['capabilities'] = self::ensure_proper_capabilities();
        
        // Step 4: Clean up any permission issues
        $results['cleanup'] = self::cleanup_permissions();
        
        return $results;
    }
    
    /**
     * Migrate users from event_trainer to hvac_trainer role
     */
    private static function migrate_users_from_legacy_role() {
        $migrated = 0;
        $errors = array();
        
        // Get all users with event_trainer role
        $users = get_users(array('role' => 'event_trainer'));
        
        foreach ($users as $user) {
            try {
                // Remove old role
                $user->remove_role('event_trainer');
                
                // Add new role
                $user->add_role('hvac_trainer');
                
                $migrated++;
                
                HVAC_Logger::info("Migrated user {$user->ID} from event_trainer to hvac_trainer", 'Role Consolidator');
            } catch (Exception $e) {
                $errors[] = "Failed to migrate user {$user->ID}: " . $e->getMessage();
                HVAC_Logger::error("Failed to migrate user {$user->ID}: " . $e->getMessage(), 'Role Consolidator');
            }
        }
        
        return array(
            'migrated' => $migrated,
            'errors' => $errors
        );
    }
    
    /**
     * Remove the legacy event_trainer role
     */
    private static function remove_legacy_role() {
        // Check if role exists
        if (get_role('event_trainer')) {
            remove_role('event_trainer');
            HVAC_Logger::info('Removed legacy event_trainer role', 'Role Consolidator');
            return true;
        }
        
        return false;
    }
    
    /**
     * Ensure hvac_trainer role has all proper capabilities
     */
    private static function ensure_proper_capabilities() {
        $role = get_role('hvac_trainer');
        
        if (!$role) {
            HVAC_Logger::error('hvac_trainer role not found!', 'Role Consolidator');
            return false;
        }
        
        // Get the proper capabilities from HVAC_Roles class
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-roles.php';
        $roles_manager = new HVAC_Roles();
        $proper_caps = $roles_manager->get_trainer_capabilities();
        
        $updated = 0;
        
        // Add any missing capabilities
        foreach ($proper_caps as $cap => $grant) {
            if ($grant && !$role->has_cap($cap)) {
                $role->add_cap($cap);
                $updated++;
                HVAC_Logger::info("Added capability {$cap} to hvac_trainer role", 'Role Consolidator');
            } elseif (!$grant && $role->has_cap($cap)) {
                $role->remove_cap($cap);
                $updated++;
                HVAC_Logger::info("Removed capability {$cap} from hvac_trainer role", 'Role Consolidator');
            }
        }
        
        return $updated;
    }
    
    /**
     * Clean up permission issues across the plugin
     */
    private static function cleanup_permissions() {
        $cleaned = array();
        
        // Fix capability checks in the codebase
        $capability_mappings = array(
            'event_trainer' => 'hvac_trainer',
            'event_master_trainer' => 'hvac_master_trainer'
        );
        
        // Update user meta that might reference old roles
        global $wpdb;
        
        // Update any user meta that references old role names
        foreach ($capability_mappings as $old_role => $new_role) {
            $query = $wpdb->prepare(
                "UPDATE {$wpdb->usermeta} 
                 SET meta_value = REPLACE(meta_value, %s, %s) 
                 WHERE meta_key = %s 
                 AND meta_value LIKE %s",
                $old_role,
                $new_role,
                $wpdb->prefix . 'capabilities',
                '%' . $wpdb->esc_like($old_role) . '%'
            );
            
            $updated = $wpdb->query($query);
            if ($updated) {
                $cleaned['user_meta_' . $old_role] = $updated;
                HVAC_Logger::info("Updated {$updated} user meta entries from {$old_role} to {$new_role}", 'Role Consolidator');
            }
        }
        
        return $cleaned;
    }
    
    /**
     * Check if consolidation is needed
     */
    public static function needs_consolidation() {
        // Check if event_trainer role exists
        if (get_role('event_trainer')) {
            return true;
        }
        
        // Check if any users still have event_trainer in their capabilities
        $users = get_users(array('role' => 'event_trainer'));
        if (!empty($users)) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Run consolidation check on admin init
     */
    public static function check_and_consolidate() {
        // Only run for admins
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Check if we've already consolidated
        if (get_option('hvac_roles_consolidated_v2', false)) {
            return;
        }
        
        // Check if consolidation is needed
        if (self::needs_consolidation()) {
            $results = self::consolidate_roles();
            
            // Log results
            HVAC_Logger::info('Role consolidation completed: ' . json_encode($results), 'Role Consolidator');
            
            // Mark as consolidated
            update_option('hvac_roles_consolidated_v2', true);
            
            // Show admin notice
            add_action('admin_notices', function() use ($results) {
                ?>
                <div class="notice notice-success is-dismissible">
                    <p><strong>HVAC Roles Consolidated:</strong></p>
                    <ul>
                        <li>Migrated <?php echo intval($results['migration']['migrated']); ?> users to hvac_trainer role</li>
                        <li>Updated <?php echo intval($results['capabilities']); ?> capabilities</li>
                    </ul>
                </div>
                <?php
            });
        }
    }
}

// Hook into admin_init to check and consolidate
add_action('admin_init', array('HVAC_Role_Consolidator', 'check_and_consolidate'));