<?php
/**
 * HVAC Community Events - Enhanced Settings with Email Templates
 *
 * Extends the settings page with email template editors
 *
 * @package HVAC_Community_Events
 * @since 1.0.0
 */

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

/**
 * Class HVAC_Enhanced_Settings
 *
 * Adds email template management to the plugin settings
 */
class HVAC_Enhanced_Settings {
    
    /**
     * Instance
     * 
     * @var HVAC_Enhanced_Settings
     */
    private static $instance = null;
    
    /**
     * Get instance
     * 
     * @return HVAC_Enhanced_Settings
     */
    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Hook into settings initialization
        add_action( 'admin_init', array( $this, 'register_email_template_settings' ), 20 );
        
        // Add email templates tab to settings page
        add_action( 'hvac_ce_settings_tabs', array( $this, 'add_email_templates_tab' ) );
        add_action( 'hvac_ce_settings_content', array( $this, 'render_email_templates_content' ) );
        
        // Enqueue admin scripts
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
    }
    
    /**
     * Register email template settings
     */
    public function register_email_template_settings() {
        // Register the email templates option
        register_setting( 'hvac_ce_email_templates', 'hvac_ce_email_templates', array( $this, 'sanitize_email_templates' ) );
    }
    
    /**
     * Add email templates tab
     *
     * @param array $tabs Current tabs
     * @return array Modified tabs
     */
    public function add_email_templates_tab( $tabs ) {
        $tabs['email_templates'] = __( 'Email Templates', 'hvac-community-events' );
        return $tabs;
    }
    
    /**
     * Render email templates content
     *
     * @param string $active_tab Active tab ID
     */
    public function render_email_templates_content( $active_tab ) {
        if ( $active_tab !== 'email_templates' ) {
            return;
        }
        
        $templates = get_option( 'hvac_ce_email_templates', array() );
        
        // Define template keys and their descriptions
        $template_definitions = array(
            'new_registration' => array(
                'title' => __( 'New Registration Notification', 'hvac-community-events' ),
                'description' => __( 'Sent to administrators when a new trainer registers', 'hvac-community-events' ),
                'placeholders' => array(
                    '{trainer_name}' => 'Trainer full name',
                    '{trainer_email}' => 'Trainer email address',
                    '{business_name}' => 'Business name',
                    '{business_phone}' => 'Business phone',
                    '{business_email}' => 'Business email',
                    '{registration_date}' => 'Registration date',
                    '{application_details}' => 'Application details',
                    '{approval_url}' => 'Quick approval link',
                ),
            ),
            'account_approved' => array(
                'title' => __( 'Account Approved', 'hvac-community-events' ),
                'description' => __( 'Sent to trainers when their account is approved', 'hvac-community-events' ),
                'placeholders' => array(
                    '{trainer_name}' => 'Trainer full name',
                    '{trainer_email}' => 'Trainer email address',
                    '{business_name}' => 'Business name',
                    '{dashboard_url}' => 'Dashboard URL',
                    '{login_url}' => 'Login page URL',
                    '{website_name}' => 'Website name',
                    '{website_url}' => 'Website URL',
                ),
            ),
            'account_disabled' => array(
                'title' => __( 'Account Disabled', 'hvac-community-events' ),
                'description' => __( 'Sent to trainers when their account is disabled', 'hvac-community-events' ),
                'placeholders' => array(
                    '{trainer_name}' => 'Trainer full name',
                    '{trainer_email}' => 'Trainer email address',
                    '{business_name}' => 'Business name',
                    '{support_email}' => 'Support email address',
                    '{website_name}' => 'Website name',
                ),
            ),
        );
        
        ?>
        <div class="hvac-email-templates-settings">
            <form method="post" action="options.php">
                <?php settings_fields( 'hvac_ce_email_templates' ); ?>
                
                <p><?php _e( 'Customize the email templates sent by the plugin. Use the placeholders shown for each template.', 'hvac-community-events' ); ?></p>
                
                <?php foreach ( $template_definitions as $key => $definition ): ?>
                    <?php
                    // Get saved template or use default
                    $defaults = $this->get_default_templates();
                    $default_subject = isset($defaults[$key]['subject']) ? $defaults[$key]['subject'] : '';
                    $default_body = isset($defaults[$key]['body']) ? $defaults[$key]['body'] : '';
                    
                    $subject = isset( $templates[$key]['subject'] ) ? $templates[$key]['subject'] : $default_subject;
                    $body = isset( $templates[$key]['body'] ) ? $templates[$key]['body'] : $default_body;
                    ?>
                    
                    <div class="email-template-section">
                        <h3><?php echo esc_html( $definition['title'] ); ?></h3>
                        <p class="description"><?php echo esc_html( $definition['description'] ); ?></p>
                        
                        <div class="placeholders-info">
                            <strong><?php _e( 'Available placeholders:', 'hvac-community-events' ); ?></strong>
                            <div class="placeholders-list">
                                <?php foreach ( $definition['placeholders'] as $placeholder => $desc ): ?>
                                    <code><?php echo esc_html( $placeholder ); ?></code> - <?php echo esc_html( $desc ); ?><br>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="<?php echo esc_attr( $key ); ?>_subject">
                                        <?php _e( 'Subject', 'hvac-community-events' ); ?>
                                    </label>
                                </th>
                                <td>
                                    <input type="text" 
                                           id="<?php echo esc_attr( $key ); ?>_subject"
                                           name="hvac_ce_email_templates[<?php echo esc_attr( $key ); ?>][subject]"
                                           value="<?php echo esc_attr( $subject ); ?>"
                                           class="large-text" />
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="<?php echo esc_attr( $key ); ?>_body">
                                        <?php _e( 'Email Body', 'hvac-community-events' ); ?>
                                    </label>
                                </th>
                                <td>
                                    <?php
                                    wp_editor( $body, $key . '_body', array(
                                        'textarea_name' => 'hvac_ce_email_templates[' . $key . '][body]',
                                        'textarea_rows' => 15,
                                        'media_buttons' => false,
                                        'teeny' => false,
                                        'tinymce' => array(
                                            'toolbar1' => 'bold,italic,underline,separator,alignleft,aligncenter,alignright,separator,link,unlink,separator,undo,redo',
                                            'toolbar2' => 'formatselect,fontselect,fontsizeselect,separator,forecolor,backcolor,separator,bullist,numlist,separator,code',
                                        ),
                                    ) );
                                    ?>
                                </td>
                            </tr>
                        </table>
                        
                        <hr>
                    </div>
                <?php endforeach; ?>
                
                <?php submit_button(); ?>
            </form>
            
            <div class="email-template-preview">
                <h3><?php _e( 'Preview', 'hvac-community-events' ); ?></h3>
                <p><?php _e( 'Select a template above to preview how it will look with sample data.', 'hvac-community-events' ); ?></p>
                <div id="email-preview-container" style="border: 1px solid #ddd; padding: 20px; background: #fff; display: none;">
                    <div id="email-preview-subject" style="font-weight: bold; margin-bottom: 10px;"></div>
                    <div id="email-preview-body"></div>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Sanitize email templates
     *
     * @param array $input Input data
     * @return array Sanitized data
     */
    public function sanitize_email_templates( $input ) {
        $sanitized = array();
        
        if ( ! is_array( $input ) ) {
            return $sanitized;
        }
        
        foreach ( $input as $key => $template ) {
            if ( isset( $template['subject'] ) ) {
                $sanitized[$key]['subject'] = sanitize_text_field( $template['subject'] );
            }
            
            if ( isset( $template['body'] ) ) {
                $sanitized[$key]['body'] = wp_kses_post( $template['body'] );
            }
        }
        
        return $sanitized;
    }
    
    /**
     * Get default email templates
     */
    public function get_default_templates() {
        return array(
            'new_registration' => array(
                'subject' => 'New Trainer Registration - {trainer_name}',
                'body' => '<p>Hello Administrator,</p>

<p>A new trainer has registered and is awaiting approval:</p>

<p><strong>Trainer Information:</strong><br>
Name: {trainer_name}<br>
Email: {trainer_email}<br>
Business: {business_name}<br>
Phone: {business_phone}<br>
Business Email: {business_email}<br>
Registration Date: {registration_date}</p>

<p><strong>Application Details:</strong><br>
{application_details}</p>

<p><strong>Action Required:</strong><br>
Please review this trainer\'s application and approve or deny their access.</p>

<p><a href="{approval_url}" style="background-color: #0073aa; color: white; padding: 10px 20px; text-decoration: none; border-radius: 3px; display: inline-block;">Review Application</a></p>

<p>Best regards,<br>
{website_name}</p>'
            ),
            'account_approved' => array(
                'subject' => 'Welcome to {website_name} - Your Trainer Account is Approved!',
                'body' => '<p>Dear {trainer_name},</p>

<p>Great news! Your trainer account for {business_name} has been approved.</p>

<p>You can now access your trainer dashboard to:</p>
<ul>
<li>Create and manage HVAC training events</li>
<li>Generate certificates for attendees</li>
<li>View reports and analytics</li>
<li>Communicate with your attendees</li>
</ul>

<p><strong>Get Started:</strong><br>
<a href="{dashboard_url}" style="background-color: #0073aa; color: white; padding: 10px 20px; text-decoration: none; border-radius: 3px; display: inline-block;">Go to Your Dashboard</a></p>

<p>If you need to log in again, visit: <a href="{login_url}">{login_url}</a></p>

<p>We\'re excited to have you as part of our community of HVAC trainers!</p>

<p>If you have any questions or need assistance, please don\'t hesitate to reach out.</p>

<p>Best regards,<br>
The {website_name} Team</p>'
            ),
            'account_disabled' => array(
                'subject' => 'Your {website_name} Trainer Account Has Been Disabled',
                'body' => '<p>Dear {trainer_name},</p>

<p>We\'re writing to inform you that your trainer account for {business_name} has been temporarily disabled.</p>

<p>This may be due to:</p>
<ul>
<li>Routine account review</li>
<li>Expired credentials or certifications</li>
<li>Policy compliance review</li>
<li>Account inactivity</li>
</ul>

<p>If you believe this was done in error or would like to discuss reactivating your account, please contact us at <a href="mailto:{support_email}">{support_email}</a>.</p>

<p>We value your participation in our trainer community and look forward to resolving this matter.</p>

<p>Best regards,<br>
The {website_name} Team</p>'
            ),
        );
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts( $hook ) {
        // Only load on our settings page
        if ( strpos( $hook, 'hvac-community-events' ) === false ) {
            return;
        }
        
        // Add custom CSS
        wp_add_inline_style( 'wp-admin', '
            .hvac-email-templates-settings .email-template-section {
                background: #fff;
                border: 1px solid #e5e5e5;
                padding: 20px;
                margin-bottom: 20px;
            }
            .hvac-email-templates-settings .placeholders-info {
                background: #f5f5f5;
                padding: 15px;
                margin: 15px 0;
                border-radius: 3px;
            }
            .hvac-email-templates-settings .placeholders-list {
                margin-top: 10px;
                line-height: 1.8;
            }
            .hvac-email-templates-settings .placeholders-list code {
                background: #fff;
                padding: 2px 5px;
                border: 1px solid #ddd;
            }
            .hvac-email-templates-settings .email-template-preview {
                margin-top: 40px;
                background: #f9f9f9;
                padding: 20px;
                border-radius: 3px;
            }
        ' );
        
        // Add preview functionality
        wp_add_inline_script( 'jquery', '
            jQuery(document).ready(function($) {
                // Preview functionality could be added here
                // For now, just a placeholder
            });
        ' );
    }
}