<?php
/**
 * Template Loader for HVAC Community Events
 *
 * Handles loading of plugin templates with proper fallback hierarchy
 *
 * @package HVAC_Community_Events
 * @since 1.0.0
 */

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

/**
 * HVAC_Template_Loader class
 */
class HVAC_Template_Loader {
    
    /**
     * Plugin template directory
     * 
     * @var string
     */
    private static $plugin_template_dir = 'templates/';
    
    /**
     * Theme template directory for overrides
     * 
     * @var string
     */
    private static $theme_template_dir = 'hvac-community-events/';
    
    /**
     * Initialize the template loader
     * 
     * @return void
     */
    public static function init() {
        // Hook into template_include to load our templates
        add_filter('template_include', [__CLASS__, 'template_loader']);
        
        // Add body classes for our pages
        add_filter('body_class', [__CLASS__, 'add_body_classes']);
        
        // Hide page titles on HVAC pages
        add_filter('the_title', [__CLASS__, 'hide_page_titles'], 10, 2);
        
        // Also filter post class to add a class for CSS targeting
        add_filter('post_class', [__CLASS__, 'add_no_title_class']);
    }
    
    /**
     * Load the appropriate template
     * 
     * @param string $template The template to load
     * @return string Modified template path
     */
    public static function template_loader($template) {
        if (!is_page()) {
            return $template;
        }
        
        global $post;
        
        // Get the page template from post meta
        $custom_template = get_post_meta($post->ID, '_wp_page_template', true);
        
        if ($custom_template && $custom_template !== 'default') {
            $located = self::locate_template($custom_template);
            if ($located) {
                return $located;
            }
        }
        
        // Check if this is one of our plugin pages
        $page_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        $page_config = HVAC_Page_Manager::get_page_config($page_path);
        
        if ($page_config && !empty($page_config['template'])) {
            $located = self::locate_template($page_config['template']);
            if ($located) {
                return $located;
            }
        }
        
        return $template;
    }
    
    /**
     * Locate a template file
     * 
     * @param string $template_name Template file name
     * @return string|false Template path or false if not found
     */
    public static function locate_template($template_name) {
        // Check theme directory first for overrides
        $theme_template = get_stylesheet_directory() . '/' . self::$theme_template_dir . $template_name;
        if (file_exists($theme_template)) {
            return $theme_template;
        }
        
        // Check parent theme if using child theme
        if (get_template_directory() !== get_stylesheet_directory()) {
            $parent_theme_template = get_template_directory() . '/' . self::$theme_template_dir . $template_name;
            if (file_exists($parent_theme_template)) {
                return $parent_theme_template;
            }
        }
        
        // Check plugin directory
        $plugin_template = HVAC_PLUGIN_DIR . self::$plugin_template_dir . $template_name;
        if (file_exists($plugin_template)) {
            return $plugin_template;
        }
        
        return false;
    }
    
    /**
     * Include a template part
     * 
     * @param string $slug Template slug
     * @param string $name Optional template name
     * @param array $args Optional arguments to pass to template
     * @return void
     */
    public static function get_template_part($slug, $name = '', $args = []) {
        $template = '';
        
        // Look for specific template first
        if ($name) {
            $template = self::locate_template("{$slug}-{$name}.php");
        }
        
        // Fallback to generic template
        if (!$template) {
            $template = self::locate_template("{$slug}.php");
        }
        
        if ($template) {
            // Make args available to the template
            if (!empty($args)) {
                extract($args);
            }
            
            include $template;
        }
    }
    
    /**
     * Get template content as string
     * 
     * @param string $template_name Template file name
     * @param array $args Optional arguments to pass to template
     * @return string Template content
     */
    public static function get_template($template_name, $args = []) {
        $template = self::locate_template($template_name);
        
        if (!$template) {
            return '';
        }
        
        // Make args available to the template
        if (!empty($args)) {
            extract($args);
        }
        
        ob_start();
        include $template;
        return ob_get_clean();
    }
    
    /**
     * Add body classes for plugin pages
     * 
     * @param array $classes Body classes
     * @return array Modified body classes
     */
    public static function add_body_classes($classes) {
        if (!is_page()) {
            return $classes;
        }
        
        global $post;
        
        // Add general plugin class
        $page_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        $page_config = HVAC_Page_Manager::get_page_config($page_path);
        
        if ($page_config) {
            $classes[] = 'hvac-community-events';
            $classes[] = 'hvac-page';
            $classes[] = 'hvac-plugin-page'; // Additional class for CSS targeting
            
            // Add specific page class
            $page_slug = str_replace('/', '-', $page_path);
            $classes[] = 'hvac-page-' . $page_slug;
            
            // Add status-specific classes
            if (strpos($page_path, 'trainer-account-') === 0) {
                $classes[] = 'hvac-status-page';
                
                if (strpos($page_path, 'pending') !== false) {
                    $classes[] = 'hvac-status-pending';
                } elseif (strpos($page_path, 'disabled') !== false) {
                    $classes[] = 'hvac-status-disabled';
                }
            }
            
            // Add role-based classes
            if (strpos($page_path, 'trainer/') === 0) {
                $classes[] = 'hvac-trainer-area';
            } elseif (strpos($page_path, 'master-trainer/') === 0) {
                $classes[] = 'hvac-master-trainer-area';
            }
        }
        
        return $classes;
    }
    
    /**
     * Render a template with dynamic data
     * 
     * @param string $template_name Template file name
     * @param array $data Data to pass to template
     * @return void
     */
    public static function render_template($template_name, $data = []) {
        echo self::get_template($template_name, $data);
    }
    
    /**
     * Check if current page uses a plugin template
     * 
     * @return bool
     */
    public static function is_plugin_template() {
        if (!is_page()) {
            return false;
        }
        
        global $post;
        $custom_template = get_post_meta($post->ID, '_wp_page_template', true);
        
        if ($custom_template && self::locate_template($custom_template)) {
            return true;
        }
        
        $page_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        $page_config = HVAC_Page_Manager::get_page_config($page_path);
        
        return $page_config && !empty($page_config['template']);
    }
    
    /**
     * Hide page titles on HVAC pages
     * 
     * @param string $title The page title
     * @param int $id The post ID
     * @return string Modified title (empty for HVAC pages)
     */
    public static function hide_page_titles($title, $id = null) {
        // Only hide titles in the main query, not in navigation menus or admin
        if (!is_main_query() || is_admin() || !in_the_loop() || !is_page()) {
            return $title;
        }
        
        // Check if this is an HVAC page
        if (self::is_hvac_page()) {
            return ''; // Return empty string to hide the title
        }
        
        return $title;
    }
    
    /**
     * Add no-title class to HVAC pages
     * 
     * @param array $classes Post classes
     * @return array Modified classes
     */
    public static function add_no_title_class($classes) {
        if (is_page() && self::is_hvac_page()) {
            $classes[] = 'hvac-no-title';
            $classes[] = 'entry-title-hidden';
        }
        
        return $classes;
    }
    
    /**
     * Check if current page is an HVAC plugin page
     * 
     * @return bool
     */
    private static function is_hvac_page() {
        if (!is_page()) {
            return false;
        }
        
        global $post;
        
        // Check by page path
        $page_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        $page_config = HVAC_Page_Manager::get_page_config($page_path);
        
        if ($page_config) {
            return true;
        }
        
        // Check by meta key
        $is_plugin_page = get_post_meta($post->ID, '_hvac_plugin_page', true);
        if ($is_plugin_page) {
            return true;
        }
        
        // Check common HVAC page slugs
        $hvac_slugs = [
            'training-login',
            'trainer',
            'trainer-dashboard',
            'trainer-registration',
            'master-trainer',
            'master-trainer-dashboard',
            'trainer-account-pending',
            'trainer-account-disabled',
            'registration-pending'
        ];
        
        if (in_array($post->post_name, $hvac_slugs)) {
            return true;
        }
        
        // Check if page path starts with trainer/ or master-trainer/
        if (strpos($page_path, 'trainer/') === 0 || strpos($page_path, 'master-trainer/') === 0) {
            return true;
        }
        
        return false;
    }
}