<?php
/**
 * HVAC Master Pages Fixer
 * 
 * Ensures master trainer pages have the correct shortcodes
 */

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

class HVAC_Master_Pages_Fixer {
    
    /**
     * Fix master trainer pages by adding shortcodes
     */
    public static function fix_pages() {
        // Define the pages and their shortcodes
        $pages_to_fix = array(
            'master-trainer/trainers' => array(
                'title' => 'All Trainers',
                'shortcode' => '[hvac_master_trainers]'
            ),
            'master-trainer/events' => array(
                'title' => 'Events Overview', 
                'shortcode' => '[hvac_master_events]'
            ),
            'master-trainer/pending-approvals' => array(
                'title' => 'Pending Approvals',
                'shortcode' => '[hvac_pending_approvals]'
            ),
            'master-trainer/announcements' => array(
                'title' => 'Announcements',
                'shortcode' => '[hvac_announcements_timeline]'
            )
        );
        
        $results = array();
        
        // Process each page
        foreach ($pages_to_fix as $slug => $page_data) {
            // Find the page by path
            $page = get_page_by_path($slug);
            
            if ($page) {
                // Check if content is empty or doesn't contain the shortcode
                if (empty($page->post_content) || strpos($page->post_content, $page_data['shortcode']) === false) {
                    // Update the page content with the shortcode
                    $update_data = array(
                        'ID' => $page->ID,
                        'post_content' => $page_data['shortcode']
                    );
                    
                    $result = wp_update_post($update_data);
                    
                    if ($result) {
                        $results[] = "✅ Updated page '{$page_data['title']}' (ID: {$page->ID}) with shortcode";
                        error_log("HVAC: Updated master page '{$page_data['title']}' with shortcode {$page_data['shortcode']}");
                    } else {
                        $results[] = "❌ Failed to update page '{$page_data['title']}'";
                        error_log("HVAC: Failed to update master page '{$page_data['title']}'");
                    }
                } else {
                    $results[] = "✓ Page '{$page_data['title']}' already has correct shortcode";
                }
            } else {
                // Page doesn't exist, create it
                $parent_page = get_page_by_path('master-trainer');
                $parent_id = $parent_page ? $parent_page->ID : 0;
                
                // Extract the last part of the slug for the page slug
                $parts = explode('/', $slug);
                $page_slug = end($parts);
                
                $new_page = array(
                    'post_title' => $page_data['title'],
                    'post_content' => $page_data['shortcode'],
                    'post_status' => 'publish',
                    'post_type' => 'page',
                    'post_parent' => $parent_id,
                    'post_name' => $page_slug,
                    'meta_input' => array(
                        '_wp_page_template' => 'default'
                    )
                );
                
                $page_id = wp_insert_post($new_page);
                
                if ($page_id && !is_wp_error($page_id)) {
                    $results[] = "✅ Created page '{$page_data['title']}' (ID: {$page_id})";
                    error_log("HVAC: Created master page '{$page_data['title']}' with shortcode {$page_data['shortcode']}");
                } else {
                    $error = is_wp_error($page_id) ? $page_id->get_error_message() : 'Unknown error';
                    $results[] = "❌ Failed to create page '{$page_data['title']}': {$error}";
                    error_log("HVAC: Failed to create master page '{$page_data['title']}': {$error}");
                }
            }
        }
        
        // Flush rewrite rules
        flush_rewrite_rules();
        
        return $results;
    }
    
    /**
     * Hook to run on plugin activation
     */
    public static function activate() {
        self::fix_pages();
    }
    
    /**
     * Hook to check pages on init
     */
    public static function check_pages() {
        // Only run once per day to avoid performance impact
        $last_check = get_option('hvac_master_pages_last_check', 0);
        $now = time();
        
        if ($now - $last_check > DAY_IN_SECONDS) {
            self::fix_pages();
            update_option('hvac_master_pages_last_check', $now);
        }
    }
}