<?php
/**
 * HVAC Community Events - Communication Templates Management
 *
 * Handles creation, storage, and management of email templates for trainers.
 *
 * @package HVAC_Community_Events
 * @subpackage Communication
 * @version 1.0.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class HVAC_Communication_Templates
 *
 * Manages email templates for trainers to use when communicating with attendees.
 */
class HVAC_Communication_Templates {

    /**
     * Template post type name
     */
    const POST_TYPE = 'hvac_email_template';

    /**
     * Available template placeholders
     */
    const PLACEHOLDERS = array(
        '{attendee_name}' => 'Attendee Name',
        '{event_title}' => 'Event Title', 
        '{event_date}' => 'Event Date',
        '{event_time}' => 'Event Time',
        '{event_location}' => 'Event Location',
        '{trainer_name}' => 'Trainer Name',
        '{business_name}' => 'Business Name',
        '{trainer_email}' => 'Trainer Email',
        '{trainer_phone}' => 'Trainer Phone',
        '{current_date}' => 'Current Date',
        '{website_name}' => 'Website Name',
        '{website_url}' => 'Website URL'
    );

    /**
     * Default template categories
     */
    const DEFAULT_CATEGORIES = array(
        'pre_event' => 'Pre-Event Communications',
        'event_reminder' => 'Event Reminders',
        'post_event' => 'Post-Event Follow-up',
        'certificate' => 'Certificate Information',
        'general' => 'General Communications'
    );

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'init', array( $this, 'register_post_type' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'wp_ajax_hvac_save_template', array( $this, 'ajax_save_template' ) );
        add_action( 'wp_ajax_hvac_load_template', array( $this, 'ajax_load_template' ) );
        add_action( 'wp_ajax_hvac_delete_template', array( $this, 'ajax_delete_template' ) );
        add_action( 'wp_ajax_hvac_get_templates', array( $this, 'ajax_get_templates' ) );
        
        // Debug logging
        if ( class_exists( 'HVAC_Logger' ) ) {
            HVAC_Logger::info( 'HVAC_Communication_Templates class instantiated', 'Templates' );
        }
    }

    /**
     * Register the email template custom post type
     */
    public function register_post_type() {
        $args = array(
            'label' => __( 'Email Templates', 'hvac-community-events' ),
            'labels' => array(
                'name' => __( 'Email Templates', 'hvac-community-events' ),
                'singular_name' => __( 'Email Template', 'hvac-community-events' ),
            ),
            'public' => false,
            'publicly_queryable' => false,
            'show_ui' => false,
            'show_in_menu' => false,
            'show_in_rest' => true, // Enable REST API access
            'rest_base' => 'hvac_email_templates',
            'rest_controller_class' => 'WP_REST_Posts_Controller',
            'supports' => array( 'title', 'editor', 'author' ),
            'capability_type' => 'post',
            'capabilities' => array(
                'create_posts' => 'edit_posts',
                'delete_posts' => 'delete_posts',
                'delete_others_posts' => 'delete_others_posts',
                'delete_private_posts' => 'delete_private_posts',
                'delete_published_posts' => 'delete_published_posts',
                'edit_posts' => 'edit_posts',
                'edit_others_posts' => 'edit_others_posts',
                'edit_private_posts' => 'edit_private_posts',
                'edit_published_posts' => 'edit_published_posts',
                'publish_posts' => 'publish_posts',
                'read_private_posts' => 'read_private_posts',
            ),
            'hierarchical' => false,
            'has_archive' => false,
            'rewrite' => false,
        );

        register_post_type( self::POST_TYPE, $args );
    }

    /**
     * Enqueue scripts for template management
     */
    public function enqueue_scripts() {
        global $post;
        
        // Check if we're on a relevant page
        $should_enqueue = false;
        
        if ( is_a( $post, 'WP_Post' ) ) {
            // Check for shortcodes
            if ( has_shortcode( $post->post_content, 'hvac_email_attendees' ) ||
                 has_shortcode( $post->post_content, 'hvac_communication_templates' ) ) {
                $should_enqueue = true;
            }
            
            // Also check by page slug
            if ( $post->post_name === 'communication-templates' || $post->post_name === 'email-attendees' ) {
                $should_enqueue = true;
            }
        }
        
        // Also check if we're on specific pages by is_page
        if ( is_page( 'communication-templates' ) || is_page( 'email-attendees' ) ) {
            $should_enqueue = true;
        }
        
        if ( $should_enqueue ) {
            // Debug logging
            if ( class_exists( 'HVAC_Logger' ) ) {
                HVAC_Logger::info( 'Enqueuing template scripts and styles', 'Templates' );
            }
            
            wp_enqueue_script(
                'hvac-communication-templates',
                HVAC_PLUGIN_URL . 'assets/js/communication-templates.js',
                array( 'jquery' ),
                HVAC_PLUGIN_VERSION,
                true
            );

            wp_localize_script( 'hvac-communication-templates', 'hvacTemplates', array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'nonce' => wp_create_nonce( 'hvac_templates_nonce' ),
                'placeholders' => self::PLACEHOLDERS,
                'categories' => self::DEFAULT_CATEGORIES,
                'strings' => array(
                    'saveTemplate' => __( 'Save Template', 'hvac-community-events' ),
                    'templateSaved' => __( 'Template saved successfully', 'hvac-community-events' ),
                    'templateDeleted' => __( 'Template deleted successfully', 'hvac-community-events' ),
                    'confirmDelete' => __( 'Are you sure you want to delete this template?', 'hvac-community-events' ),
                    'error' => __( 'An error occurred. Please try again.', 'hvac-community-events' ),
                    'templateName' => __( 'Template Name', 'hvac-community-events' ),
                    'selectCategory' => __( 'Select Category', 'hvac-community-events' ),
                    'insertPlaceholder' => __( 'Insert Placeholder', 'hvac-community-events' ),
                )
            ) );

            wp_enqueue_style(
                'hvac-communication-templates',
                HVAC_PLUGIN_URL . 'assets/css/communication-templates.css',
                array(),
                HVAC_PLUGIN_VERSION
            );
        }
    }

    /**
     * Get templates for a specific user
     *
     * @param int $user_id User ID (defaults to current user)
     * @param string $category Optional category filter
     * @return array Array of templates
     */
    public function get_user_templates( $user_id = 0, $category = '' ) {
        if ( empty( $user_id ) ) {
            $user_id = get_current_user_id();
        }

        $args = array(
            'post_type' => self::POST_TYPE,
            'author' => $user_id,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC',
        );

        if ( ! empty( $category ) ) {
            $args['meta_query'] = array(
                array(
                    'key' => '_hvac_template_category',
                    'value' => $category,
                    'compare' => '='
                )
            );
        }

        $templates = get_posts( $args );
        $formatted_templates = array();

        foreach ( $templates as $template ) {
            $formatted_templates[] = array(
                'id' => $template->ID,
                'title' => $template->post_title,
                'content' => $template->post_content,
                'category' => get_post_meta( $template->ID, '_hvac_template_category', true ),
                'description' => get_post_meta( $template->ID, '_hvac_template_description', true ),
                'created' => $template->post_date,
                'modified' => $template->post_modified,
            );
        }

        return $formatted_templates;
    }

    /**
     * Save a template
     *
     * @param array $template_data Template data
     * @return int|WP_Error Template ID on success, WP_Error on failure
     */
    public function save_template( $template_data ) {
        // Validate required fields
        if ( empty( $template_data['title'] ) || empty( $template_data['content'] ) ) {
            return new WP_Error( 'missing_data', __( 'Template title and content are required.', 'hvac-community-events' ) );
        }

        $post_data = array(
            'post_type' => self::POST_TYPE,
            'post_title' => sanitize_text_field( $template_data['title'] ),
            'post_content' => wp_kses_post( $template_data['content'] ),
            'post_status' => 'publish',
            'post_author' => get_current_user_id(),
        );

        // Update existing template if ID provided
        if ( ! empty( $template_data['id'] ) ) {
            $post_data['ID'] = intval( $template_data['id'] );
            
            // Verify ownership
            $existing_template = get_post( $post_data['ID'] );
            if ( ! $existing_template || $existing_template->post_author != get_current_user_id() ) {
                return new WP_Error( 'permission_denied', __( 'You can only edit your own templates.', 'hvac-community-events' ) );
            }
        }

        $template_id = wp_insert_post( $post_data );

        if ( is_wp_error( $template_id ) ) {
            return $template_id;
        }

        // Save metadata
        if ( ! empty( $template_data['category'] ) ) {
            update_post_meta( $template_id, '_hvac_template_category', sanitize_text_field( $template_data['category'] ) );
        }

        if ( ! empty( $template_data['description'] ) ) {
            update_post_meta( $template_id, '_hvac_template_description', sanitize_text_field( $template_data['description'] ) );
        }

        return $template_id;
    }

    /**
     * Delete a template
     *
     * @param int $template_id Template ID
     * @return bool Success status
     */
    public function delete_template( $template_id ) {
        $template = get_post( $template_id );
        
        if ( ! $template || $template->post_type !== self::POST_TYPE ) {
            return false;
        }

        // Verify ownership
        if ( $template->post_author != get_current_user_id() && ! current_user_can( 'delete_others_posts' ) ) {
            return false;
        }

        return wp_delete_post( $template_id, true ) !== false;
    }

    /**
     * Process placeholders in template content
     *
     * @param string $content Template content
     * @param array $context Context data for placeholders
     * @return string Processed content
     */
    public function process_placeholders( $content, $context = array() ) {
        $current_user = wp_get_current_user();
        
        // Default context values
        $defaults = array(
            'attendee_name' => '',
            'event_title' => '',
            'event_date' => '',
            'event_time' => '',
            'event_location' => '',
            'trainer_name' => $current_user->display_name,
            'business_name' => get_user_meta( $current_user->ID, 'business_name', true ),
            'trainer_email' => $current_user->user_email,
            'trainer_phone' => get_user_meta( $current_user->ID, 'phone_number', true ),
            'current_date' => date( 'F j, Y' ),
            'website_name' => get_bloginfo( 'name' ),
            'website_url' => home_url(),
        );

        // Get trainer contact email if available
        if ( in_array( 'hvac_trainer', $current_user->roles ) ) {
            $contact_email = get_user_meta( $current_user->ID, 'contact_email', true );
            if ( ! empty( $contact_email ) && is_email( $contact_email ) ) {
                $defaults['trainer_email'] = $contact_email;
            }
        }

        $context = wp_parse_args( $context, $defaults );

        // Replace placeholders
        foreach ( self::PLACEHOLDERS as $placeholder => $description ) {
            $key = str_replace( array( '{', '}' ), '', $placeholder );
            if ( isset( $context[ $key ] ) ) {
                $content = str_replace( $placeholder, $context[ $key ], $content );
            }
        }

        return $content;
    }

    /**
     * Get default templates
     *
     * @return array Default templates
     */
    public function get_default_templates() {
        return array(
            array(
                'title' => __( 'Event Reminder - 24 Hours', 'hvac-community-events' ),
                'category' => 'event_reminder',
                'description' => __( 'Reminder sent 24 hours before the event', 'hvac-community-events' ),
                'content' => "Hello {attendee_name},\n\nThis is a friendly reminder that you're registered for {event_title} tomorrow at {event_time}.\n\nEvent Details:\n- Date: {event_date}\n- Time: {event_time}\n- Location: {event_location}\n\nPlease bring a valid ID and any materials mentioned in your registration confirmation.\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}"
            ),
            array(
                'title' => __( 'Welcome & Pre-Event Information', 'hvac-community-events' ),
                'category' => 'pre_event',
                'description' => __( 'Welcome message with event preparation information', 'hvac-community-events' ),
                '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\n1. Please arrive 15 minutes early for check-in\n2. Bring a valid photo ID\n3. Dress comfortably and wear closed-toe shoes\n4. Bring a notebook and pen for taking notes\n5. 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}"
            ),
            array(
                'title' => __( 'Thank You & Certificate Information', 'hvac-community-events' ),
                'category' => 'post_event',
                'description' => __( 'Post-event thank you with certificate details', 'hvac-community-events' ),
                '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}"
            ),
            array(
                'title' => __( 'Certificate Ready for Download', 'hvac-community-events' ),
                'category' => 'certificate',
                'description' => __( 'Notification when certificate is ready', 'hvac-community-events' ),
                '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}"
            )
        );
    }

    /**
     * Install default templates for a user
     *
     * @param int $user_id User ID
     */
    public function install_default_templates( $user_id ) {
        $defaults = $this->get_default_templates();
        
        foreach ( $defaults as $template ) {
            $template_data = array(
                'title' => $template['title'],
                'content' => $template['content'],
                'category' => $template['category'],
                'description' => $template['description'],
            );

            // Temporarily switch to the target user
            $current_user_id = get_current_user_id();
            wp_set_current_user( $user_id );
            
            $this->save_template( $template_data );
            
            // Switch back to original user
            wp_set_current_user( $current_user_id );
        }
    }

    /**
     * AJAX handler for saving templates
     */
    public function ajax_save_template() {
        check_ajax_referer( 'hvac_templates_nonce', 'nonce' );

        if ( ! is_user_logged_in() ) {
            wp_send_json_error( array( 'message' => __( 'You must be logged in to save templates.', 'hvac-community-events' ) ) );
        }

        $template_data = array(
            'id' => isset( $_POST['template_id'] ) ? intval( $_POST['template_id'] ) : 0,
            'title' => isset( $_POST['title'] ) ? sanitize_text_field( $_POST['title'] ) : '',
            'content' => isset( $_POST['content'] ) ? wp_kses_post( $_POST['content'] ) : '',
            'category' => isset( $_POST['category'] ) ? sanitize_text_field( $_POST['category'] ) : '',
            'description' => isset( $_POST['description'] ) ? sanitize_text_field( $_POST['description'] ) : '',
        );

        $result = $this->save_template( $template_data );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
        }

        wp_send_json_success( array(
            'template_id' => $result,
            'message' => __( 'Template saved successfully.', 'hvac-community-events' )
        ) );
    }

    /**
     * AJAX handler for loading templates
     */
    public function ajax_load_template() {
        check_ajax_referer( 'hvac_templates_nonce', 'nonce' );

        if ( ! is_user_logged_in() ) {
            wp_send_json_error( array( 'message' => __( 'You must be logged in to load templates.', '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' ) ) );
        }

        // Verify ownership or admin access
        if ( $template->post_author != get_current_user_id() && ! current_user_can( 'edit_others_posts' ) ) {
            wp_send_json_error( array( 'message' => __( 'You can only load your own templates.', 'hvac-community-events' ) ) );
        }

        wp_send_json_success( array(
            'id' => $template->ID,
            'title' => $template->post_title,
            'content' => $template->post_content,
            'category' => get_post_meta( $template->ID, '_hvac_template_category', true ),
            'description' => get_post_meta( $template->ID, '_hvac_template_description', true ),
        ) );
    }

    /**
     * AJAX handler for deleting templates
     */
    public function ajax_delete_template() {
        check_ajax_referer( 'hvac_templates_nonce', 'nonce' );

        if ( ! is_user_logged_in() ) {
            wp_send_json_error( array( 'message' => __( 'You must be logged in to delete templates.', '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' ) ) );
        }

        $result = $this->delete_template( $template_id );

        if ( ! $result ) {
            wp_send_json_error( array( 'message' => __( 'Failed to delete template.', 'hvac-community-events' ) ) );
        }

        wp_send_json_success( array( 'message' => __( 'Template deleted successfully.', 'hvac-community-events' ) ) );
    }

    /**
     * AJAX handler for getting templates list
     */
    public function ajax_get_templates() {
        check_ajax_referer( 'hvac_templates_nonce', 'nonce' );

        if ( ! is_user_logged_in() ) {
            wp_send_json_error( array( 'message' => __( 'You must be logged in to view templates.', 'hvac-community-events' ) ) );
        }

        $category = isset( $_POST['category'] ) ? sanitize_text_field( $_POST['category'] ) : '';
        $templates = $this->get_user_templates( get_current_user_id(), $category );

        wp_send_json_success( array( 'templates' => $templates ) );
    }
}

// Initialize the class
new HVAC_Communication_Templates();