<?php
/**
 * HVAC Community Events - Activation Helper
 * 
 * This file provides robust activation handling for the HVAC Community Events plugin.
 */

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

/**
 * Robust activation function for HVAC Community Events
 */
function hvac_robust_activation() {
    // Set a flag to track activation status
    update_option('hvac_activation_in_progress', 'yes');
    update_option('hvac_activation_start_time', current_time('mysql'));
    
    try {
        // Log activation start
        error_log('[HVAC Activation] Starting plugin activation process');
        
        // STEP 1: Create a minimal dashboard page first
        create_hvac_dashboard_page();
        
        // STEP 2: Create the basic trainer role
        create_hvac_trainer_role();
        
        // STEP 3: Create remaining required pages
        create_hvac_required_pages();
        
        // STEP 4: Set activation success flag
        update_option('hvac_activation_successful', 'yes');
        update_option('hvac_activation_finish_time', current_time('mysql'));
        error_log('[HVAC Activation] Plugin activation completed successfully');
    } 
    catch (Exception $e) {
        // Log activation error
        error_log('[HVAC Activation] ERROR: ' . $e->getMessage());
        update_option('hvac_activation_error', $e->getMessage());
    }
    
    // Clear in-progress flag
    delete_option('hvac_activation_in_progress');
}

/**
 * Create the main dashboard page
 */
function create_hvac_dashboard_page() {
    error_log('[HVAC Activation] Creating dashboard page');
    
    // Check if the page already exists by slug
    $existing_page = get_page_by_path('hvac-dashboard', OBJECT, 'page');
    
    if (!empty($existing_page) && is_object($existing_page)) {
        error_log('[HVAC Activation] Dashboard page already exists with ID: ' . $existing_page->ID);
        $created_pages = get_option('hvac_community_pages', []);
        $created_pages['hvac_dashboard'] = $existing_page->ID;
        update_option('hvac_community_pages', $created_pages);
        return;
    }
    
    // Create the dashboard page
    $page_data = [
        'post_title'     => 'Trainer Dashboard',
        'post_name'      => 'hvac-dashboard',
        'post_content'   => '<!-- wp:shortcode -->[hvac_trainer_dashboard]<!-- /wp:shortcode -->',
        'post_status'    => 'publish',
        'post_type'      => 'page',
        'comment_status' => 'closed',
        'ping_status'    => 'closed',
    ];
    
    $page_id = wp_insert_post($page_data);
    
    if (is_wp_error($page_id)) {
        throw new Exception('Failed to create dashboard page: ' . $page_id->get_error_message());
    }
    
    error_log('[HVAC Activation] Successfully created dashboard page with ID: ' . $page_id);
    
    // Save page ID in options
    $created_pages = get_option('hvac_community_pages', []);
    $created_pages['hvac_dashboard'] = $page_id;
    update_option('hvac_community_pages', $created_pages);
}

/**
 * Create the HVAC trainer role
 */
function create_hvac_trainer_role() {
    error_log('[HVAC Activation] Creating trainer role');
    
    // Check if role already exists
    if (get_role('hvac_trainer')) {
        error_log('[HVAC Activation] Trainer role already exists');
        return;
    }
    
    // Define trainer capabilities
    $caps = array(
        // Basic WordPress capabilities
        'read' => true,
        'upload_files' => true,
        
        // Custom HVAC capabilities
        'manage_hvac_events' => true,
        'edit_hvac_profile' => true,
        'view_hvac_dashboard' => true,
        'manage_attendees' => true,
        'email_attendees' => true,
        
        // The Events Calendar capabilities
        'publish_tribe_events' => true,
        'edit_tribe_events' => true,
        'delete_tribe_events' => true,
        'edit_published_tribe_events' => true,
        'delete_published_tribe_events' => true,
        'read_private_tribe_events' => true,
    );
    
    // Add the role
    $result = add_role(
        'hvac_trainer',
        'HVAC Trainer',
        $caps
    );
    
    if ($result === null) {
        throw new Exception('Failed to create hvac_trainer role');
    }
    
    error_log('[HVAC Activation] Successfully created hvac_trainer role');
}

/**
 * Create all required pages for the plugin
 */
function create_hvac_required_pages() {
    error_log('[HVAC Activation] Creating required pages');
    
    // Define required pages (excluding dashboard, which was created first)
    $required_pages = [
        'community-login' => [
            'title' => 'Trainer Login',
            'content' => '<!-- wp:shortcode -->[hvac_community_login]<!-- /wp:shortcode -->',
            'template' => 'page-community-login.php',
        ],
        'trainer-registration' => [
            'title' => 'Trainer Registration',
            'content' => '<!-- wp:shortcode -->[hvac_trainer_registration]<!-- /wp:shortcode -->',
        ],
        'manage-event' => [
            'title' => 'Manage Event',
            'content' => '<!-- wp:shortcode -->[tribe_community_events view="submission_form"]<!-- /wp:shortcode -->',
        ],
        'trainer-profile' => [
            'title' => 'Trainer Profile',
            'content' => '<!-- wp:shortcode -->[hvac_trainer_profile]<!-- /wp:shortcode -->',
        ],
        'event-summary' => [
            'title' => 'Event Summary',
            'content' => '<!-- wp:shortcode -->[hvac_event_summary]<!-- /wp:shortcode -->',
        ],
        'email-attendees' => [
            'title' => 'Email Attendees',
            'content' => '<!-- wp:shortcode -->[hvac_email_attendees]<!-- /wp:shortcode -->',
        ],
    ];
    
    // Get existing page IDs from options
    $created_pages = get_option('hvac_community_pages', []);
    
    // Create each page one by one
    foreach ($required_pages as $slug => $page_data) {
        try {
            create_single_hvac_page($slug, $page_data, $created_pages);
        } catch (Exception $e) {
            error_log('[HVAC Activation] Error creating page ' . $slug . ': ' . $e->getMessage());
            // Continue with other pages even if one fails
        }
    }
    
    // Update the option with all created pages
    update_option('hvac_community_pages', $created_pages);
}

/**
 * Create a single page safely
 */
function create_single_hvac_page($slug, $page_data, &$created_pages) {
    // Create the feature key
    $feature_key = str_replace('-', '_', $slug);
    
    // Skip if already exists in our option
    if (isset($created_pages[$feature_key]) && get_post($created_pages[$feature_key])) {
        error_log('[HVAC Activation] Page ' . $slug . ' already exists in options with ID: ' . $created_pages[$feature_key]);
        return;
    }
    
    // Check if page already exists by slug
    $existing_page = get_page_by_path($slug, OBJECT, 'page');
    
    // Safe handling of existing page
    if (!empty($existing_page) && is_object($existing_page) && isset($existing_page->ID)) {
        error_log('[HVAC Activation] Page ' . $slug . ' exists with ID: ' . $existing_page->ID);
        $created_pages[$feature_key] = $existing_page->ID;
        return;
    }
    
    // Page doesn't exist, create it
    error_log('[HVAC Activation] Creating page: ' . $slug);
    
    $post_data = [
        'post_title'     => $page_data['title'],
        'post_name'      => $slug,
        'post_content'   => $page_data['content'],
        'post_status'    => 'publish',
        'post_type'      => 'page',
        'comment_status' => 'closed',
        'ping_status'    => 'closed',
    ];
    
    // Add template if specified
    if (!empty($page_data['template'])) {
        $post_data['page_template'] = $page_data['template'];
    }
    
    // Insert the page
    $page_id = wp_insert_post($post_data);
    
    // Handle the result
    if (is_wp_error($page_id)) {
        throw new Exception('Error creating page ' . $slug . ': ' . $page_id->get_error_message());
    } elseif (!empty($page_id)) {
        error_log('[HVAC Activation] Successfully created page ' . $slug . ' with ID: ' . $page_id);
        $created_pages[$feature_key] = $page_id;
    }
}

/**
 * Show admin notice for activation status
 */
function hvac_activation_admin_notice() {
    // Show only on plugin pages
    $screen = get_current_screen();
    if (!in_array($screen->id, ['plugins', 'dashboard'])) {
        return;
    }
    
    // Check if activation was successful
    if (get_option('hvac_activation_successful') === 'yes') {
        ?>
        <div class="notice notice-success is-dismissible">
            <p><strong>HVAC Community Events:</strong> Plugin activated successfully!</p>
            <p>Activation completed at: <?php echo esc_html(get_option('hvac_activation_finish_time')); ?></p>
            <?php
            // Show created pages
            $created_pages = get_option('hvac_community_pages', []);
            if (!empty($created_pages)) {
                echo '<p>Created pages:</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
        
        // Clear success flag after showing once
        delete_option('hvac_activation_successful');
    }
    
    // Show activation error if any
    $activation_error = get_option('hvac_activation_error', '');
    if (!empty($activation_error)) {
        ?>
        <div class="notice notice-error is-dismissible">
            <p><strong>HVAC Community Events:</strong> Plugin activation encountered an error:</p>
            <p><?php echo esc_html($activation_error); ?></p>
            <p>Please deactivate and reactivate the plugin to try again.</p>
        </div>
        <?php
        
        // Clear error after showing once
        delete_option('hvac_activation_error');
    }
    
    // Show if activation is in progress (shouldn't happen, but just in case)
    if (get_option('hvac_activation_in_progress') === 'yes') {
        ?>
        <div class="notice notice-warning is-dismissible">
            <p><strong>HVAC Community Events:</strong> Plugin activation appears to be in progress.</p>
            <p>Started at: <?php echo esc_html(get_option('hvac_activation_start_time')); ?></p>
            <p>If this message persists, please deactivate and reactivate the plugin.</p>
        </div>
        <?php
    }
}
add_action('admin_notices', 'hvac_activation_admin_notice');