<?php
/**
 * Plugin Name: HVAC Community Events (Fixed)
 * Plugin URI: https://upskillhvac.com
 * Description: Custom plugin for HVAC trainer event management system (Fixed version)
 * Version: 1.0.0
 * Author: Upskill HVAC
 * Author URI: https://upskillhvac.com
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain: hvac-community-events
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('HVAC_CE_VERSION', '1.0.0');
define('HVAC_CE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('HVAC_CE_PLUGIN_URL', plugin_dir_url(__FILE__));

/**
 * Create required pages upon plugin activation.
 * Fixed version with proper error handling and logging.
 */
function hvac_ce_fixed_activation() {
    // Log the activation process for debugging
    error_log('[HVAC CE] Starting activation process');
    
    // Create a test option
    add_option('hvac_ce_fixed_activated', 'yes');
    
    // Store the current time of activation
    update_option('hvac_ce_fixed_activation_time', current_time('mysql'));
    
    // Define a single test page to create
    $test_page = [
        'post_title'     => 'HVAC Dashboard',
        'post_name'      => 'hvac-dashboard',
        'post_content'   => '<!-- wp:paragraph --><p>This is the HVAC dashboard page.</p><!-- /wp:paragraph -->',
        'post_status'    => 'publish',
        'post_type'      => 'page',
        'comment_status' => 'closed',
        'ping_status'    => 'closed',
    ];
    
    // Check if page already exists by slug
    $existing_page = get_page_by_path('hvac-dashboard', OBJECT, 'page');
    
    // Only create the page if it doesn't exist
    if (empty($existing_page)) {
        // Insert the page
        $page_id = wp_insert_post($test_page);
        
        // Log the result
        if (is_wp_error($page_id)) {
            error_log('[HVAC CE] Error creating dashboard page: ' . $page_id->get_error_message());
        } else {
            error_log('[HVAC CE] Successfully created dashboard page with ID: ' . $page_id);
            
            // Store the page ID in options
            $created_pages = ['dashboard' => $page_id];
            update_option('hvac_ce_fixed_pages', $created_pages);
        }
    } else {
        error_log('[HVAC CE] Dashboard page already exists with ID: ' . $existing_page->ID);
        
        // Store the existing page ID
        $created_pages = ['dashboard' => $existing_page->ID];
        update_option('hvac_ce_fixed_pages', $created_pages);
    }
    
    // Try to create a basic role (without complex classes or dependencies)
    if (!get_role('hvac_trainer_basic')) {
        $capabilities = [
            'read' => true,
            'upload_files' => true,
            'hvac_basic_access' => true
        ];
        
        $role = add_role(
            'hvac_trainer_basic',
            'HVAC Trainer (Basic)',
            $capabilities
        );
        
        if ($role) {
            error_log('[HVAC CE] Created hvac_trainer_basic role');
        } else {
            error_log('[HVAC CE] Failed to create hvac_trainer_basic role');
        }
    } else {
        error_log('[HVAC CE] hvac_trainer_basic role already exists');
    }
    
    // Log activation completion
    error_log('[HVAC CE] Activation process completed');
}
register_activation_hook(__FILE__, 'hvac_ce_fixed_activation');

/**
 * Remove roles and options upon plugin deactivation.
 */
function hvac_ce_fixed_deactivation() {
    // Remove the role
    remove_role('hvac_trainer_basic');
    
    // Log deactivation
    error_log('[HVAC CE] Plugin deactivated, hvac_trainer_basic role removed');
}
register_deactivation_hook(__FILE__, 'hvac_ce_fixed_deactivation');

/**
 * Initialize the plugin
 */
function hvac_ce_fixed_init() {
    // Add admin notice for activation
    if (is_admin()) {
        add_action('admin_notices', 'hvac_ce_fixed_admin_notice');
    }
}
add_action('plugins_loaded', 'hvac_ce_fixed_init');

/**
 * Display admin notice about successful activation
 */
function hvac_ce_fixed_admin_notice() {
    if (get_option('hvac_ce_fixed_activated') === 'yes') {
        ?>
        <div class="notice notice-success is-dismissible">
            <p><?php _e('HVAC Community Events (Fixed) plugin activated successfully!', 'hvac-community-events'); ?></p>
            <p><?php echo sprintf(__('Activated at: %s', 'hvac-community-events'), get_option('hvac_ce_fixed_activation_time')); ?></p>
            <?php
            // Show created pages if any
            $created_pages = get_option('hvac_ce_fixed_pages', []);
            if (!empty($created_pages)) {
                echo '<p>' . __('Created pages:', 'hvac-community-events') . '</p>';
                echo '<ul>';
                foreach ($created_pages as $key => $page_id) {
                    $page = get_post($page_id);
                    if ($page) {
                        echo '<li>' . esc_html($page->post_title) . ' (ID: ' . $page_id . ')</li>';
                    }
                }
                echo '</ul>';
            }
            ?>
        </div>
        <?php
    }
}