<?php
/**
 * Helper script to create or refresh the trainer-profile page
 * 
 * This can be run using wp-cli with:
 * wp --path=/path/to/wordpress eval-file create-trainer-profile-page.php
 */

// Bootstrap WordPress
if (!defined('ABSPATH')) {
    // Load WordPress core if not loaded
    require_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/wp-load.php');
}

// Check if the trainer-profile page exists
$existing_page = get_page_by_path('trainer-profile', OBJECT, 'page');

// Page data
$page_data = [
    'post_title'   => 'Trainer Profile',
    'post_name'    => 'trainer-profile',
    'post_content' => '<!-- wp:shortcode -->[hvac_trainer_profile]<!-- /wp:shortcode -->',
    'post_status'  => 'publish',
    'post_type'    => 'page',
    'comment_status' => 'closed',
    'ping_status'  => 'closed',
];

if (!$existing_page) {
    // Create new page
    $page_id = wp_insert_post($page_data);
    if (is_wp_error($page_id)) {
        echo "Error creating trainer-profile page: " . $page_id->get_error_message() . "\n";
    } else {
        echo "Successfully created trainer-profile page with ID: $page_id\n";
        
        // Update the HVAC community pages option
        $created_pages_option = 'hvac_community_pages';
        $created_pages = get_option($created_pages_option, []);
        $created_pages['trainer_profile'] = $page_id;
        update_option($created_pages_option, $created_pages);
        echo "Updated hvac_community_pages option with the new page ID\n";
    }
} else {
    // Update existing page
    $page_data['ID'] = $existing_page->ID;
    $page_id = wp_update_post($page_data);
    
    if (is_wp_error($page_id)) {
        echo "Error updating trainer-profile page: " . $page_id->get_error_message() . "\n";
    } else {
        echo "Successfully updated trainer-profile page with ID: $page_id\n";
        
        // Ensure the page is in the HVAC community pages option
        $created_pages_option = 'hvac_community_pages';
        $created_pages = get_option($created_pages_option, []);
        if (!isset($created_pages['trainer_profile']) || $created_pages['trainer_profile'] != $page_id) {
            $created_pages['trainer_profile'] = $page_id;
            update_option($created_pages_option, $created_pages);
            echo "Updated hvac_community_pages option with the page ID\n";
        }
    }
}

// Flush rewrite rules to ensure the page is accessible
flush_rewrite_rules();
echo "Flushed rewrite rules\n";

echo "Done!\n";