<?php
/**
 * HVAC Trainer Communication Templates
 * 
 * Read-only communication templates system for HVAC trainers.
 * Provides view-only access to pre-built communication templates with 
 * copy-to-clipboard functionality and search/filter capabilities.
 *
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

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

class HVAC_Trainer_Communication_Templates {
    
    /**
     * Plugin instance
     * 
     * @var HVAC_Trainer_Communication_Templates
     */
    private static $instance = null;
    
    /**
     * Custom post type name
     */
    const POST_TYPE = 'hvac_comm_template';
    
    /**
     * Category taxonomy name
     */
    const TAXONOMY_CATEGORY = 'hvac_template_category';
    
    /**
     * Channel taxonomy name
     */
    const TAXONOMY_CHANNEL = 'hvac_template_channel';
    
    /**
     * Get plugin instance
     * 
     * @return HVAC_Trainer_Communication_Templates
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        $this->init_hooks();
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        add_action('init', array($this, 'register_post_type'));
        add_action('init', array($this, 'register_taxonomies'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        
        // AJAX handlers for template operations
        add_action('wp_ajax_hvac_get_template_preview', array($this, 'ajax_get_template_preview'));
        add_action('wp_ajax_hvac_search_templates', array($this, 'ajax_search_templates'));
    }
    
    /**
     * Register the communication templates custom post type
     */
    public function register_post_type() {
        $labels = array(
            'name'                  => _x('Communication Templates', 'Post type general name', 'hvac-community-events'),
            'singular_name'         => _x('Communication Template', 'Post type singular name', 'hvac-community-events'),
            'menu_name'             => _x('Communication Templates', 'Admin Menu text', 'hvac-community-events'),
            'name_admin_bar'        => _x('Communication Template', 'Add New on Toolbar', 'hvac-community-events'),
            'add_new'               => __('Add New', 'hvac-community-events'),
            'add_new_item'          => __('Add New Template', 'hvac-community-events'),
            'new_item'              => __('New Template', 'hvac-community-events'),
            'edit_item'             => __('Edit Template', 'hvac-community-events'),
            'view_item'             => __('View Template', 'hvac-community-events'),
            'all_items'             => __('All Templates', 'hvac-community-events'),
            'search_items'          => __('Search Templates', 'hvac-community-events'),
            'parent_item_colon'     => __('Parent Templates:', 'hvac-community-events'),
            'not_found'             => __('No templates found.', 'hvac-community-events'),
            'not_found_in_trash'    => __('No templates found in Trash.', 'hvac-community-events'),
        );
        
        $args = array(
            'labels'                => $labels,
            'public'                => false,
            'publicly_queryable'    => false,
            'show_ui'               => true,
            'show_in_menu'          => false, // We'll add to HVAC admin menu
            'query_var'             => false,
            'rewrite'               => false,
            'capability_type'       => array('hvac_comm_template', 'hvac_comm_templates'),
            'map_meta_cap'          => true,
            'has_archive'           => false,
            'hierarchical'          => false,
            'menu_position'         => null,
            'menu_icon'             => 'dashicons-email',
            'supports'              => array('title', 'editor', 'author', 'custom-fields'),
            'show_in_rest'          => true,
            'rest_base'             => 'hvac-comm-templates',
        );
        
        register_post_type(self::POST_TYPE, $args);
    }
    
    /**
     * Register custom taxonomies
     */
    public function register_taxonomies() {
        // Register Category taxonomy
        $category_labels = array(
            'name'                       => _x('Template Categories', 'taxonomy general name', 'hvac-community-events'),
            'singular_name'              => _x('Template Category', 'taxonomy singular name', 'hvac-community-events'),
            'search_items'               => __('Search Categories', 'hvac-community-events'),
            'all_items'                  => __('All Categories', 'hvac-community-events'),
            'edit_item'                  => __('Edit Category', 'hvac-community-events'),
            'update_item'                => __('Update Category', 'hvac-community-events'),
            'add_new_item'               => __('Add New Category', 'hvac-community-events'),
            'new_item_name'              => __('New Category Name', 'hvac-community-events'),
            'menu_name'                  => __('Categories', 'hvac-community-events'),
        );
        
        register_taxonomy(self::TAXONOMY_CATEGORY, self::POST_TYPE, array(
            'hierarchical'          => true,
            'labels'                => $category_labels,
            'show_ui'               => true,
            'show_admin_column'     => true,
            'query_var'             => false,
            'rewrite'               => false,
            'show_in_rest'          => true,
        ));
        
        // Register Channel taxonomy (email/sms)
        $channel_labels = array(
            'name'                       => _x('Template Channels', 'taxonomy general name', 'hvac-community-events'),
            'singular_name'              => _x('Template Channel', 'taxonomy singular name', 'hvac-community-events'),
            'search_items'               => __('Search Channels', 'hvac-community-events'),
            'all_items'                  => __('All Channels', 'hvac-community-events'),
            'edit_item'                  => __('Edit Channel', 'hvac-community-events'),
            'update_item'                => __('Update Channel', 'hvac-community-events'),
            'add_new_item'               => __('Add New Channel', 'hvac-community-events'),
            'new_item_name'              => __('New Channel Name', 'hvac-community-events'),
            'menu_name'                  => __('Channels', 'hvac-community-events'),
        );
        
        register_taxonomy(self::TAXONOMY_CHANNEL, self::POST_TYPE, array(
            'hierarchical'          => false,
            'labels'                => $channel_labels,
            'show_ui'               => true,
            'show_admin_column'     => true,
            'query_var'             => false,
            'rewrite'               => false,
            'show_in_rest'          => true,
        ));
        
        // Create default terms
        $this->create_default_terms();
    }
    
    /**
     * Create default taxonomy terms
     */
    private function create_default_terms() {
        // Default categories
        $categories = array(
            'pre_event' => 'Pre-Event Communications',
            'event_reminder' => 'Event Reminders', 
            'post_event' => 'Post-Event Follow-up',
            'certificate' => 'Certificate Information',
            'general' => 'General Communications'
        );
        
        foreach ($categories as $slug => $name) {
            if (!term_exists($slug, self::TAXONOMY_CATEGORY)) {
                wp_insert_term($name, self::TAXONOMY_CATEGORY, array('slug' => $slug));
            }
        }
        
        // Default channels
        $channels = array(
            'email' => 'Email',
            'sms' => 'SMS'
        );
        
        foreach ($channels as $slug => $name) {
            if (!term_exists($slug, self::TAXONOMY_CHANNEL)) {
                wp_insert_term($name, self::TAXONOMY_CHANNEL, array('slug' => $slug));
            }
        }
    }
    
    /**
     * Enqueue scripts and styles for communication templates page
     */
    public function enqueue_scripts() {
        // Only enqueue on trainer communication templates page
        if (!$this->is_communication_templates_page()) {
            return;
        }
        
        // CRITICAL FIX: Ensure jQuery is loaded first to prevent "jQuery is not defined" errors
        wp_enqueue_script('jquery');
        
        // Enqueue CSS
        wp_enqueue_style(
            'hvac-trainer-communication-templates',
            HVAC_PLUGIN_URL . 'assets/css/hvac-trainer-communication-templates.css',
            array(),
            HVAC_PLUGIN_VERSION
        );
        
        // CRITICAL FIX: Force jQuery load before dependent script
        wp_enqueue_script('jquery');
        
        // Enqueue JavaScript
        wp_enqueue_script(
            'hvac-trainer-communication-templates',
            HVAC_PLUGIN_URL . 'assets/js/hvac-trainer-communication-templates.js',
            array('jquery'),
            HVAC_PLUGIN_VERSION,
            true
        );
        
        // Localize script
        wp_localize_script('hvac-trainer-communication-templates', 'hvacTrainerTemplates', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_trainer_templates_nonce'),
            'strings' => array(
                'copy' => __('Copy to Clipboard', 'hvac-community-events'),
                'copied' => __('Copied!', 'hvac-community-events'),
                'copyError' => __('Copy failed. Please select and copy manually.', 'hvac-community-events'),
                'loading' => __('Loading...', 'hvac-community-events'),
                'noResults' => __('No templates found matching your criteria.', 'hvac-community-events'),
                'showMore' => __('Show More', 'hvac-community-events'),
                'showLess' => __('Show Less', 'hvac-community-events'),
            )
        ));
    }
    
    /**
     * Check if current page is communication templates page
     */
    private function is_communication_templates_page() {
        global $wp;
        $current_url = home_url(add_query_arg(array(), $wp->request));
        return strpos($current_url, '/trainer/communication-templates') !== false ||
               is_page('communication-templates') ||
               is_page('trainer-communication-templates');
    }
    
    /**
     * Get all communication templates with filtering
     */
    public function get_templates($args = array()) {
        $defaults = array(
            'post_type' => self::POST_TYPE,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'menu_order title',
            'order' => 'ASC',
            'meta_query' => array(),
            'tax_query' => array(),
        );
        
        $args = wp_parse_args($args, $defaults);
        
        $templates = get_posts($args);
        $formatted_templates = array();
        
        foreach ($templates as $template) {
            $categories = wp_get_post_terms($template->ID, self::TAXONOMY_CATEGORY);
            $channels = wp_get_post_terms($template->ID, self::TAXONOMY_CHANNEL);
            
            $formatted_templates[] = array(
                'id' => $template->ID,
                'title' => $template->post_title,
                'content' => $template->post_content,
                'excerpt' => $template->post_excerpt,
                'categories' => $categories,
                'channels' => $channels,
                'allowed_tokens' => get_post_meta($template->ID, '_hvac_allowed_tokens', true),
                'created' => $template->post_date,
                'modified' => $template->post_modified,
            );
        }
        
        return $formatted_templates;
    }
    
    /**
     * Get templates filtered by category
     */
    public function get_templates_by_category($category_slug = '') {
        $args = array();
        
        if (!empty($category_slug)) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => self::TAXONOMY_CATEGORY,
                    'field'    => 'slug',
                    'terms'    => $category_slug,
                ),
            );
        }
        
        return $this->get_templates($args);
    }
    
    /**
     * Get templates filtered by channel
     */
    public function get_templates_by_channel($channel_slug = '') {
        $args = array();
        
        if (!empty($channel_slug)) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => self::TAXONOMY_CHANNEL,
                    'field'    => 'slug',
                    'terms'    => $channel_slug,
                ),
            );
        }
        
        return $this->get_templates($args);
    }
    
    /**
     * Search templates by title and content
     */
    public function search_templates($search_term = '') {
        if (empty($search_term)) {
            return $this->get_templates();
        }
        
        $args = array(
            's' => sanitize_text_field($search_term),
        );
        
        return $this->get_templates($args);
    }
    
    /**
     * Render the communication templates interface
     */
    public function render_templates_interface() {
        // Check permissions
        if (!$this->user_can_view_templates()) {
            return '<div class="hvac-error">' . __('You do not have permission to view communication templates.', 'hvac-community-events') . '</div>';
        }
        
        $templates = $this->get_templates();
        $categories = get_terms(array(
            'taxonomy' => self::TAXONOMY_CATEGORY,
            'hide_empty' => false,
        ));
        $channels = get_terms(array(
            'taxonomy' => self::TAXONOMY_CHANNEL,
            'hide_empty' => false,
        ));
        
        ob_start();
        include HVAC_PLUGIN_DIR . 'templates/partials/trainer-communication-templates-interface.php';
        return ob_get_clean();
    }
    
    /**
     * Check if current user can view templates
     */
    private function user_can_view_templates() {
        if (!is_user_logged_in()) {
            return false;
        }
        
        // Capability-based authorization only (WordPress security best practice)
        // Users must have explicit capability - no role-based fallbacks
        return current_user_can('hvac_trainer_templates_view') || current_user_can('manage_options');
    }
    
    /**
     * AJAX handler for template preview
     */
    public function ajax_get_template_preview() {
        check_ajax_referer('hvac_trainer_templates_nonce', 'nonce');
        
        if (!$this->user_can_view_templates()) {
            wp_send_json_error(array('message' => __('Permission denied.', 'hvac-community-events')));
        }
        
        $template_id = isset($_POST['template_id']) ? intval($_POST['template_id']) : 0;
        
        if (empty($template_id)) {
            wp_send_json_error(array('message' => __('Invalid template ID.', 'hvac-community-events')));
        }
        
        $template = get_post($template_id);
        
        if (!$template || $template->post_type !== self::POST_TYPE) {
            wp_send_json_error(array('message' => __('Template not found.', 'hvac-community-events')));
        }
        
        $categories = wp_get_post_terms($template_id, self::TAXONOMY_CATEGORY);
        $channels = wp_get_post_terms($template_id, self::TAXONOMY_CHANNEL);
        
        wp_send_json_success(array(
            'id' => $template->ID,
            'title' => $template->post_title,
            'content' => $template->post_content,
            'excerpt' => $template->post_excerpt,
            'categories' => $categories,
            'channels' => $channels,
            'allowed_tokens' => get_post_meta($template_id, '_hvac_allowed_tokens', true),
        ));
    }
    
    /**
     * AJAX handler for template search
     */
    public function ajax_search_templates() {
        check_ajax_referer('hvac_trainer_templates_nonce', 'nonce');
        
        if (!$this->user_can_view_templates()) {
            wp_send_json_error(array('message' => __('Permission denied.', 'hvac-community-events')));
        }
        
        $search_term = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
        $category = isset($_POST['category']) ? sanitize_text_field($_POST['category']) : '';
        $channel = isset($_POST['channel']) ? sanitize_text_field($_POST['channel']) : '';
        
        $args = array();
        
        if (!empty($search_term)) {
            $args['s'] = $search_term;
        }
        
        $tax_query = array();
        if (!empty($category)) {
            $tax_query[] = array(
                'taxonomy' => self::TAXONOMY_CATEGORY,
                'field'    => 'slug',
                'terms'    => $category,
            );
        }
        
        if (!empty($channel)) {
            $tax_query[] = array(
                'taxonomy' => self::TAXONOMY_CHANNEL,
                'field'    => 'slug',
                'terms'    => $channel,
            );
        }
        
        if (!empty($tax_query)) {
            $args['tax_query'] = $tax_query;
            if (count($tax_query) > 1) {
                $args['tax_query']['relation'] = 'AND';
            }
        }
        
        $templates = $this->get_templates($args);
        
        wp_send_json_success(array(
            'templates' => $templates,
            'count' => count($templates),
        ));
    }
    
    /**
     * Install default templates
     */
    public function install_default_templates() {
        $default_templates = array(
            array(
                'title' => 'Event Reminder - 24 Hours Before',
                'content' => "Hello [ATTENDEE_NAME],\n\nThis is a friendly reminder that you're registered for [EVENT_TITLE] tomorrow.\n\nEvent Details:\n• Date: [EVENT_DATE]\n• Time: [EVENT_TIME]\n• Location: [EVENT_LOCATION]\n\nPlease bring a valid ID and arrive 15 minutes early for check-in.\n\nIf you have any questions, please don't hesitate to contact me.\n\nBest regards,\n[TRAINER_NAME]\n[BUSINESS_NAME]\n[TRAINER_EMAIL]\n[TRAINER_PHONE]",
                'excerpt' => 'Standard 24-hour event reminder with all essential details',
                'category' => 'event_reminder',
                'channel' => 'email',
                'allowed_tokens' => '[ATTENDEE_NAME], [EVENT_TITLE], [EVENT_DATE], [EVENT_TIME], [EVENT_LOCATION], [TRAINER_NAME], [BUSINESS_NAME], [TRAINER_EMAIL], [TRAINER_PHONE]'
            ),
            array(
                'title' => 'Welcome & Pre-Event Information',
                'content' => "Welcome [ATTENDEE_NAME]!\n\nThank you for registering for [EVENT_TITLE]. I'm excited to have you join us on [EVENT_DATE] at [EVENT_TIME].\n\nTo help you prepare for the training:\n\n✓ Please arrive 15 minutes early for check-in\n✓ Bring a valid photo ID\n✓ Dress comfortably and wear closed-toe shoes\n✓ Bring a notebook and pen for taking notes\n✓ Lunch will be provided\n\nIf you have any questions before the event, please feel free to reach out.\n\nLooking forward to seeing you there!\n\n[TRAINER_NAME]\n[BUSINESS_NAME]\n[TRAINER_EMAIL]\n[TRAINER_PHONE]",
                'excerpt' => 'Welcome message with comprehensive event preparation checklist',
                'category' => 'pre_event',
                'channel' => 'email',
                'allowed_tokens' => '[ATTENDEE_NAME], [EVENT_TITLE], [EVENT_DATE], [EVENT_TIME], [TRAINER_NAME], [BUSINESS_NAME], [TRAINER_EMAIL], [TRAINER_PHONE]'
            ),
            array(
                'title' => 'Thank You & Certificate Information',
                'content' => "Dear [ATTENDEE_NAME],\n\nThank you for attending [EVENT_TITLE] on [EVENT_DATE]. It was great having you participate in the training.\n\nYour certificate of completion will be available within 3-5 business days. You can download it from your attendee profile on our website.\n\nIf you have any questions about the training content or need additional resources, please don't hesitate to contact me.\n\nThank you again for your participation, and I look forward to seeing you at future training events.\n\nBest regards,\n[TRAINER_NAME]\n[BUSINESS_NAME]\n[TRAINER_EMAIL]\n[TRAINER_PHONE]",
                'excerpt' => 'Post-event thank you with certificate availability information',
                'category' => 'post_event',
                'channel' => 'email',
                'allowed_tokens' => '[ATTENDEE_NAME], [EVENT_TITLE], [EVENT_DATE], [TRAINER_NAME], [BUSINESS_NAME], [TRAINER_EMAIL], [TRAINER_PHONE]'
            ),
            array(
                'title' => 'Certificate Ready - Download Available',
                'content' => "Hello [ATTENDEE_NAME],\n\nGreat news! Your certificate of completion for [EVENT_TITLE] is now ready for download.\n\nTo access your certificate:\n1. Visit [WEBSITE_URL]\n2. Log into your attendee profile\n3. Navigate to the 'My Certificates' section\n4. Download your certificate for [EVENT_TITLE]\n\nYour certificate includes:\n• Official completion verification\n• Training date and hours\n• Digital security features\n• Suitable for continuing education records\n\nIf you have any trouble accessing your certificate, please contact me directly.\n\nCongratulations on completing the training!\n\n[TRAINER_NAME]\n[BUSINESS_NAME]\n[TRAINER_EMAIL]\n[TRAINER_PHONE]",
                'excerpt' => 'Certificate ready notification with download instructions',
                'category' => 'certificate',
                'channel' => 'email',
                'allowed_tokens' => '[ATTENDEE_NAME], [EVENT_TITLE], [WEBSITE_URL], [TRAINER_NAME], [BUSINESS_NAME], [TRAINER_EMAIL], [TRAINER_PHONE]'
            ),
            array(
                'title' => 'Event Reminder - SMS',
                'content' => "Hi [ATTENDEE_NAME]! Reminder: [EVENT_TITLE] tomorrow at [EVENT_TIME]. Location: [EVENT_LOCATION]. Please arrive 15 min early with ID. Questions? Reply to this message. - [TRAINER_NAME]",
                'excerpt' => 'Concise SMS reminder for mobile notifications',
                'category' => 'event_reminder',
                'channel' => 'sms',
                'allowed_tokens' => '[ATTENDEE_NAME], [EVENT_TITLE], [EVENT_TIME], [EVENT_LOCATION], [TRAINER_NAME]'
            ),
        );
        
        foreach ($default_templates as $template_data) {
            // Check if template already exists
            $existing = get_posts(array(
                'post_type' => self::POST_TYPE,
                'title' => $template_data['title'],
                'post_status' => 'publish',
                'numberposts' => 1,
            ));
            
            if (!empty($existing)) {
                continue; // Skip if already exists
            }
            
            // Create the template
            $template_id = wp_insert_post(array(
                'post_type' => self::POST_TYPE,
                'post_title' => $template_data['title'],
                'post_content' => $template_data['content'],
                'post_excerpt' => $template_data['excerpt'],
                'post_status' => 'publish',
                'post_author' => 1, // Admin user
            ));
            
            if (!is_wp_error($template_id)) {
                // Set category
                wp_set_post_terms($template_id, array($template_data['category']), self::TAXONOMY_CATEGORY);
                
                // Set channel
                wp_set_post_terms($template_id, array($template_data['channel']), self::TAXONOMY_CHANNEL);
                
                // Set allowed tokens
                update_post_meta($template_id, '_hvac_allowed_tokens', $template_data['allowed_tokens']);
            }
        }
    }
}

// Initialize
HVAC_Trainer_Communication_Templates::instance();