<?php
session_start();
require_once 'config/config.php';
require_once 'auth/check_auth.php';

// Check if user is logged in and has appropriate permissions
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Email Campaign Management';
$currentPage = 'email-templates';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- AdminLTE CSS -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap4.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <!-- Summernote -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css">
    
    <style>
        .email-stats {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 15px;
        }
        
        .stat-icon {
            font-size: 2rem;
            margin-bottom: 10px;
        }
        
        .template-card {
            transition: all 0.3s ease;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 20px;
            cursor: pointer;
        }
        
        .template-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .template-preview {
            max-height: 200px;
            overflow: hidden;
            border-radius: 8px;
            background: #f8f9fa;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .email-editor {
            min-height: 400px;
        }
        
        .campaign-progress {
            background: #e9ecef;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .progress-step {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .progress-step.active {
            color: #007bff;
            font-weight: bold;
        }
        
        .progress-step.completed {
            color: #28a745;
        }
        
        .recipient-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 10px;
        }
        
        .recipient-item {
            padding: 8px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .email-metrics {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .metric-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .template-builder {
            background: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
        }
        
        .variable-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 15px;
        }
        
        .variable-tag {
            background: #e9ecef;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .variable-tag:hover {
            background: #007bff;
            color: white;
        }
        
        .schedule-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .loading-spinner {
            background: white;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
        }
        
        .template-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .campaign-status {
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: bold;
        }
        
        .status-draft {
            background: #f8f9fa;
            color: #6c757d;
        }
        
        .status-scheduled {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-sending {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .status-sent {
            background: #d4edda;
            color: #155724;
        }
        
        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-envelope text-primary"></i> Email Campaign Management
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">Email Campaigns</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- Email Campaign Statistics -->
                <div class="email-stats">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-primary">
                                    <i class="fas fa-paper-plane"></i>
                                </div>
                                <h3 class="mb-1" id="totalCampaigns">0</h3>
                                <p class="mb-0">Total Campaigns</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-success">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <h3 class="mb-1" id="sentEmails">0</h3>
                                <p class="mb-0">Emails Sent</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-info">
                                    <i class="fas fa-eye"></i>
                                </div>
                                <h3 class="mb-1" id="openRate">0%</h3>
                                <p class="mb-0">Open Rate</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-warning">
                                    <i class="fas fa-mouse-pointer"></i>
                                </div>
                                <h3 class="mb-1" id="clickRate">0%</h3>
                                <p class="mb-0">Click Rate</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="row">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-plus"></i> Create Campaign
                                </h3>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">Start a new email campaign with our advanced editor.</p>
                                <button class="btn btn-primary btn-block" onclick="createNewCampaign()">
                                    <i class="fas fa-magic"></i> Create Campaign
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-template"></i> Template Library
                                </h3>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">Browse and manage email templates.</p>
                                <button class="btn btn-success btn-block" onclick="showTemplateLibrary()">
                                    <i class="fas fa-folder"></i> Browse Templates
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-line"></i> Analytics
                                </h3>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">View detailed campaign performance metrics.</p>
                                <button class="btn btn-info btn-block" onclick="showAnalytics()">
                                    <i class="fas fa-analytics"></i> View Analytics
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Campaign Builder Section -->
                <div class="card template-builder" id="campaignBuilder" style="display: none;">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit"></i> Campaign Builder
                        </h3>
                        <div class="card-tools">
                            <button class="btn btn-sm btn-secondary" onclick="closeCampaignBuilder()">
                                <i class="fas fa-times"></i> Close
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="campaign-progress">
                            <div class="progress-step active" id="step1">
                                <i class="fas fa-info-circle"></i>
                                <span class="ml-2">1. Campaign Details</span>
                            </div>
                            <div class="progress-step" id="step2">
                                <i class="fas fa-edit"></i>
                                <span class="ml-2">2. Design Email</span>
                            </div>
                            <div class="progress-step" id="step3">
                                <i class="fas fa-users"></i>
                                <span class="ml-2">3. Select Recipients</span>
                            </div>
                            <div class="progress-step" id="step4">
                                <i class="fas fa-clock"></i>
                                <span class="ml-2">4. Schedule & Send</span>
                            </div>
                        </div>

                        <!-- Step 1: Campaign Details -->
                        <div class="step-content" id="stepContent1">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Campaign Name</label>
                                        <input type="text" class="form-control" id="campaignName" placeholder="Enter campaign name">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Campaign Type</label>
                                        <select class="form-control" id="campaignType">
                                            <option value="newsletter">Newsletter</option>
                                            <option value="announcement">Announcement</option>
                                            <option value="event">Event Notification</option>
                                            <option value="reminder">Reminder</option>
                                            <option value="welcome">Welcome Message</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Campaign Description</label>
                                <textarea class="form-control" id="campaignDescription" rows="3" placeholder="Brief description of this campaign"></textarea>
                            </div>
                            <button class="btn btn-primary" onclick="nextStep(2)">
                                Next: Design Email <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>

                        <!-- Step 2: Design Email -->
                        <div class="step-content" id="stepContent2" style="display: none;">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label>Email Subject</label>
                                        <input type="text" class="form-control" id="emailSubject" placeholder="Enter email subject">
                                    </div>
                                    <div class="form-group">
                                        <label>Email Content</label>
                                        <textarea class="form-control email-editor" id="emailContent"></textarea>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <h6>Template Variables</h6>
                                    <div class="variable-tags">
                                        <span class="variable-tag" onclick="insertVariable('{{member_name}}')">{{member_name}}</span>
                                        <span class="variable-tag" onclick="insertVariable('{{member_id}}')">{{member_id}}</span>
                                        <span class="variable-tag" onclick="insertVariable('{{organization}}')">{{organization}}</span>
                                        <span class="variable-tag" onclick="insertVariable('{{current_date}}')">{{current_date}}</span>
                                        <span class="variable-tag" onclick="insertVariable('{{membership_status}}')">{{membership_status}}</span>
                                        <span class="variable-tag" onclick="insertVariable('{{expiry_date}}')">{{expiry_date}}</span>
                                    </div>
                                    <div class="form-group">
                                        <label>Select Template</label>
                                        <select class="form-control" id="emailTemplate" onchange="loadTemplate()">
                                            <option value="">Choose a template</option>
                                            <option value="welcome">Welcome Message</option>
                                            <option value="reminder">Payment Reminder</option>
                                            <option value="event">Event Invitation</option>
                                            <option value="newsletter">Newsletter</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-3">
                                <button class="btn btn-secondary" onclick="previousStep(1)">
                                    <i class="fas fa-arrow-left"></i> Previous
                                </button>
                                <button class="btn btn-primary ml-2" onclick="nextStep(3)">
                                    Next: Select Recipients <i class="fas fa-arrow-right"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 3: Select Recipients -->
                        <div class="step-content" id="stepContent3" style="display: none;">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>Recipient Groups</h6>
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="allMembers">
                                            <label class="custom-control-label" for="allMembers">All Active Members</label>
                                        </div>
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="individualMembers">
                                            <label class="custom-control-label" for="individualMembers">Individual Members</label>
                                        </div>
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="familyMembers">
                                            <label class="custom-control-label" for="familyMembers">Family Members</label>
                                        </div>
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="expiringMembers">
                                            <label class="custom-control-label" for="expiringMembers">Expiring Memberships</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <h6>Selected Recipients (<span id="recipientCount">0</span>)</h6>
                                    <div class="recipient-list" id="recipientList">
                                        <!-- Recipients will be populated here -->
                                    </div>
                                </div>
                            </div>
                            <div class="mt-3">
                                <button class="btn btn-secondary" onclick="previousStep(2)">
                                    <i class="fas fa-arrow-left"></i> Previous
                                </button>
                                <button class="btn btn-primary ml-2" onclick="nextStep(4)">
                                    Next: Schedule & Send <i class="fas fa-arrow-right"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 4: Schedule & Send -->
                        <div class="step-content" id="stepContent4" style="display: none;">
                            <div class="schedule-section">
                                <h6>Schedule Options</h6>
                                <div class="form-group">
                                    <div class="custom-control custom-radio">
                                        <input type="radio" class="custom-control-input" id="sendNow" name="scheduleType" value="now" checked>
                                        <label class="custom-control-label" for="sendNow">Send Now</label>
                                    </div>
                                    <div class="custom-control custom-radio">
                                        <input type="radio" class="custom-control-input" id="scheduleLater" name="scheduleType" value="later">
                                        <label class="custom-control-label" for="scheduleLater">Schedule for Later</label>
                                    </div>
                                </div>
                                <div class="row" id="scheduleDateTime" style="display: none;">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Schedule Date</label>
                                            <input type="date" class="form-control" id="scheduleDate">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Schedule Time</label>
                                            <input type="time" class="form-control" id="scheduleTime">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="campaign-summary">
                                <h6>Campaign Summary</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <tr>
                                            <td><strong>Campaign Name:</strong></td>
                                            <td id="summaryName">-</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Type:</strong></td>
                                            <td id="summaryType">-</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Subject:</strong></td>
                                            <td id="summarySubject">-</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Recipients:</strong></td>
                                            <td id="summaryRecipients">-</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Schedule:</strong></td>
                                            <td id="summarySchedule">-</td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            
                            <div class="mt-3">
                                <button class="btn btn-secondary" onclick="previousStep(3)">
                                    <i class="fas fa-arrow-left"></i> Previous
                                </button>
                                <button class="btn btn-success ml-2" onclick="sendCampaign()">
                                    <i class="fas fa-paper-plane"></i> Send Campaign
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Campaigns List -->
                <div class="card" id="campaignsList">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list"></i> Email Campaigns
                        </h3>
                        <div class="card-tools">
                            <button class="btn btn-primary btn-sm" onclick="createNewCampaign()">
                                <i class="fas fa-plus"></i> New Campaign
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="campaignsTable">
                                <thead>
                                    <tr>
                                        <th>Campaign</th>
                                        <th>Type</th>
                                        <th>Recipients</th>
                                        <th>Status</th>
                                        <th>Sent</th>
                                        <th>Opens</th>
                                        <th>Clicks</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="campaignsTableBody">
                                    <!-- Data will be loaded here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner">
        <i class="fas fa-spinner fa-spin fa-2x"></i>
        <p class="mt-2">Processing...</p>
    </div>
</div>

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>

<!-- Custom JavaScript -->
<script src="dist/js/preloader.js"></script>
<script src="dist/js/theme-manager.js"></script>
<script src="dist/js/toast.js"></script>
<script src="dist/js/breadcrumbs.js"></script>

<script>
// Industrial-Level Email Campaign Management System
$(document).ready(function() {
    // Initialize the page
    loadCampaigns();
    loadStatistics();
    initializeEditor();
    setupEventListeners();
});

let currentStep = 1;
let campaignData = {};

function initializeEditor() {
    $('#emailContent').summernote({
        height: 300,
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'italic', 'underline', 'clear']],
            ['fontname', ['fontname']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['table', ['table']],
            ['insert', ['link', 'picture', 'video']],
            ['view', ['fullscreen', 'codeview', 'help']]
        ]
    });
}

function setupEventListeners() {
    // Schedule type radio buttons
    $('input[name="scheduleType"]').on('change', function() {
        if ($(this).val() === 'later') {
            $('#scheduleDateTime').show();
        } else {
            $('#scheduleDateTime').hide();
        }
    });
    
    // Recipient checkboxes
    $('#allMembers, #individualMembers, #familyMembers, #expiringMembers').on('change', function() {
        updateRecipientList();
    });
}

function loadCampaigns() {
    $.ajax({
        url: 'api/email/campaigns/fetch.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const tbody = $('#campaignsTableBody');
                tbody.empty();
                
                response.campaigns.forEach(function(campaign) {
                    tbody.append(createCampaignRow(campaign));
                });
                
                // Initialize DataTable
                if ($.fn.DataTable.isDataTable('#campaignsTable')) {
                    $('#campaignsTable').DataTable().destroy();
                }
                $('#campaignsTable').DataTable({
                    responsive: true,
                    lengthChange: false,
                    autoWidth: false,
                    pageLength: 25
                });
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Error loading campaigns');
            }
        }
    });
}

function createCampaignRow(campaign) {
    const statusClass = getStatusClass(campaign.status);
    
    return `
        <tr>
            <td>
                <div class="font-weight-bold">${campaign.name}</div>
                <div class="text-muted small">${campaign.subject}</div>
            </td>
            <td>
                <span class="badge badge-info">${campaign.type}</span>
            </td>
            <td>${campaign.recipient_count}</td>
            <td>
                <span class="campaign-status ${statusClass}">${campaign.status}</span>
            </td>
            <td>${campaign.sent_count || 0}</td>
            <td>${campaign.open_count || 0} (${campaign.open_rate || 0}%)</td>
            <td>${campaign.click_count || 0} (${campaign.click_rate || 0}%)</td>
            <td>${formatDate(campaign.created_at)}</td>
            <td>
                <div class="btn-group">
                    <button class="btn btn-sm btn-primary" onclick="viewCampaign(${campaign.id})" title="View">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-warning" onclick="editCampaign(${campaign.id})" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-info" onclick="duplicateCampaign(${campaign.id})" title="Duplicate">
                        <i class="fas fa-copy"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteCampaign(${campaign.id})" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
        </tr>
    `;
}

function getStatusClass(status) {
    switch(status) {
        case 'draft': return 'status-draft';
        case 'scheduled': return 'status-scheduled';
        case 'sending': return 'status-sending';
        case 'sent': return 'status-sent';
        case 'failed': return 'status-failed';
        default: return 'status-draft';
    }
}

function loadStatistics() {
    $.ajax({
        url: 'api/email/campaigns/stats.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalCampaigns').text(response.stats.total);
                $('#sentEmails').text(response.stats.sent);
                $('#openRate').text(response.stats.open_rate + '%');
                $('#clickRate').text(response.stats.click_rate + '%');
            }
        },
        error: function() {
            // Set default values on error
            $('#totalCampaigns').text('0');
            $('#sentEmails').text('0');
            $('#openRate').text('0%');
            $('#clickRate').text('0%');
        }
    });
}

function createNewCampaign() {
    $('#campaignBuilder').show();
    $('#campaignsList').hide();
    currentStep = 1;
    campaignData = {};
    updateStepProgress();
}

function closeCampaignBuilder() {
    $('#campaignBuilder').hide();
    $('#campaignsList').show();
    currentStep = 1;
    campaignData = {};
    clearForm();
}

function nextStep(step) {
    if (validateCurrentStep()) {
        saveCurrentStepData();
        currentStep = step;
        updateStepProgress();
        showStepContent(step);
        
        if (step === 4) {
            updateCampaignSummary();
        }
    }
}

function previousStep(step) {
    currentStep = step;
    updateStepProgress();
    showStepContent(step);
}

function updateStepProgress() {
    $('.progress-step').removeClass('active completed');
    
    for (let i = 1; i <= 4; i++) {
        if (i < currentStep) {
            $(`#step${i}`).addClass('completed');
        } else if (i === currentStep) {
            $(`#step${i}`).addClass('active');
        }
    }
}

function showStepContent(step) {
    $('.step-content').hide();
    $(`#stepContent${step}`).show();
}

function validateCurrentStep() {
    switch(currentStep) {
        case 1:
            return $('#campaignName').val().trim() !== '';
        case 2:
            return $('#emailSubject').val().trim() !== '' && $('#emailContent').summernote('code').trim() !== '';
        case 3:
            return $('.custom-control-input:checked').length > 0;
        case 4:
            return true;
        default:
            return true;
    }
}

function saveCurrentStepData() {
    switch(currentStep) {
        case 1:
            campaignData.name = $('#campaignName').val();
            campaignData.type = $('#campaignType').val();
            campaignData.description = $('#campaignDescription').val();
            break;
        case 2:
            campaignData.subject = $('#emailSubject').val();
            campaignData.content = $('#emailContent').summernote('code');
            campaignData.template = $('#emailTemplate').val();
            break;
        case 3:
            campaignData.recipients = getSelectedRecipients();
            break;
        case 4:
            campaignData.schedule_type = $('input[name="scheduleType"]:checked').val();
            if (campaignData.schedule_type === 'later') {
                campaignData.schedule_date = $('#scheduleDate').val();
                campaignData.schedule_time = $('#scheduleTime').val();
            }
            break;
    }
}

function getSelectedRecipients() {
    const recipients = [];
    if ($('#allMembers').is(':checked')) recipients.push('all');
    if ($('#individualMembers').is(':checked')) recipients.push('individual');
    if ($('#familyMembers').is(':checked')) recipients.push('family');
    if ($('#expiringMembers').is(':checked')) recipients.push('expiring');
    return recipients;
}

function updateRecipientList() {
    const recipients = getSelectedRecipients();
    
    $.ajax({
        url: 'api/email/campaigns/recipients.php',
        method: 'POST',
        data: { recipient_types: recipients },
        success: function(response) {
            if (response.success) {
                const recipientList = $('#recipientList');
                recipientList.empty();
                
                response.recipients.forEach(function(recipient) {
                    recipientList.append(`
                        <div class="recipient-item">
                            <span>${recipient.name}</span>
                            <small class="text-muted">${recipient.email}</small>
                        </div>
                    `);
                });
                
                $('#recipientCount').text(response.recipients.length);
            }
        }
    });
}

function updateCampaignSummary() {
    $('#summaryName').text(campaignData.name || '-');
    $('#summaryType').text(campaignData.type || '-');
    $('#summarySubject').text(campaignData.subject || '-');
    $('#summaryRecipients').text($('#recipientCount').text() + ' recipients');
    
    if (campaignData.schedule_type === 'now') {
        $('#summarySchedule').text('Send immediately');
    } else {
        $('#summarySchedule').text(`${campaignData.schedule_date} at ${campaignData.schedule_time}`);
    }
}

function sendCampaign() {
    if (!validateCurrentStep()) {
        if (window.ksoToast) {
            window.ksoToast.error('Please fill in all required fields');
        }
        return;
    }
    
    saveCurrentStepData();
    
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Send Campaign?',
            text: `This will send the email to ${$('#recipientCount').text()} recipients.`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, send it!'
        }).then((result) => {
            if (result.isConfirmed) {
                performSendCampaign();
            }
        });
    } else {
        if (confirm(`Are you sure you want to send this campaign to ${$('#recipientCount').text()} recipients?`)) {
            performSendCampaign();
        }
    }
}

function performSendCampaign() {
    $('#loadingOverlay').show();
    
    $.ajax({
        url: 'api/email/campaigns/send.php',
        method: 'POST',
        data: campaignData,
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Campaign sent successfully!');
                }
                closeCampaignBuilder();
                loadCampaigns();
                loadStatistics();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Campaign failed: ' + response.message);
                }
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Campaign sending failed');
            }
        },
        complete: function() {
            $('#loadingOverlay').hide();
        }
    });
}

function insertVariable(variable) {
    $('#emailContent').summernote('insertText', variable);
}

function loadTemplate() {
    const template = $('#emailTemplate').val();
    if (template) {
        $.ajax({
            url: 'api/email/templates/get.php',
            method: 'GET',
            data: { template: template },
            success: function(response) {
                if (response.success) {
                    $('#emailContent').summernote('code', response.content);
                    if (response.subject) {
                        $('#emailSubject').val(response.subject);
                    }
                }
            }
        });
    }
}

function viewCampaign(id) {
    window.open(`api/email/campaigns/view.php?id=${id}`, '_blank');
}

function editCampaign(id) {
    // Load campaign data and open builder
    $.ajax({
        url: 'api/email/campaigns/get.php',
        method: 'GET',
        data: { id: id },
        success: function(response) {
            if (response.success) {
                campaignData = response.campaign;
                populateForm(campaignData);
                createNewCampaign();
            }
        }
    });
}

function duplicateCampaign(id) {
    $.ajax({
        url: 'api/email/campaigns/duplicate.php',
        method: 'POST',
        data: { id: id },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Campaign duplicated successfully!');
                }
                loadCampaigns();
            }
        }
    });
}

function deleteCampaign(id) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Delete Campaign?',
            text: 'This action cannot be undone.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                performDeleteCampaign(id);
            }
        });
    } else {
        if (confirm('Are you sure you want to delete this campaign?')) {
            performDeleteCampaign(id);
        }
    }
}

function performDeleteCampaign(id) {
    $.ajax({
        url: 'api/email/campaigns/delete.php',
        method: 'POST',
        data: { id: id },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Campaign deleted successfully!');
                }
                loadCampaigns();
                loadStatistics();
            }
        }
    });
}

function showTemplateLibrary() {
    // Implementation for template library
    if (window.ksoToast) {
        window.ksoToast.info('Template library coming soon!');
    }
}

function showAnalytics() {
    // Implementation for analytics
    if (window.ksoToast) {
        window.ksoToast.info('Analytics dashboard coming soon!');
    }
}

function populateForm(data) {
    $('#campaignName').val(data.name || '');
    $('#campaignType').val(data.type || '');
    $('#campaignDescription').val(data.description || '');
    $('#emailSubject').val(data.subject || '');
    $('#emailContent').summernote('code', data.content || '');
}

function clearForm() {
    $('#campaignName').val('');
    $('#campaignType').val('newsletter');
    $('#campaignDescription').val('');
    $('#emailSubject').val('');
    $('#emailContent').summernote('code', '');
    $('#emailTemplate').val('');
    $('.custom-control-input').prop('checked', false);
    $('#recipientList').empty();
    $('#recipientCount').text('0');
    $('input[name="scheduleType"][value="now"]').prop('checked', true);
    $('#scheduleDateTime').hide();
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}
</script>

</body>
</html>
                                            <td><strong>Recipients:</strong></td>
                                            <td id="summaryRecipients">-</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Schedule:</strong></td>
                                            <td id="summarySchedule">-</td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            
                            <div class="mt-3">
                                <button class="btn btn-secondary" onclick="previousStep(3)">
                                    <i class="fas fa-arrow-left"></i> Previous
                                </button>
                                <button class="btn btn-success ml-2" onclick="sendCampaign()">
                                    <i class="fas fa-paper-plane"></i> Send Campaign
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Campaigns List -->
                <div class="card" id="campaignsList">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list"></i> Email Campaigns
                        </h3>
                        <div class="card-tools">
                            <button class="btn btn-primary btn-sm" onclick="createNewCampaign()">
                                <i class="fas fa-plus"></i> New Campaign
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="campaignsTable">
                                <thead>
                                    <tr>
                                        <th>Campaign</th>
                                        <th>Type</th>
                                        <th>Recipients</th>
                                        <th>Status</th>
                                        <th>Sent</th>
                                        <th>Opens</th>
                                        <th>Clicks</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="campaignsTableBody">
                                    <!-- Data will be loaded here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner">
        <i class="fas fa-spinner fa-spin fa-2x"></i>
        <p class="mt-2">Processing...</p>
    </div>
</div>
                                <a href="#" class="list-group-item list-group-item-action" data-category="reminder">
                                    <i class="fas fa-clock"></i> Reminders
                                </a>
                                <a href="#" class="list-group-item list-group-item-action" data-category="event">
                                    <i class="fas fa-calendar"></i> Event Invitations
                                </a>
                                <a href="#" class="list-group-item list-group-item-action" data-category="membership">
                                    <i class="fas fa-users"></i> Membership
                                </a>
                                <a href="#" class="list-group-item list-group-item-action" data-category="newsletter">
                                    <i class="fas fa-newspaper"></i> Newsletter
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Quick Actions</h3>
                        </div>
                        <div class="card-body">
                            <button type="button" class="btn btn-primary btn-block" data-toggle="modal" data-target="#createTemplateModal">
                                <i class="fas fa-plus"></i> Create New Template
                            </button>
                            <button type="button" class="btn btn-info btn-block" onclick="importTemplate()">
                                <i class="fas fa-upload"></i> Import Template
                            </button>
                            <button type="button" class="btn btn-warning btn-block" onclick="exportTemplates()">
                                <i class="fas fa-download"></i> Export Templates
                            </button>
                        </div>
                    </div>
                </div>

                <div class="col-md-8">
                    <!-- Templates Grid -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Email Templates</h3>
                            <div class="card-tools">
                                <div class="input-group input-group-sm" style="width: 250px;">
                                    <input type="text" id="searchTemplates" class="form-control" placeholder="Search templates...">
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-default">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row" id="templatesGrid">
                                <!-- Templates will be populated here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Create Template Modal -->
<div class="modal fade" id="createTemplateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Create Email Template</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="createTemplateForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Template Name *</label>
                                <input type="text" class="form-control" name="template_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Category *</label>
                                <select class="form-control" name="category" required>
                                    <option value="">Select Category</option>
                                    <option value="welcome">Welcome Messages</option>
                                    <option value="notification">Notifications</option>
                                    <option value="reminder">Reminders</option>
                                    <option value="event">Event Invitations</option>
                                    <option value="membership">Membership</option>
                                    <option value="newsletter">Newsletter</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Subject *</label>
                        <input type="text" class="form-control" name="subject" required>
                    </div>
                    <div class="form-group">
                        <label>Email Body *</label>
                        <textarea id="emailEditor" name="content" class="form-control" rows="15" required></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Variables Available</label>
                                <div class="bg-light p-3 rounded">
                                    <small>
                                        <strong>Member Variables:</strong><br>
                                        {{member_name}}, {{member_email}}, {{member_id}}<br>
                                        {{membership_type}}, {{membership_expiry}}<br><br>
                                        <strong>Organization Variables:</strong><br>
                                        {{org_name}}, {{org_address}}, {{org_phone}}<br>
                                        {{org_email}}, {{org_website}}<br><br>
                                        <strong>Event Variables:</strong><br>
                                        {{event_name}}, {{event_date}}, {{event_location}}<br>
                                        {{event_time}}, {{registration_link}}
                                    </small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Template Preview</label>
                                <div id="templatePreview" class="bg-light p-3 rounded" style="height: 200px; overflow-y: auto;">
                                    <small class="text-muted">Preview will appear here...</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-info" onclick="previewTemplate()">Preview</button>
                    <button type="submit" class="btn btn-primary">Create Template</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Template Modal -->
<div class="modal fade" id="editTemplateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Edit Email Template</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="editTemplateForm">
                <div class="modal-body">
                    <input type="hidden" id="edit_template_id" name="template_id">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Template Name *</label>
                                <input type="text" class="form-control" name="template_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Category *</label>
                                <select class="form-control" name="category" required>
                                    <option value="">Select Category</option>
                                    <option value="welcome">Welcome Messages</option>
                                    <option value="notification">Notifications</option>
                                    <option value="reminder">Reminders</option>
                                    <option value="event">Event Invitations</option>
                                    <option value="membership">Membership</option>
                                    <option value="newsletter">Newsletter</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Subject *</label>
                        <input type="text" class="form-control" name="subject" required>
                    </div>
                    <div class="form-group">
                        <label>Email Body *</label>
                        <textarea id="editEmailEditor" name="content" class="form-control" rows="15" required></textarea>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="editIsActive" name="is_active" checked>
                            <label class="custom-control-label" for="editIsActive">Active Template</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-info" onclick="testTemplate()">Test Send</button>
                    <button type="submit" class="btn btn-primary">Update Template</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Test Email Modal -->
<div class="modal fade" id="testEmailModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Test Email</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="testEmailForm">
                <div class="modal-body">
                    <input type="hidden" id="test_template_id" name="template_id">
                    <div class="form-group">
                        <label>Test Email Address</label>
                        <input type="email" class="form-control" name="test_email" required>
                    </div>
                    <div class="form-group">
                        <label>Test Member (for variables)</label>
                        <select class="form-control" name="test_member_id">
                            <option value="">Use dummy data</option>
                            <!-- Will be populated with actual members -->
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Send Test Email</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Include Rich Text Editor -->
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js"></script>

<script>
let currentCategory = 'all';

$(document).ready(function() {
    loadTemplates();
    loadTestMembers();
    initializeEditor();
    
    // Category filter
    $('.list-group-item[data-category]').click(function(e) {
        e.preventDefault();
        $('.list-group-item').removeClass('active');
        $(this).addClass('active');
        currentCategory = $(this).data('category');
        loadTemplates();
    });
    
    // Search functionality
    $('#searchTemplates').on('input', function() {
        loadTemplates();
    });
});

function initializeEditor() {
    tinymce.init({
        selector: '#emailEditor, #editEmailEditor',
        height: 300,
        menubar: false,
        plugins: [
            'advlist autolink lists link image charmap print preview anchor',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table paste code help wordcount'
        ],
        toolbar: 'undo redo | formatselect | ' +
            'bold italic backcolor | alignleft aligncenter ' +
            'alignright alignjustify | bullist numlist outdent indent | ' +
            'removeformat | help',
        content_style: 'body { font-family: Arial, Helvetica, sans-serif; font-size: 14px }',
        setup: function(editor) {
            editor.on('change', function() {
                updatePreview();
            });
        }
    });
}

function loadTemplates() {
    const search = $('#searchTemplates').val();
    
    $.ajax({
        url: 'api/fetch_email_templates.php',
        type: 'GET',
        data: {
            category: currentCategory,
            search: search
        },
        success: function(response) {
            if (response.success) {
                let html = '';
                response.templates.forEach(function(template) {
                    html += `
                        <div class="col-md-6 mb-3">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">${template.template_name}</h5>
                                    <p class="card-text">
                                        <small class="text-muted">Category: ${template.category}</small><br>
                                        <strong>Subject:</strong> ${template.subject}<br>
                                        <span class="badge badge-${template.is_active ? 'success' : 'secondary'}">
                                            ${template.is_active ? 'Active' : 'Inactive'}
                                        </span>
                                    </p>
                                    <div class="btn-group btn-group-sm">
                                        <button class="btn btn-outline-primary" onclick="editTemplate(${template.id})">
                                            <i class="fas fa-edit"></i> Edit
                                        </button>
                                        <button class="btn btn-outline-success" onclick="useTemplate(${template.id})">
                                            <i class="fas fa-paper-plane"></i> Use
                                        </button>
                                        <button class="btn btn-outline-info" onclick="duplicateTemplate(${template.id})">
                                            <i class="fas fa-copy"></i> Duplicate
                                        </button>
                                        <button class="btn btn-outline-danger" onclick="deleteTemplate(${template.id})">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    </div>
                                </div>
                                <div class="card-footer">
                                    <small class="text-muted">Created: ${template.created_at}</small>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                if (html === '') {
                    html = '<div class="col-12 text-center"><p class="text-muted">No templates found</p></div>';
                }
                
                $('#templatesGrid').html(html);
            }
        }
    });
}

function loadTestMembers() {
    $.ajax({
        url: 'api/fetch_test_members.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                let options = '<option value="">Use dummy data</option>';
                response.members.forEach(function(member) {
                    options += `<option value="${member.id}">${member.first_name} ${member.last_name}</option>`;
                });
                $('#testEmailForm select[name="test_member_id"]').html(options);
            }
        }
    });
}

function editTemplate(templateId) {
    $.ajax({
        url: 'api/fetch_email_template.php',
        type: 'GET',
        data: { id: templateId },
        success: function(response) {
            if (response.success) {
                const template = response.template;
                
                $('#edit_template_id').val(template.id);
                $('#editTemplateForm input[name="template_name"]').val(template.template_name);
                $('#editTemplateForm select[name="category"]').val(template.category);
                $('#editTemplateForm input[name="subject"]').val(template.subject);
                $('#editIsActive').prop('checked', template.is_active == 1);
                
                tinymce.get('editEmailEditor').setContent(template.content);
                
                $('#editTemplateModal').modal('show');
            }
        }
    });
}

function useTemplate(templateId) {
    window.location.href = `email-campaigns.php?template_id=${templateId}`;
}

function duplicateTemplate(templateId) {
    $.ajax({
        url: 'api/duplicate_email_template.php',
        type: 'POST',
        data: { template_id: templateId },
        success: function(response) {
            if (response.success) {
                toastr.success('Template duplicated successfully');
                loadTemplates();
            } else {
                toastr.error(response.message);
            }
        }
    });
}

function deleteTemplate(templateId) {
    if (confirm('Are you sure you want to delete this template?')) {
        $.ajax({
            url: 'api/delete_email_template.php',
            type: 'POST',
            data: { template_id: templateId },
            success: function(response) {
                if (response.success) {
                    toastr.success('Template deleted successfully');
                    loadTemplates();
                } else {
                    toastr.error(response.message);
                }
            }
        });
    }
}

function previewTemplate() {
    const content = tinymce.get('emailEditor').getContent();
    $('#templatePreview').html(content);
}

function testTemplate() {
    const templateId = $('#edit_template_id').val();
    $('#test_template_id').val(templateId);
    $('#testEmailModal').modal('show');
}

function updatePreview() {
    const content = tinymce.get('emailEditor').getContent();
    $('#templatePreview').html(content);
}

// Form submissions
$('#createTemplateForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = $(this).serialize();
    const content = tinymce.get('emailEditor').getContent();
    
    $.ajax({
        url: 'api/create_email_template.php',
        type: 'POST',
        data: formData + '&content=' + encodeURIComponent(content),
        success: function(response) {
            if (response.success) {
                toastr.success('Template created successfully');
                $('#createTemplateModal').modal('hide');
                $('#createTemplateForm')[0].reset();
                tinymce.get('emailEditor').setContent('');
                loadTemplates();
            } else {
                toastr.error(response.message);
            }
        }
    });
});

$('#editTemplateForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = $(this).serialize();
    const content = tinymce.get('editEmailEditor').getContent();
    
    $.ajax({
        url: 'api/update_email_template.php',
        type: 'POST',
        data: formData + '&content=' + encodeURIComponent(content),
        success: function(response) {
            if (response.success) {
                toastr.success('Template updated successfully');
                $('#editTemplateModal').modal('hide');
                loadTemplates();
            } else {
                toastr.error(response.message);
            }
        }
    });
});

$('#testEmailForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'api/send_test_email.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            if (response.success) {
                toastr.success('Test email sent successfully');
                $('#testEmailModal').modal('hide');
            } else {
                toastr.error(response.message);
            }
        }
    });
});
</script>

<?php require_once 'templates/footer.php'; ?>
