<?php
/**
 * HVAC Community Events - Communication Templates Template
 *
 * Template for managing email templates.
 *
 * @package HVAC_Community_Events
 * @subpackage Templates
 */

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

// Check if user is logged in
if ( ! is_user_logged_in() ) {
    wp_redirect( site_url( '/community-login/' ) );
    exit;
}

// Load the templates class
require_once HVAC_PLUGIN_DIR . 'includes/communication/class-communication-templates.php';
$templates_manager = new HVAC_Communication_Templates();

// Get current user templates
$user_templates = $templates_manager->get_user_templates();
$categories = HVAC_Communication_Templates::DEFAULT_CATEGORIES;

// Handle first-time user setup
$current_user = wp_get_current_user();
$has_templates = !empty($user_templates);

// Install default templates if this is a new trainer
if (!$has_templates && in_array('hvac_trainer', $current_user->roles)) {
    $install_defaults = isset($_GET['install_defaults']) ? $_GET['install_defaults'] === 'true' : false;
    
    if ($install_defaults) {
        $templates_manager->install_default_templates(get_current_user_id());
        wp_redirect(remove_query_arg('install_defaults'));
        exit;
    }
}

// Get the site title for the page title
$site_title = get_bloginfo( 'name' );
?>

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo esc_html( $site_title ); ?> - <?php _e( 'Communication Templates', 'hvac-community-events' ); ?></title>
    <?php wp_head(); ?>
    
    <style>
        .hvac-templates-wrapper {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .hvac-templates-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        
        .hvac-templates-title h1 {
            margin: 0 0 10px 0;
            color: var(--hvac-theme-text-dark);
        }
        
        .hvac-templates-navigation {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .hvac-templates-stats {
            background: var(--hvac-background-subtle);
            padding: 20px;
            border-radius: var(--hvac-radius-lg);
            margin-bottom: 30px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }
        
        .hvac-stat-item {
            text-align: center;
        }
        
        .hvac-stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: var(--hvac-primary);
            margin-bottom: 5px;
        }
        
        .hvac-stat-label {
            color: var(--hvac-theme-text-light);
            font-size: 0.9rem;
        }
        
        .hvac-getting-started {
            background: var(--hvac-info-light);
            border: 1px solid var(--hvac-accent);
            border-radius: var(--hvac-radius-lg);
            padding: 30px;
            text-align: center;
            margin-bottom: 30px;
        }
        
        .hvac-getting-started h2 {
            color: var(--hvac-accent);
            margin-bottom: 15px;
        }
        
        .hvac-templates-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .hvac-template-card {
            background: var(--hvac-background-white);
            border: 1px solid var(--hvac-border);
            border-radius: var(--hvac-radius-lg);
            padding: 20px;
            transition: all var(--hvac-transition-fast);
        }
        
        .hvac-template-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--hvac-shadow-md);
        }
        
        .hvac-template-card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 15px;
        }
        
        .hvac-template-card-title {
            font-weight: bold;
            color: var(--hvac-theme-text-dark);
            margin: 0;
        }
        
        .hvac-template-card-category {
            background: var(--hvac-primary);
            color: white;
            padding: 4px 8px;
            border-radius: var(--hvac-radius-sm);
            font-size: 0.8rem;
        }
        
        .hvac-template-card-description {
            color: var(--hvac-theme-text-light);
            font-size: 0.9rem;
            margin-bottom: 15px;
        }
        
        .hvac-template-card-actions {
            display: flex;
            gap: 10px;
        }
        
        .hvac-template-card-actions button {
            padding: 8px 12px;
            border: none;
            border-radius: var(--hvac-radius-sm);
            font-size: 0.8rem;
            cursor: pointer;
            transition: all var(--hvac-transition-fast);
        }
        
        .hvac-category-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .hvac-category-tab {
            padding: 10px 15px;
            background: var(--hvac-background-subtle);
            border: 1px solid var(--hvac-border);
            border-radius: var(--hvac-radius-md);
            cursor: pointer;
            transition: all var(--hvac-transition-fast);
        }
        
        .hvac-category-tab.active {
            background: var(--hvac-primary);
            color: white;
            border-color: var(--hvac-primary);
        }
        
        .hvac-template-form-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            display: none;
        }
        
        .hvac-template-form-modal {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: var(--hvac-background-white);
            border-radius: var(--hvac-radius-lg);
            padding: 30px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }
    </style>
</head>

<body <?php body_class(); ?>>
    <?php wp_body_open(); ?>

    <div class="hvac-templates-wrapper">
        <div class="hvac-templates-header">
            <div class="hvac-templates-title">
                <h1><?php _e( 'Communication Templates', 'hvac-community-events' ); ?></h1>
                <p><?php _e( 'Manage your email templates for communicating with event attendees.', 'hvac-community-events' ); ?></p>
            </div>
            
            <div class="hvac-templates-navigation">
                <a href="<?php echo esc_url( site_url( '/hvac-dashboard/' ) ); ?>" class="ast-button ast-button-secondary">
                    <?php _e( 'Return to Dashboard', 'hvac-community-events' ); ?>
                </a>
                <button type="button" class="ast-button ast-button-primary" onclick="HVACTemplates.createNewTemplate()">
                    <?php _e( 'Create New Template', 'hvac-community-events' ); ?>
                </button>
            </div>
        </div>

        <?php if (!$has_templates && in_array('hvac_trainer', $current_user->roles)) : ?>
            <div class="hvac-getting-started">
                <h2><?php _e( 'Welcome to Communication Templates!', 'hvac-community-events' ); ?></h2>
                <p><?php _e( 'Save time by creating reusable email templates for your events. You can create your own templates or start with our professionally crafted defaults.', 'hvac-community-events' ); ?></p>
                
                <div style="margin: 20px 0;">
                    <a href="<?php echo esc_url( add_query_arg( 'install_defaults', 'true' ) ); ?>" class="ast-button ast-button-primary" style="margin-right: 10px;">
                        <?php _e( 'Install Default Templates', 'hvac-community-events' ); ?>
                    </a>
                    <button type="button" class="ast-button ast-button-secondary" onclick="HVACTemplates.createNewTemplate()">
                        <?php _e( 'Create From Scratch', 'hvac-community-events' ); ?>
                    </button>
                </div>
                
                <small><?php _e( 'Default templates include: Event reminders, welcome messages, post-event follow-ups, and certificate notifications.', 'hvac-community-events' ); ?></small>
            </div>
        <?php endif; ?>

        <?php if ($has_templates) : ?>
            <!-- Template Statistics -->
            <div class="hvac-templates-stats">
                <div class="hvac-stat-item">
                    <div class="hvac-stat-number"><?php echo count($user_templates); ?></div>
                    <div class="hvac-stat-label"><?php _e( 'Total Templates', 'hvac-community-events' ); ?></div>
                </div>
                
                <?php
                $category_counts = array();
                foreach ($user_templates as $template) {
                    $category = $template['category'] ?: 'general';
                    $category_counts[$category] = ($category_counts[$category] ?? 0) + 1;
                }
                ?>
                
                <div class="hvac-stat-item">
                    <div class="hvac-stat-number"><?php echo count($category_counts); ?></div>
                    <div class="hvac-stat-label"><?php _e( 'Categories Used', 'hvac-community-events' ); ?></div>
                </div>
                
                <div class="hvac-stat-item">
                    <div class="hvac-stat-number"><?php echo date('M Y', strtotime(max(array_column($user_templates, 'modified')))); ?></div>
                    <div class="hvac-stat-label"><?php _e( 'Last Updated', 'hvac-community-events' ); ?></div>
                </div>
            </div>

            <!-- Category Tabs -->
            <div class="hvac-category-tabs">
                <div class="hvac-category-tab active" data-category="">
                    <?php _e( 'All Templates', 'hvac-community-events' ); ?>
                    <span class="hvac-count-badge"><?php echo count($user_templates); ?></span>
                </div>
                
                <?php foreach ($categories as $key => $label) : ?>
                    <?php $count = $category_counts[$key] ?? 0; ?>
                    <?php if ($count > 0) : ?>
                        <div class="hvac-category-tab" data-category="<?php echo esc_attr($key); ?>">
                            <?php echo esc_html($label); ?>
                            <span class="hvac-count-badge"><?php echo $count; ?></span>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>

            <!-- Templates Grid -->
            <div class="hvac-templates-grid" id="templates-grid">
                <?php foreach ($user_templates as $template) : ?>
                    <div class="hvac-template-card" data-category="<?php echo esc_attr($template['category']); ?>">
                        <div class="hvac-template-card-header">
                            <h3 class="hvac-template-card-title"><?php echo esc_html($template['title']); ?></h3>
                            <?php if (!empty($template['category'])) : ?>
                                <span class="hvac-template-card-category">
                                    <?php echo esc_html($categories[$template['category']] ?? $template['category']); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                        
                        <?php if (!empty($template['description'])) : ?>
                            <p class="hvac-template-card-description"><?php echo esc_html($template['description']); ?></p>
                        <?php endif; ?>
                        
                        <div class="hvac-template-card-actions">
                            <button type="button" class="hvac-btn-edit ast-button ast-button-secondary" data-template-id="<?php echo $template['id']; ?>">
                                <?php _e( 'Edit', 'hvac-community-events' ); ?>
                            </button>
                            <button type="button" class="hvac-btn-preview ast-button ast-button-outline" data-template-id="<?php echo $template['id']; ?>">
                                <?php _e( 'Preview', 'hvac-community-events' ); ?>
                            </button>
                            <button type="button" class="hvac-btn-delete ast-button ast-button-danger" data-template-id="<?php echo $template['id']; ?>">
                                <?php _e( 'Delete', 'hvac-community-events' ); ?>
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- Template Form Modal -->
        <div class="hvac-template-form-overlay" id="template-form-overlay">
            <div class="hvac-template-form-modal">
                <h2 id="template-form-title"><?php _e( 'Create New Template', 'hvac-community-events' ); ?></h2>
                
                <form id="template-form">
                    <div class="hvac-template-form-row">
                        <label for="hvac_template_title"><?php _e( 'Template Name:', 'hvac-community-events' ); ?> <span class="hvac-required">*</span></label>
                        <input type="text" id="hvac_template_title" name="title" required>
                    </div>

                    <div class="hvac-template-form-row">
                        <label for="hvac_template_category"><?php _e( 'Category:', 'hvac-community-events' ); ?></label>
                        <select id="hvac_template_category" name="category">
                            <option value=""><?php _e( 'Select category...', 'hvac-community-events' ); ?></option>
                            <?php foreach ($categories as $key => $label) : ?>
                                <option value="<?php echo esc_attr($key); ?>"><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="hvac-template-form-row">
                        <label for="hvac_template_description"><?php _e( 'Description:', 'hvac-community-events' ); ?></label>
                        <input type="text" id="hvac_template_description" name="description" placeholder="<?php _e( 'Brief description of when to use this template', 'hvac-community-events' ); ?>">
                    </div>

                    <div class="hvac-template-form-row">
                        <label for="hvac_template_content"><?php _e( 'Content:', 'hvac-community-events' ); ?> <span class="hvac-required">*</span></label>
                        <textarea id="hvac_template_content" name="content" rows="12" required placeholder="<?php _e( 'Enter your email template content here. Use placeholders like {attendee_name} and {event_title} for dynamic content.', 'hvac-community-events' ); ?>"></textarea>
                    </div>

                    <!-- Placeholder Helper -->
                    <div class="hvac-placeholder-helper">
                        <h4><?php _e( 'Available Placeholders', 'hvac-community-events' ); ?></h4>
                        <p><?php _e( 'Click any placeholder below to insert it into your template:', 'hvac-community-events' ); ?></p>
                        <div class="hvac-placeholder-grid"></div>
                    </div>

                    <div class="hvac-template-form-actions">
                        <button type="button" class="hvac-btn-secondary hvac-template-form-cancel">
                            <?php _e( 'Cancel', 'hvac-community-events' ); ?>
                        </button>
                        <button type="submit" class="hvac-btn-primary hvac-template-form-save">
                            <span class="hvac-spinner" style="display: none;"></span>
                            <?php _e( 'Save Template', 'hvac-community-events' ); ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Category filtering
        document.addEventListener('DOMContentLoaded', function() {
            const tabs = document.querySelectorAll('.hvac-category-tab');
            const cards = document.querySelectorAll('.hvac-template-card');
            
            tabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    const category = this.dataset.category;
                    
                    // Update active tab
                    tabs.forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    // Filter cards
                    cards.forEach(card => {
                        if (!category || card.dataset.category === category) {
                            card.style.display = 'block';
                        } else {
                            card.style.display = 'none';
                        }
                    });
                });
            });
            
            // Template actions
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('hvac-btn-edit')) {
                    const templateId = e.target.dataset.templateId;
                    HVACTemplates.editTemplate(templateId);
                }
                
                if (e.target.classList.contains('hvac-btn-delete')) {
                    const templateId = e.target.dataset.templateId;
                    if (confirm('<?php echo esc_js(__('Are you sure you want to delete this template?', 'hvac-community-events')); ?>')) {
                        HVACTemplates.deleteTemplate(templateId);
                    }
                }
            });
            
            // Modal handling
            const overlay = document.getElementById('template-form-overlay');
            const cancelBtn = document.querySelector('.hvac-template-form-cancel');
            
            cancelBtn.addEventListener('click', function() {
                overlay.style.display = 'none';
                overlay.style.visibility = 'hidden';
                overlay.style.opacity = '0';
                HVACTemplates.cancelTemplateForm();
            });
            
            overlay.addEventListener('click', function(e) {
                if (e.target === overlay) {
                    overlay.style.display = 'none';
                    overlay.style.visibility = 'hidden';
                    overlay.style.opacity = '0';
                    HVACTemplates.cancelTemplateForm();
                }
            });
            
            // Form submission
            document.getElementById('template-form').addEventListener('submit', function(e) {
                e.preventDefault();
                HVACTemplates.saveTemplate();
            });
        });
        
        // Override HVACTemplates methods for modal
        if (typeof HVACTemplates !== 'undefined') {
            HVACTemplates.createNewTemplate = function() {
                this.currentTemplateId = null;
                this.isEditing = true;
                
                // Clear form
                document.getElementById('hvac_template_title').value = '';
                document.getElementById('hvac_template_content').value = '';
                document.getElementById('hvac_template_category').value = '';
                document.getElementById('hvac_template_description').value = '';
                
                // Show modal - make sure to set display to block!
                const overlay = document.getElementById('template-form-overlay');
                overlay.style.display = 'block';
                overlay.style.visibility = 'visible';
                overlay.style.opacity = '1';
                
                document.getElementById('template-form-title').textContent = '<?php echo esc_js(__('Create New Template', 'hvac-community-events')); ?>';
                
                // Focus on title field with a slight delay
                setTimeout(function() {
                    document.getElementById('hvac_template_title').focus();
                }, 100);
            };
            
            HVACTemplates.editTemplate = function(templateId) {
                const self = this;
                
                $.ajax({
                    url: this.config.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'hvac_load_template',
                        nonce: this.config.nonce,
                        template_id: templateId
                    },
                    success: function(response) {
                        if (response.success) {
                            const template = response.data;
                            self.currentTemplateId = template.id;
                            self.isEditing = true;
                            
                            // Populate form
                            document.getElementById('hvac_template_title').value = template.title;
                            document.getElementById('hvac_template_content').value = template.content;
                            document.getElementById('hvac_template_category').value = template.category;
                            document.getElementById('hvac_template_description').value = template.description;
                            
                            // Show modal
                            const overlay = document.getElementById('template-form-overlay');
                            overlay.style.display = 'block';
                            overlay.style.visibility = 'visible';
                            overlay.style.opacity = '1';
                            document.getElementById('template-form-title').textContent = '<?php echo esc_js(__('Edit Template', 'hvac-community-events')); ?>';
                            
                        } else {
                            alert(response.data.message);
                        }
                    }
                });
            };
            
            HVACTemplates.saveTemplate = function() {
                const self = this;
                
                const templateData = {
                    action: 'hvac_save_template',
                    nonce: this.config.nonce,
                    template_id: this.currentTemplateId || 0,
                    title: document.getElementById('hvac_template_title').value,
                    content: document.getElementById('hvac_template_content').value,
                    category: document.getElementById('hvac_template_category').value,
                    description: document.getElementById('hvac_template_description').value
                };

                if (!templateData.title || !templateData.content) {
                    alert('<?php echo esc_js(__('Template title and content are required', 'hvac-community-events')); ?>');
                    return;
                }

                $.ajax({
                    url: this.config.ajaxUrl,
                    type: 'POST',
                    data: templateData,
                    beforeSend: function() {
                        document.querySelector('.hvac-template-form-save .hvac-spinner').style.display = 'inline-block';
                    },
                    success: function(response) {
                        if (response.success) {
                            alert(response.data.message);
                            const overlay = document.getElementById('template-form-overlay');
                            overlay.style.display = 'none';
                            overlay.style.visibility = 'hidden';
                            overlay.style.opacity = '0';
                            location.reload(); // Refresh page to show updated templates
                        } else {
                            alert(response.data.message);
                        }
                    },
                    complete: function() {
                        document.querySelector('.hvac-template-form-save .hvac-spinner').style.display = 'none';
                    }
                });
            };
            
            HVACTemplates.deleteTemplate = function(templateId) {
                const self = this;
                
                $.ajax({
                    url: this.config.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'hvac_delete_template',
                        nonce: this.config.nonce,
                        template_id: templateId
                    },
                    success: function(response) {
                        if (response.success) {
                            alert(response.data.message);
                            location.reload(); // Refresh page
                        } else {
                            alert(response.data.message);
                        }
                    }
                });
            };
        }
    </script>

    <?php wp_footer(); ?>
    
    <script>
        // IMPORTANT: This must run AFTER the external JS file loads
        jQuery(document).ready(function($) {
            // Wait for external JS to load, then override
            if (typeof HVACTemplates !== 'undefined') {
                console.log('Overriding HVACTemplates.createNewTemplate with modal version');
                
                HVACTemplates.createNewTemplate = function() {
                    console.log('Modal createNewTemplate called');
                    this.currentTemplateId = null;
                    this.isEditing = true;
                    
                    // Clear form
                    document.getElementById('hvac_template_title').value = '';
                    document.getElementById('hvac_template_content').value = '';
                    document.getElementById('hvac_template_category').value = '';
                    document.getElementById('hvac_template_description').value = '';
                    
                    // Show modal - make sure to set display to block!
                    const overlay = document.getElementById('template-form-overlay');
                    overlay.style.display = 'block';
                    overlay.style.visibility = 'visible';
                    overlay.style.opacity = '1';
                    
                    document.getElementById('template-form-title').textContent = 'Create New Template';
                    
                    // Focus on title field with a slight delay
                    setTimeout(function() {
                        document.getElementById('hvac_template_title').focus();
                    }, 100);
                };
                
                // Also override editTemplate to use modal
                HVACTemplates.editTemplate = function(templateId) {
                    const self = this;
                    
                    $.ajax({
                        url: this.config.ajaxUrl,
                        type: 'POST',
                        data: {
                            action: 'hvac_load_template',
                            nonce: this.config.nonce,
                            template_id: templateId
                        },
                        success: function(response) {
                            if (response.success) {
                                const template = response.data;
                                self.currentTemplateId = template.id;
                                self.isEditing = true;
                                
                                // Populate form
                                document.getElementById('hvac_template_title').value = template.title;
                                document.getElementById('hvac_template_content').value = template.content;
                                document.getElementById('hvac_template_category').value = template.category;
                                document.getElementById('hvac_template_description').value = template.description;
                                
                                // Show modal
                                const overlay = document.getElementById('template-form-overlay');
                                overlay.style.display = 'block';
                                overlay.style.visibility = 'visible';
                                overlay.style.opacity = '1';
                                document.getElementById('template-form-title').textContent = 'Edit Template';
                                
                            } else {
                                alert(response.data.message);
                            }
                        }
                    });
                };
            }
        });
    </script>
</body>
</html>