<?php
session_start();

/*
|--------------------------------------------------------------------------
| Detect AJAX
|--------------------------------------------------------------------------
*/
$isAjax = $_SERVER['REQUEST_METHOD'] === 'POST' && (
    isset($_POST['ajax_send_email']) ||
    isset($_POST['ajax_upload_logo'])
);

/*
|--------------------------------------------------------------------------
| Start output buffering ONLY for AJAX
|--------------------------------------------------------------------------
*/
if ($isAjax) {
    ob_start();
}

/*
|--------------------------------------------------------------------------
| Helper: JSON response (single exit point)
|--------------------------------------------------------------------------
*/
function jsonResponse(array $data)
{
    if (ob_get_length()) {
        ob_clean();
    }
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($data);
    exit();
}

/*
|--------------------------------------------------------------------------
| Auth check
|--------------------------------------------------------------------------
*/
if (!isset($_SESSION['admin_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    if ($isAjax) {
        jsonResponse([
            'success' => false,
            'message' => 'Session expired. Please log in again.'
        ]);
    } else {
        header('Location: signin-admin.php');
        exit();
    }
}

/*
|--------------------------------------------------------------------------
| Logout
|--------------------------------------------------------------------------
*/
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: signin-admin.php');
    exit();
}

/*
|--------------------------------------------------------------------------
| Config
|--------------------------------------------------------------------------
*/
require_once 'php/adminconfig.php';

/*
|--------------------------------------------------------------------------
| PHPMailer check
|--------------------------------------------------------------------------
*/
if (!file_exists('PHPMailer-master/src/PHPMailer.php')) {
    if ($isAjax) {
        jsonResponse([
            'success' => false,
            'message' => 'Server mail configuration error.'
        ]);
    } else {
        die('ERROR: PHPMailer library not found.');
    }
}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

/*
|--------------------------------------------------------------------------
| AJAX: Send Email
|--------------------------------------------------------------------------
*/
if ($isAjax && isset($_POST['ajax_send_email'])) {
    try {
        $senderName = $_POST['sender_name'] ?? 'Tradewave TT';
        $subject    = $_POST['email_subject'] ?? 'DOM ALGORITHM EXECUTION';
        $amount     = (float)($_POST['amount'] ?? 0);
        $currency   = $_POST['currency'] ?? 'USD';
        $emailBody  = trim($_POST['email_body'] ?? '');
        $recipients = json_decode($_POST['recipients'] ?? '[]', true);

        $primaryLogo   = $_POST['primary_logo_path'] ?? 'https://tradewavett.xyz/images/icon.png';
        $secondaryLogo = $_POST['secondary_logo_path'] ?? '';

        if (empty($recipients)) {
            jsonResponse(['success' => false, 'message' => 'Please select at least one recipient']);
        }

        if ($emailBody === '') {
            jsonResponse(['success' => false, 'message' => 'Email body cannot be empty']);
        }

        $success = 0;
        $failed  = 0;
        $errors  = [];

        foreach ($recipients as $userId) {
            try {
                $stmt = $conn->prepare(
                    "SELECT firstname, lastname, email FROM users WHERE id = :id"
                );
                $stmt->execute([':id' => $userId]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);

                if (!$user || empty($user['email'])) {
                    $failed++;
                    $errors[] = "Invalid user ID: {$userId}";
                    continue;
                }

                $html = buildEmailTemplate(
                    $user['firstname'],
                    $emailBody,
                    $amount,
                    $currency,
                    $primaryLogo,
                    $secondaryLogo
                );


                // Fallback to PHPMailer
                $mail = new PHPMailer(true);
                $mail->isSMTP();
                $mail->Host       = 'mail.tradewavett.xyz';
                $mail->SMTPAuth   = true;
                $mail->Username   = 'official@tradewavett.xyz';
                $mail->Password   = '#Trader00#';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port       = 587;

                $mail->setFrom('official@tradewavett.xyz', $senderName);
                $mail->addAddress($user['email'], "{$user['firstname']} {$user['lastname']}");
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body    = $html;

                if (file_exists('images/subdoc6.pdf')) {
                    $mail->addAttachment('images/subdoc6.pdf', 'subscription_document.pdf');
                }

                $mail->send();
                $success++;

            } catch (Exception $e) {
                $failed++;
                $errors[] = "Failed to send to {$user['email']}: {$e->getMessage()}";
            }
        }

        jsonResponse([
            'success' => $success > 0,
            'message' => $success > 0
                ? "✅ Email sent to {$success} recipient(s)" . ($failed ? " | Failed: {$failed}" : '')
                : '❌ Failed to send all emails',
            'details' => $errors
        ]);

    } catch (Throwable $e) {
        jsonResponse([
            'success' => false,
            'message' => 'Server error',
            'details' => [$e->getMessage()]
        ]);
    }
}

/*
|--------------------------------------------------------------------------
| AJAX: Logo Upload
|--------------------------------------------------------------------------
*/
if ($isAjax && isset($_POST['ajax_upload_logo'])) {
    $uploadDir = 'uploads/logos/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $result = ['success' => true, 'primaryLogo' => '', 'secondaryLogo' => ''];

    foreach (['primary_logo' => 'primaryLogo', 'secondary_logo' => 'secondaryLogo'] as $field => $key) {
        if (!empty($_FILES[$field]) && $_FILES[$field]['error'] === 0) {
            $name = time() . '_' . basename($_FILES[$field]['name']);
            $path = $uploadDir . $name;
            if (move_uploaded_file($_FILES[$field]['tmp_name'], $path)) {
                $result[$key] = $path;
            }
        }
    }

    jsonResponse($result);
}


// Fetch all users
try {
    $stmt = $conn->query("SELECT id, firstname, lastname, email, status FROM users ORDER BY firstname ASC");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die("Database error: " . $e->getMessage());
}

function buildEmailTemplate($firstName, $bodyText, $amount, $currency, $primaryLogo, $secondaryLogo) {
    $secondaryLogoHtml = $secondaryLogo ? '<img src="' . htmlspecialchars($secondaryLogo) . '" alt="Logo" style="height: 40px; margin-left: 20px;">' : '';
    
    return '
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }
            .email-wrapper { max-width: 650px; margin: 30px auto; background: #ffffff; border-radius: 30px 30px 10px 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
            .email-header { background: linear-gradient(135deg, #8B4513 0%, #A0522D 100%); padding: 30px 20px; text-align: center; }
            .email-header img { height: 50px; vertical-align: middle; border-radius: 50px; }
            .email-body { padding: 40px 30px; color: #333333; line-height: 1.8; }
            .greeting { font-size: 18px; font-weight: 600; color: #8B4513; margin-bottom: 20px; }
            .amount-box { background: #fff5f0; padding: 10px 20px; margin: 8px 0 8px 0; border-radius: 5px; }
            .amount-label { font-size: 14px; color: #666; margin-bottom: 2px; }
            .amount-value { font-size: 25px; font-weight: 600; color: #FF8C00; }
            .cta-button { display: inline-block; background: #8B4513; color: #ffffff; padding: 10px 20px; text-decoration: none; border-radius: 30px; margin: 10px 0; font-weight: 600; transition: background 0.3s; }
            .cta-button:hover { background: #A0522D; }
            .email-footer { background: #f9f9f9; padding: 30px; text-align: center; color: #666; font-size: 13px; border-top: 1px solid #e0e0e0; }
            .footer-links { margin: 15px 0; }
            .footer-links a { color: #8B4513; text-decoration: none; margin: 0 10px; }
            .copyright { margin-top: 15px; font-size: 12px; }
        </style>
    </head>
    <body>
        <div class="email-wrapper">
            <div class="email-header">
                <img src="' . htmlspecialchars($primaryLogo) . '" alt="TradewaveTT">
                ' . $secondaryLogoHtml . '
            </div>
            <div class="email-body">
                <div class="greeting">Dear ' . htmlspecialchars($firstName) . ',</div>
                <p>' . nl2br(htmlspecialchars($bodyText)) . '</p>
                <div class="amount-box">
                    <div class="amount-label">Subscription Amount Due:</div>
                    <div class="amount-value">' . htmlspecialchars($currency) . ' ' . number_format($amount, 2) . '</div>
                </div>
                <p style="margin-top: 25px;">To ensure uninterrupted access to our premium features, please review the attached document for detailed payment instructions and contactsupport for any form of questioning.</p>
                <center>
                    <a href="https://www.tradewavett.xyz" class="cta-button">Know More</a>
                </center>
            </div>
            <div class="email-footer">
                <strong>TradewaveTT - Your Premium Trading Experience</strong>
                <div class="footer-links">
                    <a href="https://www.tradewavett.xyz">Visit Website</a> |
                    <a href="mailto:official@tradewavett.xyz">Contact Support</a>
                </div>
                <div style="margin: 15px 0;">
                    <strong>Support Email:</strong> official@tradewavett.xyz<br>
                    <strong>Website:</strong> www.tradewavett.xyz
                </div>
                <div class="copyright">
                    &copy; ' . date('Y') . ' TradewaveTT. All rights reserved.<br>
                    This is an automated notification. Please do not reply to this email.
                </div>
            </div>
        </div>
    </body>
    </html>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Subscription Email - TradewaveTT Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-brown: #8B4513;
            --secondary-brown: #A0522D;
            --accent-orange: #FF8C00;
            --light-bg: #fff5f0;
            --text-dark: #2c2c2c;
        }
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
            min-height: 100vh;
            padding: 20px 0;
            zoom: 0.85;
        }

        ::-webkit-scrollbar {
            display: none;
        }
        
        .admin-header-section {
            background: linear-gradient(135deg, var(--primary-brown) 0%, var(--secondary-brown) 100%);
            color: white;
            padding: 25px 0;
            margin-bottom: 30px;
            animation: slideDown 0.5s ease-out;
        }
        
        @keyframes slideDown {
            from { transform: translateY(-20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .admin-header-section h1 {
            font-size: 28px;
            font-weight: 700;
            margin: 0;
        }
        
        .admin-card-wrapper {
            background: white;
            border-radius: 7px;
            overflow: hidden;
            margin-bottom: 30px;
            animation: fadeInUp 0.6s ease-out;
        }
        
        @keyframes fadeInUp {
            from { transform: translateY(30px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .admin-card-header {
            background: linear-gradient(135deg, var(--light-bg) 0%, #ffe8d6 100%);
            padding: 20px 25px;
            border-bottom: 2px solid var(--accent-orange);
        }
        
        .admin-card-header h3 {
            color: var(--primary-brown);
            font-weight: 600;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .admin-card-body {
            padding: 30px 25px;
        }
        
        .form-label-custom {
            font-weight: 600;
            color: var(--text-dark);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .form-control-custom, .form-select-custom {
            border: 2px solid #e0e0e0;
            border-radius: 4px;
            padding: 12px 15px;
            transition: all 0.3s ease;
            font-size: 15px;
        }
        
        .form-control-custom:focus, .form-select-custom:focus {
            border-color: var(--accent-orange);
        }
        
        .btn-primary-custom {
            background: linear-gradient(135deg, var(--primary-brown) 0%, var(--secondary-brown) 100%);
            border: none;
            padding: 12px 30px;
            border-radius: 4px;
            font-weight: 600;
            color: white;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary-custom:hover:not(:disabled) {
            transform: translateY(-2px);
        }
        
        .btn-primary-custom:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }
        
        .btn-secondary-custom {
            background: #6c757d;
            border: none;
            padding: 10px 25px;
            border-radius: 4px;
            font-weight: 600;
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-secondary-custom:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }
        
        .user-selector-wrapper {
            border: 2px solid #e0e0e0;
            border-radius: 4px;
            padding: 20px;
            background: #fafafa;
            max-height: 400px;
            overflow-y: auto;
        }
        
        .user-checkbox-item {
            background: white;
            border: 2px solid #e8e8e8;
            border-radius: 4px;
            padding: 12px 15px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .user-checkbox-item:hover {
            border-color: var(--accent-orange);
            background: var(--light-bg);
            transform: translateX(5px);
        }
        
        .user-checkbox-item input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
            accent-color: var(--accent-orange);
        }
        
        .user-info-display {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .user-avatar-icon {
            width: 35px;
            height: 35px;
            background: linear-gradient(135deg, var(--primary-brown), var(--secondary-brown));
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }
        
        .email-preview-section {
            border: 3px solid var(--primary-brown);
            border-radius: 6px;
            overflow: hidden;
            background: white;
        }
        
        .preview-toolbar {
            background: var(--primary-brown);
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .preview-content-area {
            padding: 0;
            min-height: 500px;
            max-height: 700px;
            overflow-y: auto;
        }
        
        .alert-custom {
            border-radius: 5px;
            padding: 20px 25px;
            margin-bottom: 25px;
            animation: slideIn 0.5s ease-out;
            display: flex;
            align-items: flex-start;
            gap: 15px;
            font-size: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            position: relative;
        }
        
        @keyframes slideIn {
            from { transform: translateX(-20px); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        
        .alert-success-custom {
            background: #d4edda;
            border-left: 5px solid #28a745;
            color: #155724;
        }
        
        .alert-error-custom {
            background: #f8d7da;
            border-left: 5px solid #dc3545;
            color: #721c24;
        }
        
        .alert-custom i {
            font-size: 24px;
            margin-top: 2px;
        }
        
        .alert-custom-content {
            flex: 1;
        }
        
        .alert-custom-close {
            cursor: pointer;
            font-size: 24px;
            opacity: 0.7;
            transition: opacity 0.3s;
            position: absolute;
            right: 15px;
            top: 15px;
        }
        
        .alert-custom-close:hover {
            opacity: 1;
        }
        
        .logo-upload-preview {
            width: 100px;
            height: 100px;
            border: 2px dashed #ccc;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            background: #f9f9f9;
            margin-top: 10px;
        }
        
        .logo-upload-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            border-radius: 50%;
        }
        
        .select-all-btn {
            background: var(--accent-orange);
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 6px;
            font-weight: 600;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .select-all-btn:hover {
            background: #ff7700;
            transform: scale(1.05);
        }
        
        .loading-spinner {
            display: none;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .sending .loading-spinner {
            display: inline-block;
        }
        
        .pdf-viewer-section {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 20px;
            background: white;
            text-align: center;
        }
        
        .pdf-icon-display {
            font-size: 64px;
            color: var(--accent-orange);
            margin-bottom: 15px;
        }
        
        textarea.form-control-custom {
            min-height: 200px;
            resize: vertical;
        }
        
        .character-counter {
            font-size: 12px;
            color: #666;
            text-align: right;
            margin-top: 5px;
        }
        
        .notification-toast {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            min-width: 300px;
            max-width: 500px;
        }
    </style>
</head>
<body>
    <div class="admin-header-section">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <h1><i class="bi bi-envelope-paper"></i> Subscription Email Sender</h1>
                <a href="?action=logout" class="btn btn-light">
                    <i class="bi bi-box-arrow-right"></i> Logout
                </a>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Notification Area -->
        <div id="notificationArea"></div>

        <div class="row">
            <!-- Configuration Panel -->
            <div class="col-lg-5">
                <form id="emailSenderForm" enctype="multipart/form-data">
                    <div class="admin-card-wrapper">
                        <div class="admin-card-header">
                            <h3><i class="bi bi-gear-fill"></i> Email Configuration</h3>
                        </div>
                        <div class="admin-card-body">
                            <!-- Sender Name -->
                            <div class="mb-4">
                                <label class="form-label-custom">
                                    <i class="bi bi-person-badge"></i> Sender Name
                                </label>
                                <input type="text" name="sender_name" id="senderName" class="form-control form-control-custom" value="Tradewave TT" required>
                            </div>

                            <!-- Email Subject -->
                            <div class="mb-4">
                                <label class="form-label-custom">
                                    <i class="bi bi-chat-left-text"></i> Email Subject
                                </label>
                                <input type="text" name="email_subject" id="emailSubject" class="form-control form-control-custom" value="DOM ALGORITHM EXECUTION" required>
                            </div>

                            <!-- Amount -->
                            <div class="mb-4">
                                <label class="form-label-custom">
                                    <i class="bi bi-currency-dollar"></i> Amount
                                </label>
                                <div class="input-group">
                                    <select name="currency" class="form-select form-select-custom" style="max-width: 100px;" id="currencySelect">
                                        <option value="USD">USD</option>
                                        <option value="TTD">TTD</option>
                                    </select>
                                    <input type="number" name="amount" class="form-control form-control-custom" value="29.99" step="0.01" required id="amountInput">
                                </div>
                            </div>

                            <!-- Email Body -->
                            <div class="mb-4">
                                <label class="form-label-custom">
                                    <i class="bi bi-file-text"></i> Email Body Message
                                </label>
                                <textarea name="email_body" class="form-control form-control-custom" id="emailBodyText" maxlength="1000" required>Your trading account has been temporarily suspended from all trading activities due to an outstanding Platform/Data charge following recent upgrades to our brokerage systems. The account was found linked to an outdated version, which limits access to our advanced Trade Guidance and DOM Algorithm Execution capabilities. This charge covers subscription and market data fees essential for real-time order execution, accurate market depth insights, algorithmic trading, and portfolio monitoring across all asset classes, including multi-currency, crypto, and NFT positions. Compliance with this fee is critical to restore uninterrupted access to the enhanced platform, ensure operational integrity, and maintain alignment with institutional trading protocols. The exact amount of the charge will be detailed in this communication or provided separately as per standard account procedures. Prompt settlement is therefore required to reinstate trading functionality and re-enable all platform-driven tools and analytics.</textarea>
                                <div class="character-counter">
                                    <span id="charCount">0</span> / 1000 characters
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Logo Upload Section -->
                    <div class="admin-card-wrapper">
                        <div class="admin-card-header">
                            <h3><i class="bi bi-image"></i> Logo Management</h3>
                        </div>
                        <div class="admin-card-body">
                            <!-- Primary Logo -->
                            <div class="mb-4">
                                <label class="form-label-custom">
                                    <i class="bi bi-star-fill"></i> Primary Logo
                                </label>
                                <input type="file" name="primary_logo" class="form-control form-control-custom" accept="image/*" id="primaryLogoInput">
                                <input type="hidden" name="primary_logo_path" id="primaryLogoPath" value="https://tradewavett.xyz/images/icon.png">
                                <div class="logo-upload-preview" id="primaryLogoPreview">
                                    <img src="https://tradewavett.xyz/images/icon.png" alt="Primary Logo">
                                </div>
                            </div>

                            <!-- Secondary Logo -->
                            <div class="mb-4">
                                <label class="form-label-custom">
                                    <i class="bi bi-plus-circle"></i> Secondary Logo (Optional)
                                </label>
                                <input type="file" name="secondary_logo" class="form-control form-control-custom" accept="image/*" id="secondaryLogoInput">
                                <input type="hidden" name="secondary_logo_path" id="secondaryLogoPath" value="">
                                <div class="logo-upload-preview" id="secondaryLogoPreview">
                                    <i class="bi bi-cloud-upload" style="font-size: 36px; color: #ccc;"></i>
                                </div>
                            </div>

                            <button type="button" class="btn btn-secondary-custom w-100" id="uploadLogosBtn">
                                <i class="bi bi-upload"></i> Upload Logos
                            </button>
                        </div>
                    </div>

                    <!-- Recipient Selection -->
                    <div class="admin-card-wrapper">
                        <div class="admin-card-header">
                            <h3><i class="bi bi-people-fill"></i> Select Recipients</h3>
                        </div>
                        <div class="admin-card-body">
                            <button type="button" class="select-all-btn" id="selectAllBtn">
                                <i class="bi bi-check-all"></i> Select / Deselect All
                            </button>
                            <div class="user-selector-wrapper" id="recipientsList">
                                <?php foreach ($users as $user): ?>
                                    <label class="user-checkbox-item">
                                        <div class="user-info-display">
                                            <input type="checkbox" name="recipients[]" value="<?php echo $user['id']; ?>" class="recipient-checkbox">
                                            <div class="user-avatar-icon">
                                                <?php echo strtoupper(substr($user['firstname'], 0, 1)); ?>
                                            </div>
                                            <div>
                                                <strong><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></strong><br>
                                                <small style="color: #666;"><?php echo htmlspecialchars($user['email']); ?></small>
                                                <span class="badge bg-<?php echo $user['status'] === 'Active' ? 'success' : 'warning'; ?> ms-2">
                                                    <?php echo htmlspecialchars($user['status']); ?>
                                                </span>
                                            </div>
                                        </div>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Send Button -->
                    <button type="submit" class="btn btn-primary-custom w-100 mb-4" id="sendBtn">
                        <span class="loading-spinner"></span>
                        <i class="bi bi-send-fill"></i> Send Email
                    </button>
                </form>
            </div>

            <!-- Preview Panel -->
            <div class="col-lg-7">
                <div class="admin-card-wrapper">
                    <div class="admin-card-header">
                        <h3><i class="bi bi-eye-fill"></i> Email Preview</h3>
                    </div>
                    <div class="admin-card-body p-0">
                        <div class="email-preview-section">
                            <div class="preview-toolbar">
                                <span><i class="bi bi-envelope"></i> Live Preview</span>
                                <span><i class="bi bi-phone"></i> <i class="bi bi-tablet"></i> <i class="bi bi-laptop"></i></span>
                            </div>
                            <div class="preview-content-area" id="emailPreview">
                                <!-- Preview will be loaded here -->
                            </div>
                        </div>
                    </div>
                </div>

                <!-- PDF Document Section -->
                <div class="admin-card-wrapper">
                    <div class="admin-card-header">
                        <h3><i class="bi bi-file-pdf"></i> Attached Document</h3>
                    </div>
                    <div class="admin-card-body">
                        <div class="pdf-viewer-section">
                            <div class="pdf-icon-display">
                                <i class="bi bi-file-earmark-pdf-fill"></i>
                            </div>
                            <h5>subscription_document.pdf</h5>
                            <p class="text-muted">This document will be attached to the email (if available)</p>
                            <a href="https://tradewavett.xyz/images/subdoc6.pdf" target="_blank" class="btn btn-primary-custom me-2">
                                <i class="bi bi-eye"></i> View Document
                            </a>
                            <a href="https://tradewavett.xyz/images/subdoc6.pdf" download class="btn btn-secondary-custom">
                                <i class="bi bi-download"></i> Download
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Show notification
        function showNotification(message, type) {
            const notificationArea = document.getElementById('notificationArea');
            const alertClass = type === 'success' ? 'alert-success-custom' : 'alert-error-custom';
            const icon = type === 'success' ? 'check-circle-fill' : 'exclamation-triangle-fill';
            
            const notification = document.createElement('div');
            notification.className = `alert-custom ${alertClass}`;
            notification.innerHTML = `
                <i class="bi bi-${icon}"></i>
                <div class="alert-custom-content">${message}</div>
                <span class="alert-custom-close" onclick="this.parentElement.remove()">×</span>
            `;
            
            notificationArea.innerHTML = '';
            notificationArea.appendChild(notification);
            
            // Auto-remove after 8 seconds
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 8000);
            
            // Scroll to top to see notification
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        // Update preview on load
        document.addEventListener('DOMContentLoaded', function() {
            updatePreview();
            updateCharacterCount();
        });

        // Character counter for email body
        document.getElementById('emailBodyText').addEventListener('input', updateCharacterCount);

        function updateCharacterCount() {
            const text = document.getElementById('emailBodyText').value;
            document.getElementById('charCount').textContent = text.length;
        }

        // Logo preview handlers
        document.getElementById('primaryLogoInput').addEventListener('change', function(e) {
            previewLogo(e.target, 'primaryLogoPreview');
        });

        document.getElementById('secondaryLogoInput').addEventListener('change', function(e) {
            previewLogo(e.target, 'secondaryLogoPreview');
        });

        function previewLogo(input, previewId) {
            const preview = document.getElementById(previewId);
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = '<img src="' + e.target.result + '" alt="Logo Preview">';
                    updatePreview();
                };
                reader.readAsDataURL(input.files[0]);
            }
        }

        // Upload logos via AJAX
        document.getElementById('uploadLogosBtn').addEventListener('click', function() {
            const formData = new FormData();
            const primaryLogo = document.getElementById('primaryLogoInput').files[0];
            const secondaryLogo = document.getElementById('secondaryLogoInput').files[0];
            
            if (!primaryLogo && !secondaryLogo) {
                showNotification('Please select at least one logo to upload', 'error');
                return;
            }
            
            if (primaryLogo) formData.append('primary_logo', primaryLogo);
            if (secondaryLogo) formData.append('secondary_logo', secondaryLogo);
            formData.append('ajax_upload_logo', '1');
            
            this.disabled = true;
            this.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Uploading...';
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.primaryLogo) {
                        document.getElementById('primaryLogoPath').value = data.primaryLogo;
                    }
                    if (data.secondaryLogo) {
                        document.getElementById('secondaryLogoPath').value = data.secondaryLogo;
                    }
                    showNotification(data.message, 'success');
                    updatePreview();
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                showNotification('Upload error: ' + error, 'error');
            })
            .finally(() => {
                this.disabled = false;
                this.innerHTML = '<i class="bi bi-upload"></i> Upload Logos';
            });
        });

        // Update email preview
        function updatePreview() {
            const firstName = 'John';
            const amount = document.getElementById('amountInput').value;
            const currency = document.getElementById('currencySelect').value;
            const bodyText = document.getElementById('emailBodyText').value;
            
            let primaryLogo = document.getElementById('primaryLogoPath').value;
            let secondaryLogo = document.getElementById('secondaryLogoPath').value;
            
            const primaryInput = document.getElementById('primaryLogoInput');
            const secondaryInput = document.getElementById('secondaryLogoInput');
            
            let pendingReads = 0;
            
            if (primaryInput.files && primaryInput.files[0]) {
                pendingReads++;
                const reader = new FileReader();
                reader.onload = function(e) {
                    primaryLogo = e.target.result;
                    pendingReads--;
                    if (pendingReads === 0) renderPreview();
                };
                reader.readAsDataURL(primaryInput.files[0]);
            }
            
            if (secondaryInput.files && secondaryInput.files[0]) {
                pendingReads++;
                const reader = new FileReader();
                reader.onload = function(e) {
                    secondaryLogo = e.target.result;
                    pendingReads--;
                    if (pendingReads === 0) renderPreview();
                };
                reader.readAsDataURL(secondaryInput.files[0]);
            }
            
            if (pendingReads === 0) {
                renderPreview();
            }
            
            function renderPreview() {
                const secondaryLogoHtml = secondaryLogo ? 
                    '<img src="' + secondaryLogo + '" alt="Logo" style="height: 40px; margin-left: 20px;">' : '';
                
                const previewHtml = `
                    <div style="font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px;">
                        <div style="max-width: 650px; margin: 0 auto; background: #ffffff; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
                            <div style="background: linear-gradient(135deg, #8B4513 0%, #A0522D 100%); padding: 30px 20px; text-align: center;">
                                <img src="${primaryLogo}" alt="TradewaveTT" style="height: 50px; vertical-align: middle;">
                                ${secondaryLogoHtml}
                            </div>
                            <div style="padding: 40px 30px; color: #333333; line-height: 1.8;">
                                <div style="font-size: 18px; font-weight: 600; color: #8B4513; margin-bottom: 20px;">Dear ${firstName},</div>
                                <p>${bodyText.replace(/\n/g, '<br>')}</p>
                                <div style="background: #fff5f0; border-left: 4px solid #FF8C00; padding: 20px; margin: 25px 0; border-radius: 5px;">
                                    <div style="font-size: 14px; color: #666; margin-bottom: 5px;">Subscription Amount Due:</div>
                                    <div style="font-size: 32px; font-weight: 600; color: #FF8C00;">${currency} ${parseFloat(amount).toFixed(2)}</div>
                                </div>
                                <p style="margin-top: 25px;">To ensure uninterrupted access to our premium features, please review the attached document for detailed payment instructions and subscription renewal guidelines.</p>
                                <center>
                                    <a href="https://www.tradewavett.xyz" style="display: inline-block; background: #8B4513; color: #ffffff; padding: 15px 40px; text-decoration: none; border-radius: 5px; margin: 25px 0; font-weight: 600;">Know More</a>
                                </center>
                            </div>
                            <div style="background: #f9f9f9; padding: 30px; text-align: center; color: #666; font-size: 13px; border-top: 1px solid #e0e0e0;">
                                <strong>TradewaveTT - Your Premium Music Experience</strong>
                                <div style="margin: 15px 0;">
                                    <a href="https://www.tradewavett.xyz" style="color: #8B4513; text-decoration: none; margin: 0 10px;">Visit Website</a> |
                                    <a href="mailto:official@tradewavett.xyz" style="color: #8B4513; text-decoration: none; margin: 0 10px;">Contact Support</a>
                                </div>
                                <div style="margin: 15px 0;">
                                    <strong>Support Email:</strong> official@tradewavett.xyz<br>
                                    <strong>Website:</strong> www.tradewavett.xyz
                                </div>
                                <div style="margin-top: 15px; font-size: 12px;">
                                    &copy; ${new Date().getFullYear()} TradewaveTT. All rights reserved.<br>
                                    This is an automated notification. Please do not reply to this email.
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('emailPreview').innerHTML = previewHtml;
            }
        }

        // Update preview on input changes
        document.getElementById('amountInput').addEventListener('input', updatePreview);
        document.getElementById('currencySelect').addEventListener('change', updatePreview);
        document.getElementById('emailBodyText').addEventListener('input', updatePreview);

        // Toggle select all
        document.getElementById('selectAllBtn').addEventListener('click', function() {
            const checkboxes = document.querySelectorAll('.recipient-checkbox');
            const allChecked = Array.from(checkboxes).every(cb => cb.checked);
            checkboxes.forEach(cb => cb.checked = !allChecked);
        });

        // Form submission via AJAX
        document.getElementById('emailSenderForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const selectedRecipients = Array.from(document.querySelectorAll('.recipient-checkbox:checked'))
                .map(cb => cb.value);
            
            if (selectedRecipients.length === 0) {
                showNotification('⚠️ Please select at least one recipient', 'error');
                return;
            }
            
            const sendBtn = document.getElementById('sendBtn');
            sendBtn.classList.add('sending');
            sendBtn.disabled = true;
            
            const formData = new FormData();
            formData.append('ajax_send_email', '1');
            formData.append('sender_name', document.getElementById('senderName').value);
            formData.append('email_subject', document.getElementById('emailSubject').value);
            formData.append('amount', document.getElementById('amountInput').value);
            formData.append('currency', document.getElementById('currencySelect').value);
            formData.append('email_body', document.getElementById('emailBodyText').value);
            formData.append('recipients', JSON.stringify(selectedRecipients));
            formData.append('primary_logo_path', document.getElementById('primaryLogoPath').value);
            formData.append('secondary_logo_path', document.getElementById('secondaryLogoPath').value);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    // Uncheck all recipients after successful send
                    document.querySelectorAll('.recipient-checkbox').forEach(cb => cb.checked = false);
                } else {
                    let errorMsg = data.message;
                    if (data.details && data.details.length > 0) {
                        errorMsg += '<br><small>' + data.details.slice(0, 3).join('<br>') + '</small>';
                    }
                    showNotification(errorMsg, 'error');
                }
            })
            .catch(error => {
                showNotification('❌ Network error: ' + error.message + '<br>Please check your internet connection and try again.', 'error');
            })
            .finally(() => {
                sendBtn.classList.remove('sending');
                sendBtn.disabled = false;
            });
        });
    </script>
</body>
</html>