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

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

// Load the templates class if not already loaded
if (!class_exists('HVAC_Communication_Templates')) {
    require_once HVAC_PLUGIN_DIR . 'includes/communication/class-communication-templates.php';
}

$templates_manager = new HVAC_Communication_Templates();
$user_templates = $templates_manager->get_user_templates();
$categories = HVAC_Communication_Templates::DEFAULT_CATEGORIES;

// Check if this is the first time user setup
$current_user = wp_get_current_user();
$has_templates = !empty($user_templates);
?>

<div class="hvac-template-manager" style="display: none;">
    <h3><?php _e( 'Email Templates', 'hvac-community-events' ); ?></h3>
    
    <?php if (!$has_templates && in_array('hvac_trainer', $current_user->roles)) : ?>
        <div class="hvac-template-empty">
            <div class="hvac-template-empty-icon">📝</div>
            <h4><?php _e( 'No Templates Yet', 'hvac-community-events' ); ?></h4>
            <p><?php _e( 'Create reusable email templates to save time when communicating with attendees.', 'hvac-community-events' ); ?></p>
            
            <div class="hvac-template-actions">
                <a href="<?php echo esc_url( add_query_arg( 'install_defaults', 'true', site_url( '/communication-templates/' ) ) ); ?>" class="hvac-btn-primary">
                    <?php _e( 'Install Default Templates', 'hvac-community-events' ); ?>
                </a>
                <button type="button" class="hvac-btn-secondary" onclick="HVACTemplates.createNewTemplate()">
                    <?php _e( 'Create Custom Template', 'hvac-community-events' ); ?>
                </button>
            </div>
        </div>
    <?php else : ?>
        <!-- Template Selector -->
        <div class="hvac-template-selector">
            <select class="hvac-template-category-filter">
                <option value=""><?php _e( 'All Categories', '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>
            
            <select class="hvac-template-dropdown">
                <option value=""><?php _e( 'Select a template...', 'hvac-community-events' ); ?></option>
                <?php foreach ($user_templates as $template) : ?>
                    <option value="<?php echo $template['id']; ?>" data-category="<?php echo esc_attr($template['category']); ?>">
                        <?php echo esc_html($template['title']); ?>
                        <?php if (!empty($template['category'])) : ?>
                            (<?php echo esc_html($categories[$template['category']] ?? $template['category']); ?>)
                        <?php endif; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <div class="hvac-template-actions-buttons">
                <button type="button" class="hvac-btn-load" title="<?php _e( 'Load selected template into email form', 'hvac-community-events' ); ?>">
                    📝 <?php _e( 'Use', 'hvac-community-events' ); ?>
                </button>
                <button type="button" class="hvac-btn-edit" title="<?php _e( 'Edit selected template', 'hvac-community-events' ); ?>">
                    ✏️ <?php _e( 'Edit', 'hvac-community-events' ); ?>
                </button>
                <button type="button" class="hvac-btn-delete" title="<?php _e( 'Delete selected template', 'hvac-community-events' ); ?>">
                    🗑️ <?php _e( 'Delete', 'hvac-community-events' ); ?>
                </button>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="hvac-template-actions" style="margin-top: 15px;">
            <button type="button" class="hvac-template-toggle hvac-btn-save" onclick="HVACTemplates.saveCurrentEmailAsTemplate()">
                💾 <?php _e( 'Save Current as Template', 'hvac-community-events' ); ?>
            </button>
            <a href="<?php echo esc_url( site_url( '/communication-templates/' ) ); ?>" class="hvac-btn-secondary" target="_blank">
                ⚙️ <?php _e( 'Manage All Templates', 'hvac-community-events' ); ?>
            </a>
        </div>
    <?php endif; ?>

    <!-- Template Form (for creating/editing) -->
    <div class="hvac-template-form">
        <h4 id="hvac-template-form-title"><?php _e( 'Save as Template', 'hvac-community-events' ); ?></h4>
        
        <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" placeholder="<?php _e( 'e.g., Event Reminder - 24 Hours', 'hvac-community-events' ); ?>">
        </div>

        <div class="hvac-template-form-row">
            <label for="hvac_template_category"><?php _e( 'Category:', 'hvac-community-events' ); ?></label>
            <select id="hvac_template_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" 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" rows="8" placeholder="<?php _e( 'Email content will be copied from the form above...', '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 to insert it into your template:', 'hvac-community-events' ); ?></p>
            <div class="hvac-placeholder-grid">
                <!-- Populated by JavaScript -->
            </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="button" 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>
    </div>
</div>

<!-- Add template toggle button -->
<div class="hvac-template-actions" style="margin-bottom: 20px;">
    <button type="button" class="hvac-template-toggle">
        📝 <?php _e( 'Use Email Template', 'hvac-community-events' ); ?>
    </button>
</div>

<script>
// Auto-populate template content when saving current email
if (typeof HVACTemplates !== 'undefined') {
    const originalSaveCurrentEmail = HVACTemplates.saveCurrentEmailAsTemplate;
    
    HVACTemplates.saveCurrentEmailAsTemplate = function() {
        const content = this.getCurrentEmailContent();
        const subject = this.getCurrentEmailSubject();
        
        if (!content && !subject) {
            this.showMessage('<?php echo esc_js(__('No email content to save as template', 'hvac-community-events')); ?>', 'error');
            return;
        }
        
        // Pre-fill form with current email content
        $('#hvac_template_title').val(subject || '<?php echo esc_js(__('New Template', 'hvac-community-events')); ?>');
        $('#hvac_template_content').val(content);
        
        // Show the form
        $('.hvac-template-form').addClass('active');
        $('#hvac-template-form-title').text('<?php echo esc_js(__('Save Current Email as Template', 'hvac-community-events')); ?>');
        
        // Scroll to form
        $('.hvac-template-form')[0].scrollIntoView({ behavior: 'smooth' });
        
        this.isEditing = true;
        this.currentTemplateId = null;
    };
}
</script>