<?php 
$pageTitle = 'Templates';
$activePage = 'templates';
include __DIR__ . '/_header.php'; 
?>

<header class="pwa-header">
    <div class="container-fluid">
        <div class="d-flex align-items-center justify-content-between">
            <h1 class="header-title mb-0">
                <i class="bi bi-chat-square-text me-2"></i>
                Message Templates
            </h1>
            <a href="<?php echo URL_PATH; ?>/logout" class="btn-icon" title="Logout">
                <i class="bi bi-box-arrow-right"></i>
            </a>
        </div>
    </div>
</header>

<main class="pwa-content">
    <div class="container-fluid">
        <?php if (!empty($templates)): ?>
            <div class="mb-3">
                <p class="text-muted">Select your default template for birthday messages</p>
            </div>

            <div class="cards-grid">
                <?php foreach ($templates as $template): ?>
                    <div class="card" data-template-id="<?php echo $template['id']; ?>">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <h5 class="card-title mb-0">
                                    <?php echo htmlspecialchars($template['name']); ?>
                                    <?php if ($defaultTemplate && $defaultTemplate->id == $template['id']): ?>
                                        <span class="badge bg-success ms-2">
                                            <i class="bi bi-check-circle me-1"></i>Default
                                        </span>
                                    <?php endif; ?>
                                </h5>
                            </div>
                            
                            <?php if (!empty($template['description'])): ?>
                                <p class="card-text text-muted small mb-3">
                                    <?php echo htmlspecialchars($template['description']); ?>
                                </p>
                            <?php endif; ?>
                            
                            <div class="alert alert-light mb-3">
                                <small><?php echo nl2br(htmlspecialchars($template['content'])); ?></small>
                            </div>
                            
                            <?php if (!$defaultTemplate || $defaultTemplate->id != $template['id']): ?>
                                <form method="POST" action="<?php echo URL_PATH; ?>/templates">
                                    <input type="hidden" name="template_id" value="<?php echo $template['id']; ?>">
                                    <button type="submit" class="btn btn-primary btn-sm w-100">
                                        <i class="bi bi-check-circle me-1"></i>
                                        Set as Default
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="bi bi-chat-square-text"></i>
                </div>
                <h3 class="empty-title">No Templates Available</h3>
                <p class="empty-text">Contact your administrator to add message templates.</p>
            </div>
        <?php endif; ?>
    </div>
</main>

<?php 
$additionalJS = <<<'JS'
<script>
    function attachFormListeners() {
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const submitBtn = this.querySelector('button[type="submit"]');
                const templateId = this.querySelector('input[name="template_id"]').value;
                const selectedCard = this.closest('.card');
                
                if (submitBtn.disabled) return;
                
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Setting...';
                
                try {
                    const formData = new FormData(this);
                    const response = await fetch(this.action, {
                        method: 'POST',
                        headers: { 'X-Requested-With': 'XMLHttpRequest' },
                        body: formData
                    });
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        Swal.fire({
                            toast: true,
                            position: 'top-end',
                            icon: 'success',
                            title: data.message,
                            showConfirmButton: false,
                            timer: 3000,
                            timerProgressBar: true
                        });
                        
                        document.querySelectorAll('.badge.bg-success').forEach(badge => badge.remove());
                        document.querySelectorAll('form').forEach(f => f.remove());
                        
                        const titleElement = selectedCard.querySelector('.card-title');
                        const badge = document.createElement('span');
                        badge.className = 'badge bg-success ms-2';
                        badge.innerHTML = '<i class="bi bi-check-circle me-1"></i>Default';
                        titleElement.appendChild(badge);
                        
                        document.querySelectorAll('.card').forEach(card => {
                            if (card !== selectedCard && !card.querySelector('form')) {
                                const cardBody = card.querySelector('.card-body');
                                const cardTemplateId = card.getAttribute('data-template-id');
                                
                                const form = document.createElement('form');
                                form.method = 'POST';
                                form.action = `${APP_CONFIG.urlPath}/templates`;
                                
                                const hiddenInput = document.createElement('input');
                                hiddenInput.type = 'hidden';
                                hiddenInput.name = 'template_id';
                                hiddenInput.value = cardTemplateId;
                                
                                const button = document.createElement('button');
                                button.type = 'submit';
                                button.className = 'btn btn-primary btn-sm w-100';
                                button.innerHTML = '<i class="bi bi-check-circle me-1"></i>Set as Default';
                                
                                form.appendChild(hiddenInput);
                                form.appendChild(button);
                                cardBody.appendChild(form);
                            }
                        });
                        
                        attachFormListeners();
                    } else {
                        throw new Error(data.message || 'Failed to set default template');
                    }
                } catch (error) {
                    Swal.fire({
                        toast: true,
                        position: 'top-end',
                        icon: 'error',
                        title: error.message || 'Failed to set default template',
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true
                    });
                    
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="bi bi-check-circle me-1"></i>Set as Default';
                }
            });
        });
    }
    
    attachFormListeners();
</script>
JS;

include __DIR__ . '/_footer.php'; 
?>
