<?php
/**
 * HVAC Page Manager V2 - Template System Overhaul
 * 
 * New page manager using base template system with minimal hardcoded assignments
 * 
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

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

class HVAC_Page_Manager_V2 {
    
    /**
     * Simplified page definitions - no hardcoded templates for most pages
     * 
     * @var array
     */
    private static $pages = [
        // Public pages
        'community-login' => [
            'title' => 'Trainer Login',
            'template' => 'page-hvac-public.php', // Uses specialized template
            'public' => true,
            'parent' => null
        ],
        'find-a-trainer' => [
            'title' => 'Find a Trainer',
            'template' => 'page-hvac-public.php', // Uses specialized template
            'public' => true,
            'parent' => null
        ],
        'trainer/registration' => [
            'title' => 'Trainer Registration',
            'template' => 'page-hvac-form.php', // Uses specialized form template
            'public' => true,
            'parent' => null
        ],
        'registration-pending' => [
            'title' => 'Registration Pending',
            'template' => 'page-hvac-status.php', // Uses specialized status template
            'public' => true,
            'parent' => null
        ],
        
        // Trainer hierarchy pages (parent containers)
        'trainer' => [
            'title' => 'Trainer',
            'template' => null, // No template needed - just for hierarchy
            'public' => false,
            'parent' => null
        ],
        'trainer/venue' => [
            'title' => 'Venues',
            'template' => null,
            'public' => false,
            'parent' => 'trainer'
        ],
        'trainer/organizer' => [
            'title' => 'Organizers',
            'template' => null,
            'public' => false,
            'parent' => 'trainer'
        ],
        'trainer/event' => [
            'title' => 'Events',
            'template' => null,
            'public' => false,
            'parent' => 'trainer'
        ],
        'trainer/profile' => [
            'title' => 'Profile',
            'template' => null,
            'public' => false,
            'parent' => 'trainer'
        ],
        
        // Complex pages that need specialized templates
        'trainer/dashboard' => [
            'title' => 'Trainer Dashboard',
            'template' => 'page-hvac-dashboard.php',
            'public' => false,
            'parent' => 'trainer'
        ],
        'trainer/profile/view' => [
            'title' => 'View Profile',
            'template' => 'page-hvac-profile.php',
            'public' => false,
            'parent' => 'trainer/profile'
        ],
        'trainer/account-pending' => [
            'title' => 'Account Pending Approval',
            'template' => 'page-hvac-status.php',
            'public' => false,
            'parent' => null
        ],
        'trainer/account-disabled' => [
            'title' => 'Account Access Restricted',
            'template' => 'page-hvac-status.php',
            'public' => false,
            'parent' => null
        ],
        'trainer/event/create' => [
            'title' => 'Create Event',
            'template' => 'page-hvac-form.php',
            'public' => false,
            'parent' => 'trainer/event'
        ],
        'trainer/event/edit' => [
            'title' => 'Edit Event',
            'template' => 'page-hvac-form.php',
            'public' => false,
            'parent' => 'trainer/event'
        ],
        
        // Master trainer pages
        'master-trainer' => [
            'title' => 'Master Trainer',
            'template' => null,
            'public' => false,
            'parent' => null
        ],
        'master-trainer/master-dashboard' => [
            'title' => 'Master Dashboard',
            'template' => 'page-hvac-dashboard.php',
            'public' => false,
            'parent' => 'master-trainer'
        ],
        
        // All other pages use the base template via HVAC_Template_Router
        // No need to define them here - they're handled automatically
    ];
    
    /**
     * Create required pages
     */
    public static function create_required_pages() {
        foreach (self::$pages as $slug => $config) {
            self::create_page($slug, $config);
        }
        
        // Flush rewrite rules after creating pages
        flush_rewrite_rules();
    }
    
    /**
     * Create a single page
     * 
     * @param string $slug
     * @param array $config
     * @return int|false Page ID or false on failure
     */
    private static function create_page($slug, $config) {
        // Check if page already exists
        $existing_page = get_page_by_path($slug);
        if ($existing_page) {
            // Update template if needed
            self::update_page_template($existing_page->ID, $config);
            return $existing_page->ID;
        }
        
        // Parse slug for parent
        $parent_id = 0;
        if (!empty($config['parent'])) {
            $parent_page = get_page_by_path($config['parent']);
            if ($parent_page) {
                $parent_id = $parent_page->ID;
            }
        }
        
        // Create page
        $page_data = [
            'post_title' => $config['title'],
            'post_name' => $slug,
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_parent' => $parent_id,
            'comment_status' => 'closed',
            'ping_status' => 'closed'
        ];
        
        $page_id = wp_insert_post($page_data);
        
        if ($page_id && !is_wp_error($page_id)) {
            // Set template only for pages that need specialized templates
            self::update_page_template($page_id, $config);
            
            // Set Astra theme layout to full-width for all HVAC pages
            update_post_meta($page_id, 'site-sidebar-layout', 'no-sidebar');
            update_post_meta($page_id, 'site-content-layout', 'full-width');
            
            return $page_id;
        }
        
        return false;
    }
    
    /**
     * Update page template assignment
     * 
     * @param int $page_id
     * @param array $config
     */
    private static function update_page_template($page_id, $config) {
        if (!empty($config['template'])) {
            // Only set template for pages that explicitly need specialized templates
            update_post_meta($page_id, '_wp_page_template', 'templates/' . $config['template']);
        } else {
            // Use base template for simple pages
            update_post_meta($page_id, '_wp_page_template', 'templates/page-hvac-base.php');
        }
    }
    
    /**
     * Get page configuration by slug
     * 
     * @param string $slug
     * @return array|null
     */
    public static function get_page_config($slug) {
        return self::$pages[$slug] ?? null;
    }
    
    /**
     * Check if a page exists in our registry
     * 
     * @param string $slug
     * @return bool
     */
    public static function is_hvac_page($slug) {
        return isset(self::$pages[$slug]) || HVAC_Template_Router::can_use_base_template($slug);
    }
    
    /**
     * Get all page configurations
     * 
     * @return array
     */
    public static function get_all_pages() {
        return self::$pages;
    }
    
    /**
     * Add a page configuration dynamically
     * 
     * @param string $slug
     * @param array $config
     */
    public static function register_page($slug, $config) {
        self::$pages[$slug] = $config;
    }
    
    /**
     * Remove duplicate pages from old system
     */
    public static function cleanup_old_pages() {
        // Pages that should be removed (duplicates or obsolete)
        $pages_to_remove = [
            'trainer/my-profile', // Replaced by trainer/profile/view
            'training-login',     // Renamed to community-login
        ];
        
        foreach ($pages_to_remove as $slug) {
            $page = get_page_by_path($slug);
            if ($page) {
                wp_delete_post($page->ID, true); // Force delete
            }
        }
    }
    
    /**
     * Migrate pages from old template system to new base template system
     */
    public static function migrate_to_base_templates() {
        // Pages that should use base template instead of individual templates
        $base_template_pages = [
            'trainer/certificate-reports',
            'trainer/generate-certificates',
            'trainer/profile/edit',
            'trainer/venue/list',
            'trainer/venue/manage',
            'trainer/organizer/list',
            'trainer/organizer/manage',
            'trainer/profile/training-leads',
            'trainer/announcements',
            'trainer/resources',
            'trainer/documentation',
            'trainer/email-attendees',
            'trainer/communication-templates',
            'trainer/communication-schedules',
            'trainer/event/summary',
            'trainer/event/manage',
            'master-trainer/announcements',
            'master-trainer/manage-announcements'
        ];
        
        foreach ($base_template_pages as $slug) {
            $page = get_page_by_path($slug);
            if ($page) {
                // Switch to base template
                update_post_meta($page->ID, '_wp_page_template', 'templates/page-hvac-base.php');
                
                // Ensure page configuration is registered with router
                HVAC_Template_Router::register_page_config($slug, [
                    'render_method' => 'shortcode',
                    'show_navigation' => true,
                    'show_breadcrumbs' => true,
                    'menu_type' => strpos($slug, 'master-trainer/') === 0 ? 'master_trainer' : 'trainer'
                ]);
            }
        }
        
        // Flush rewrite rules
        flush_rewrite_rules();
    }
}