<?php

declare(strict_types=1);

/**
 * HVAC TEC Integration
 * 
 * Handles integration between HVAC plugin and The Events Calendar Community Events
 * Provides seamless event management experience for trainers
 */

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

class HVAC_TEC_Integration {
    
    /**
     * Instance
     */
    private static $instance = null;
    
    /**
     * Get instance
     */
    public static function instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Add hooks
        add_action('init', [$this, 'setup_redirects']);
        add_action('template_redirect', [$this, 'handle_event_redirects']);
        add_filter('page_template', [$this, 'load_tec_templates']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_integration_styles']);
        
        // Create pages if they don't exist
        add_action('init', [$this, 'create_tec_pages'], 20);
        
        // Add rewrite rules for clean URLs
        add_action('init', [$this, 'add_rewrite_rules']);
        
        // Filter TEC output to add our navigation
        add_filter('tribe_events_community_shortcode_login_form', [$this, 'customize_login_redirect']);
        
        // Handle AJAX for better integration
        add_action('wp_ajax_hvac_tec_event_created', [$this, 'handle_event_created']);
        add_action('wp_ajax_hvac_tec_event_updated', [$this, 'handle_event_updated']);
    }
    
    /**
     * Setup redirects from old URLs to new integrated pages
     */
    public function setup_redirects() {
        // Only do redirects if we're on a relevant page
        if (!is_admin()) {
            $this->register_redirect_rules();
        }
    }
    
    /**
     * Register redirect rules
     */
    private function register_redirect_rules() {
        // Map old URLs to new ones
        $redirects = [
            // Old custom pages to new integrated pages
            'trainer/event/create' => 'trainer/events/create',
            'trainer/create-event' => 'trainer/events/create',
            'trainer/add-event' => 'trainer/events/create',
            
            // Edit event redirects (handled dynamically in handle_event_redirects)
            
            // Manage page redirect
            'trainer/event/manage' => 'trainer/events/manage',
            
            // Direct TEC URLs to our integrated pages
            'events/network/add' => 'trainer/events/create',
            'events/network' => 'trainer/events/my-events',
        ];
        
        foreach ($redirects as $old => $new) {
            add_rewrite_rule(
                '^' . $old . '/?$',
                'index.php?pagename=' . $new,
                'top'
            );
        }
    }
    
    /**
     * Handle event-specific redirects
     */
    public function handle_event_redirects() {
        global $wp;
        
        $current_url = home_url($wp->request);
        $path = trim(parse_url($current_url, PHP_URL_PATH) ?? '', '/');
        
        // Redirect old edit URLs to new integrated edit pages
        if (preg_match('#trainer/edit-event/(\d+)#', $path, $matches)) {
            wp_redirect(home_url('/trainer/events/edit/' . $matches[1] . '/'), 301);
            exit;
        }
        
        // Redirect TEC edit URLs to our integrated pages
        if (preg_match('#events/network/edit/(\d+)#', $path, $matches)) {
            wp_redirect(home_url('/trainer/events/edit/' . $matches[1] . '/'), 301);
            exit;
        }
        
        // Redirect base trainer page to event management
        if ($path === 'trainer/event' || $path === 'trainer/events') {
            wp_redirect(home_url('/trainer/events/manage/'), 301);
            exit;
        }
    }
    
    /**
     * Load TEC integration templates
     */
    public function load_tec_templates($template) {
        // Check if we're on one of our event pages
        if (is_page()) {
            $page_slug = get_post_field('post_name', get_the_ID());
            
            $template_map = [
                'create' => 'page-tec-create-event.php',
                'edit' => 'page-tec-edit-event.php',
                'my-events' => 'page-tec-my-events.php',
                'manage' => 'page-manage-event-integrated.php'
            ];
            
            // Check parent slug for hierarchical pages
            $parent_id = wp_get_post_parent_id(get_the_ID());
            if ($parent_id) {
                $parent_slug = get_post_field('post_name', $parent_id);
                
                // Check if this is under trainer/events/
                if ($parent_slug === 'events') {
                    $grandparent_id = wp_get_post_parent_id($parent_id);
                    if ($grandparent_id) {
                        $grandparent_slug = get_post_field('post_name', $grandparent_id);
                        
                        if ($grandparent_slug === 'trainer' && isset($template_map[$page_slug])) {
                            $custom_template = HVAC_PLUGIN_DIR . 'templates/' . $template_map[$page_slug];
                            if (file_exists($custom_template)) {
                                return $custom_template;
                            }
                        }
                    }
                }
            }
        }
        
        return $template;
    }
    
    /**
     * Create TEC integration pages
     */
    public function create_tec_pages() {
        // Check if pages already exist
        $trainer_page = get_page_by_path('trainer');
        if (!$trainer_page) {
            return; // Trainer page doesn't exist, skip
        }
        
        // Check/create events parent page
        $events_page = get_page_by_path('trainer/events');
        if (!$events_page) {
            $events_page_id = wp_insert_post([
                'post_title' => 'Events',
                'post_name' => 'events',
                'post_status' => 'publish',
                'post_type' => 'page',
                'post_parent' => $trainer_page->ID,
                'post_content' => ''
            ]);
        } else {
            $events_page_id = $events_page->ID;
        }
        
        // Create sub-pages
        $pages = [
            'create' => [
                'title' => 'Create Event',
                'template' => 'page-tec-create-event.php'
            ],
            'edit' => [
                'title' => 'Edit Event',
                'template' => 'page-tec-edit-event.php'
            ],
            'my-events' => [
                'title' => 'My Events',
                'template' => 'page-tec-my-events.php'
            ],
            'manage' => [
                'title' => 'Manage Events',
                'template' => 'page-manage-event-integrated.php'
            ],
        ];
        
        foreach ($pages as $slug => $page_data) {
            $page = get_page_by_path('trainer/events/' . $slug);
            
            if (!$page) {
                $page_id = wp_insert_post([
                    'post_title' => $page_data['title'],
                    'post_name' => $slug,
                    'post_status' => 'publish',
                    'post_type' => 'page',
                    'post_parent' => $events_page_id,
                    'post_content' => '',
                    'meta_input' => [
                        '_wp_page_template' => 'templates/' . $page_data['template']
                    ]
                ]);
            }
        }
    }
    
    /**
     * Add rewrite rules for clean URLs
     */
    public function add_rewrite_rules() {
        // Add rule for edit with event ID
        add_rewrite_rule(
            '^trainer/events/edit/([0-9]+)/?$',
            'index.php?pagename=trainer/events/edit&event_id=$matches[1]',
            'top'
        );
    }
    
    /**
     * Enqueue integration styles
     */
    public function enqueue_integration_styles() {
        if ($this->is_tec_integration_page()) {
            wp_enqueue_style(
                'hvac-tec-integration',
                HVAC_PLUGIN_URL . 'assets/css/hvac-tec-integration.css',
                [],
                HVAC_VERSION
            );
            
            // Add inline styles for better integration
            $inline_css = '
                /* Hide TEC default navigation if our menu is shown */
                .hvac-navigation-wrapper + .tribe-community-events .tribe-events-community-nav {
                    display: none;
                }
                
                /* Style TEC forms to match HVAC design */
                .hvac-tec-wrapper .tribe-community-events input[type="text"],
                .hvac-tec-wrapper .tribe-community-events textarea {
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    padding: 10px;
                }
                
                /* Hide duplicate headers */
                .hvac-tec-wrapper .tribe-community-events h2:first-child {
                    display: none;
                }
            ';
            
            wp_add_inline_style('hvac-tec-integration', $inline_css);
        }
    }
    
    /**
     * Check if current page is a TEC integration page
     */
    private function is_tec_integration_page() {
        global $wp;
        
        if (!is_page()) {
            return false;
        }
        
        $current_url = home_url(add_query_arg([], $wp->request));
        $integration_patterns = [
            '/trainer/events/',
            '/trainer/event/',
            '/events/network/'
        ];
        
        foreach ($integration_patterns as $pattern) {
            if (strpos($current_url, $pattern) !== false) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Customize login redirect for TEC
     */
    public function customize_login_redirect($html) {
        // Redirect to our login page instead of default WP login
        $html = str_replace(
            wp_login_url(),
            home_url('/training-login/'),
            $html
        );
        
        return $html;
    }
    
    /**
     * Handle event created via AJAX
     */
    public function handle_event_created() {
        check_ajax_referer('hvac_ajax_nonce', 'nonce');
        
        $event_id = isset($_POST['event_id']) ? intval($_POST['event_id']) : 0;
        
        if ($event_id) {
            // Track event creation
            update_user_meta(get_current_user_id(), 'hvac_last_event_created', $event_id);
            
            wp_send_json_success([
                'redirect' => home_url('/trainer/events/edit/' . $event_id . '/?created=1')
            ]);
        }
        
        wp_send_json_error('No event ID provided');
    }
    
    /**
     * Handle event updated via AJAX
     */
    public function handle_event_updated() {
        check_ajax_referer('hvac_ajax_nonce', 'nonce');
        
        $event_id = isset($_POST['event_id']) ? intval($_POST['event_id']) : 0;
        
        if ($event_id) {
            wp_send_json_success([
                'message' => 'Event updated successfully'
            ]);
        }
        
        wp_send_json_error('No event ID provided');
    }
}

// Initialize
HVAC_TEC_Integration::instance();