<?php
/**
 * admin/email-config.php - Email Configuration & Template Management
 */

require_once __DIR__ . '/includes/base.php';

if (!hasAdminPermission('manage_email_config')) {
    setFlashMessage('Access denied.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [['title' => 'Email Configuration', 'url' => '']];

renderAdminHeader('Email Configuration', $breadcrumbs);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold"><i class="bi bi-envelope-gear me-2"></i>Email Configuration</h2>
        <p class="text-muted mb-0">Manage SMTP settings and email templates</p>
    </div>
    <button class="btn btn-primary" onclick="sendTestEmail()">
        <i class="bi bi-send me-2"></i>Send Test Email
    </button>
</div>

<!-- Tabs -->
<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link active" data-bs-toggle="tab" href="#smtp">SMTP Settings</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#templates">Email Templates</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#queue">Email Queue</a>
    </li>
</ul>

<div class="tab-content">
    <!-- SMTP Settings -->
    <div class="tab-pane fade show active" id="smtp">
        <div class="row">
            <div class="col-md-8">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white">
                        <h5 class="mb-0 fw-bold">SMTP Configuration</h5>
                    </div>
                    <div class="card-body">
                        <form id="smtpForm">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">SMTP Host *</label>
                                    <input type="text" class="form-control" name="smtp_host" required placeholder="smtp.gmail.com">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">SMTP Port *</label>
                                    <input type="number" class="form-control" name="smtp_port" required placeholder="587">
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">SMTP Username *</label>
                                    <input type="text" class="form-control" name="smtp_username" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">SMTP Password *</label>
                                    <div class="input-group">
                                        <input type="password" class="form-control" name="smtp_password" id="smtp_password" required>
                                        <button class="btn btn-outline-secondary" type="button" onclick="togglePassword()">
                                            <i class="bi bi-eye" id="passwordToggleIcon"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Encryption</label>
                                    <select class="form-select" name="smtp_encryption">
                                        <option value="tls">TLS</option>
                                        <option value="ssl">SSL</option>
                                        <option value="">None</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">From Email *</label>
                                    <input type="email" class="form-control" name="from_email" required>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">From Name</label>
                                <input type="text" class="form-control" name="from_name" placeholder="AIMS System">
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save me-2"></i>Save SMTP Settings
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="card border-0 shadow-sm mb-3">
                    <div class="card-header bg-white">
                        <h6 class="mb-0 fw-bold">Common SMTP Providers</h6>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            <button class="btn btn-outline-secondary text-start" onclick="useGmail()">
                                <i class="bi bi-google me-2"></i>Gmail
                            </button>
                            <button class="btn btn-outline-secondary text-start" onclick="useOutlook()">
                                <i class="bi bi-microsoft me-2"></i>Outlook
                            </button>
                            <button class="btn btn-outline-secondary text-start" onclick="useSendGrid()">
                                <i class="bi bi-envelope me-2"></i>SendGrid
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Email Templates -->
    <div class="tab-pane fade" id="templates">
        <div class="d-flex justify-content-between mb-3">
            <h5 class="fw-bold">Email Templates</h5>
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#templateModal">
                <i class="bi bi-plus-circle me-2"></i>New Template
            </button>
        </div>
        
        <div class="row" id="templatesContainer">
            <div class="col-12 text-center py-5">
                <div class="spinner-border"></div>
            </div>
        </div>
    </div>
    
    <!-- Email Queue -->
    <div class="tab-pane fade" id="queue">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <table class="table" id="queueTable">
                    <thead>
                        <tr>
                            <th>To</th>
                            <th>Subject</th>
                            <th>Status</th>
                            <th>Attempts</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="6" class="text-center py-5"><div class="spinner-border"></div></td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Template Modal -->
<div class="modal fade" id="templateModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Email Template</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="templateForm">
                <input type="hidden" name="template_id" id="template_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Template Name *</label>
                            <input type="text" class="form-control" name="template_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Template Key *</label>
                            <input type="text" class="form-control" name="template_key" required placeholder="welcome_email">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Subject *</label>
                        <input type="text" class="form-control" name="subject" required placeholder="Use {{name}} for variables">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Email Body *</label>
                        <textarea class="form-control" name="body" rows="10" required></textarea>
                        <small class="text-muted">Available variables: {{name}}, {{email}}, {{link}}, {{code}}</small>
                    </div>
                    
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_active" id="template_active" checked>
                        <label class="form-check-label" for="template_active">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Template</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    loadSMTPSettings();
    loadTemplates();
    loadEmailQueue();
});

function loadSMTPSettings() {
    $.get(APP_URL + '/api/admin.php?action=get_smtp_settings', function(response) {
        if (response.success && response.data) {
            const data = response.data;
            $('[name="smtp_host"]').val(data.smtp_host);
            $('[name="smtp_port"]').val(data.smtp_port);
            $('[name="smtp_username"]').val(data.smtp_username);
            $('[name="smtp_password"]').val(data.smtp_password);
            $('[name="smtp_encryption"]').val(data.smtp_encryption);
            $('[name="from_email"]').val(data.from_email);
            $('[name="from_name"]').val(data.from_name);
        }
    });
}

$('#smtpForm').submit(function(e) {
    e.preventDefault();
    showLoading();
    $.post(APP_URL + '/api/admin.php', $(this).serialize() + '&action=update_smtp_settings', function(response) {
        hideLoading();
        showToast(response.message, response.success ? 'success' : 'error');
    });
});

function loadTemplates() {
    $.get(APP_URL + '/api/admin.php?action=get_email_templates', function(response) {
        if (response.success && response.data.length > 0) {
            let html = '';
            response.data.forEach(template => {
                html += `
                    <div class="col-md-6 mb-3">
                        <div class="card border-0 shadow-sm">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <h6 class="fw-bold mb-1">${template.template_name}</h6>
                                        <small class="text-muted">${template.template_key}</small>
                                    </div>
                                    <span class="badge bg-${template.is_active ? 'success' : 'secondary'}">
                                        ${template.is_active ? 'Active' : 'Inactive'}
                                    </span>
                                </div>
                                <p class="small mb-2"><strong>Subject:</strong> ${template.subject}</p>
                                <div class="d-flex gap-2">
                                    <button class="btn btn-sm btn-outline-primary" onclick="editTemplate(${template.id})">
                                        <i class="bi bi-pencil"></i> Edit
                                    </button>
                                    <button class="btn btn-sm btn-outline-info" onclick="previewTemplate(${template.id})">
                                        <i class="bi bi-eye"></i> Preview
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteTemplate(${template.id})">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            $('#templatesContainer').html(html);
        } else {
            $('#templatesContainer').html('<div class="col-12 text-center py-5">No templates found</div>');
        }
    });
}

function loadEmailQueue() {
    $.get(APP_URL + '/api/admin.php?action=get_email_queue', function(response) {
        if (response.success && response.data.length > 0) {
            let html = '';
            response.data.forEach(email => {
                html += `
                    <tr>
                        <td>${email.to_email}</td>
                        <td>${email.subject}</td>
                        <td><span class="badge bg-${email.status === 'sent' ? 'success' : (email.status === 'pending' ? 'warning' : 'danger')}">${email.status}</span></td>
                        <td>${email.attempts}/${email.max_attempts}</td>
                        <td><small>${email.created_at}</small></td>
                        <td>
                            ${email.status === 'failed' ? '<button class="btn btn-sm btn-outline-primary" onclick="retryEmail(' + email.id + ')"><i class="bi bi-arrow-repeat"></i></button>' : ''}
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteEmail(' + email.id + ')"><i class="bi bi-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
            $('#queueTable tbody').html(html);
        } else {
            $('#queueTable tbody').html('<tr><td colspan="6" class="text-center">No emails in queue</td></tr>');
        }
    });
}

$('#templateForm').submit(function(e) {
    e.preventDefault();
    const formData = $(this).serializeArray();
    formData.push({name: 'action', value: $('#template_id').val() ? 'update_email_template' : 'create_email_template'});
    
    $.post(APP_URL + '/api/admin.php', $.param(formData), function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            $('#templateModal').modal('hide');
            $('#templateForm')[0].reset();
            loadTemplates();
        } else {
            showToast(response.message, 'error');
        }
    });
});

function editTemplate(id) {
    $.get(APP_URL + '/api/admin.php?action=get_email_template&template_id=' + id, function(response) {
        if (response.success) {
            const t = response.data;
            $('#template_id').val(t.id);
            $('[name="template_name"]').val(t.template_name);
            $('[name="template_key"]').val(t.template_key);
            $('[name="subject"]').val(t.subject);
            $('[name="body"]').val(t.body);
            $('[name="is_active"]').prop('checked', t.is_active);
            $('#templateModal').modal('show');
        }
    });
}

function sendTestEmail() {
    Swal.fire({
        title: 'Send Test Email',
        input: 'email',
        inputLabel: 'Test Email Address',
        inputPlaceholder: 'your@email.com',
        showCancelButton: true
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'send_test_email',
                to_email: result.value
            }, function(response) {
                hideLoading();
                showToast(response.message, response.success ? 'success' : 'error');
            });
        }
    });
}

function togglePassword() {
    const input = $('#smtp_password');
    const icon = $('#passwordToggleIcon');
    if (input.attr('type') === 'password') {
        input.attr('type', 'text');
        icon.removeClass('bi-eye').addClass('bi-eye-slash');
    } else {
        input.attr('type', 'password');
        icon.removeClass('bi-eye-slash').addClass('bi-eye');
    }
}

function useGmail() {
    $('[name="smtp_host"]').val('smtp.gmail.com');
    $('[name="smtp_port"]').val('587');
    $('[name="smtp_encryption"]').val('tls');
}

function useOutlook() {
    $('[name="smtp_host"]').val('smtp.office365.com');
    $('[name="smtp_port"]').val('587');
    $('[name="smtp_encryption"]').val('tls');
}

function useSendGrid() {
    $('[name="smtp_host"]').val('smtp.sendgrid.net');
    $('[name="smtp_port"]').val('587');
    $('[name="smtp_encryption"]').val('tls');
}
</script>

<?php renderAdminFooter(); ?>