<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AML Tariff Email Composer</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
            font-weight: 300;
        }

        .content {
            padding: 30px;
        }

        .section {
            margin-bottom: 30px;
        }

        .section h2 {
            color: #1e3c72;
            margin-bottom: 15px;
            font-size: 20px;
            border-bottom: 2px solid #e0e0e0;
            padding-bottom: 5px;
        }

        .user-selection {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            background: #f9f9f9;
        }

        .user-item {
            display: flex;
            align-items: center;
            padding: 10px;
            background: white;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .user-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .user-item input[type="checkbox"] {
            margin-right: 10px;
            transform: scale(1.2);
        }

        .user-info {
            flex: 1;
        }

        .user-name {
            font-weight: 600;
            color: #333;
        }

        .user-email {
            font-size: 12px;
            color: #666;
            margin-top: 2px;
        }

        .email-preview {
            background: #f8f9fa;
            border: 1px solid #e0e0e0;
            border-radius: 12px;
            padding: 0;
            font-size: 14px;
            line-height: 1.7;
            color: #2c3e50;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .email-preview .preview-container {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 12px;
            overflow: hidden;
        }

        .email-preview .preview-header { 
            text-align: center; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 25px 20px;
            color: white;
        }

        .email-preview .preview-content { 
            padding: 30px 25px; 
            background: white;
        }

        .email-preview .greeting {
            font-size: 16px;
            font-weight: 600;
            color: #1a73e8;
            margin-bottom: 15px;
        }

        .email-preview .subject-line {
            background: #f8f9fa;
            border-left: 4px solid #1a73e8;
            padding: 12px 16px;
            margin: 15px 0;
            font-weight: 600;
            border-radius: 0 8px 8px 0;
        }

        .email-preview .fee-box {
            background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
            border: 1px solid #ffc107;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
            text-align: center;
        }

        .email-preview .fee-amount {
            font-size: 20px;
            font-weight: 700;
            color: #d63384;
            margin: 8px 0;
        }

        .email-header {
            text-align: center;
            margin-bottom: 20px;
        }

        .logos {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 30px;
            margin-bottom: 20px;
        }

        .logos img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: contain;
        }

        .send-button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 40px;
            font-size: 18px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            margin-top: 20px;
        }

        .send-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }

        .send-button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .status {
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            text-align: center;
            font-weight: 600;
            display: none;
        }

        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .select-all {
            text-align: right;
            margin-bottom: 10px;
        }

        .select-all button {
            background: #007bff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .selected-count {
            background: #007bff;
            color: white;
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>AML Tariff Email Composer</h1>
            <p>Compose and send AML notification emails to selected users</p>
        </div>

        <div class="content">
            <div class="section">
                <h2>Select Recipients <span class="selected-count" id="selectedCount">0 selected</span></h2>
                <div class="select-all">
                    <button onclick="selectAll()">Select All</button>
                    <button onclick="deselectAll()">Deselect All</button>
                </div>
                <div class="user-selection" id="userList">
                    <!-- Users will be loaded here -->
                </div>
            </div>

            <div class="section">
                <h2>Email Preview</h2>
                <div class="email-preview">
                    <div class="preview-container">
                        <div class="preview-header">
                            <div class="logos">
                                <img src="https://tradewave.ifctrades.live/ifctrading/images/icon.png" alt="TradeWave Logo">
                                <img src="https://tradewave.ifctrades.live/ifctrading/images/frc-logo.png" alt="FRC Logo">
                            </div>
                            <p style="margin: 0; font-size: 16px; font-weight: 300; opacity: 0.95;">Financial Services Notification</p>
                        </div>
                        
                        <div class="preview-content">
                            <p><strong>Subject:</strong> Notification of AML Tariff Fee for Withdrawal Processing</p>
                            <br>
                            <p class="greeting">Dear [User's Full Name],</p>
                            
                            <div class="subject-line">
                                <strong>Re: Withdrawal Request from Trading Account</strong>
                            </div>
                            
                            <p>We are writing to inform you that due to additional scrutiny required by the <strong>Financial Services Commission (FSC) of Trinidad and Tobago</strong>, the regulatory body overseeing trading activities in the Trinidad and Tobago market, we are obligated to apply an Anti-Money Laundering (AML) tariff to your account.</p>
                            <br>
                            <p>As part of our compliance with the FSC's regulations, we have been required to conduct enhanced due diligence on your account due to the nature of your transactions. This additional scrutiny is aimed at ensuring the integrity of our platform and adherence to international standards.</p>
                            <br>
                            <p>In light of this, we regret to inform you that your current withdrawal request has been put on hold pending settlement of the AML tariff. The fee is necessary to cover the costs associated with the enhanced monitoring and reporting requirements.</p>
                            
                            <div class="fee-box">
                                <p><strong>AML Tariff Fee Required</strong></p>
                                <div class="fee-amount">TTD 13,000.00</div>
                                <p>Once payment is received, we will promptly process your withdrawal request.</p>
                            </div>
                            
                            <p><strong>Payment Details:</strong></p>
                            <ul style="margin-left: 20px; margin-top: 10px;">
                                <li><strong>Fee Amount:</strong> TTD 13,000.00</li>
                                <li><strong>Payment Method:</strong> Select from dashboard</li>
                                <li><strong>Payment Instructions:</strong> Contact support if you can't navigate to payment section and need more clarity</li>
                            </ul>
                            <br>
                            <div style="background: #e3f2fd; border-left: 4px solid #2196f3; padding: 15px; margin: 20px 0; border-radius: 0 8px 8px 0; font-style: italic; color: #1565c0;">
                                <strong>Important:</strong> We appreciate your understanding and cooperation in this matter. If you have any questions or concerns, please do not hesitate to reach out to our support team.
                            </div>
                            
                            <p>Thank you for your prompt attention to this matter.</p>
                            <br>
                            <div style="margin-top: 30px; padding-top: 20px; border-top: 2px solid #e9ecef; background: #f8f9fa; border-radius: 8px; padding: 20px;">
                                <p style="color: #1a73e8; font-weight: 600; margin-bottom: 8px;"><strong>Best regards,</strong></p>
                                <div style="font-weight: 600; color: #495057; line-height: 1.4;">
                                    Trade FRC Commission<br>
                                    TradeWave Team
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <button class="send-button" onclick="sendEmails()" id="sendBtn" disabled>
                Send Email to Selected Users
            </button>

            <div class="status" id="status"></div>
        </div>
    </div>

    <script>
        let users = [];
        let selectedUsers = [];

        // Load users from database
        async function loadUsers() {
            try {
                const response = await fetch('load_users.php');
                users = await response.json();
                renderUsers();
            } catch (error) {
                console.error('Error loading users:', error);
                // Fallback demo users for testing
                users = [
                    {id: 1, firstname: 'John', lastname: 'Doe', email: 'john.doe@example.com'},
                    {id: 2, firstname: 'Jane', lastname: 'Smith', email: 'jane.smith@example.com'},
                    {id: 3, firstname: 'Mike', lastname: 'Johnson', email: 'mike.johnson@example.com'},
                    {id: 4, firstname: 'Sarah', lastname: 'Williams', email: 'sarah.williams@example.com'},
                    {id: 5, firstname: 'David', lastname: 'Brown', email: 'david.brown@example.com'}
                ];
                renderUsers();
            }
        }

        function renderUsers() {
            const userList = document.getElementById('userList');
            userList.innerHTML = '';

            users.forEach(user => {
                const userItem = document.createElement('div');
                userItem.className = 'user-item';
                userItem.innerHTML = `
                    <input type="checkbox" id="user_${user.id}" onchange="toggleUser(${user.id})">
                    <div class="user-info">
                        <div class="user-name">${user.firstname} ${user.lastname}</div>
                        <div class="user-email">${user.email}</div>
                    </div>
                `;
                userList.appendChild(userItem);
            });
        }

        function toggleUser(userId) {
            const checkbox = document.getElementById(`user_${userId}`);
            if (checkbox.checked) {
                if (!selectedUsers.includes(userId)) {
                    selectedUsers.push(userId);
                }
            } else {
                selectedUsers = selectedUsers.filter(id => id !== userId);
            }
            updateSelectedCount();
        }

        function updateSelectedCount() {
            document.getElementById('selectedCount').textContent = `${selectedUsers.length} selected`;
            document.getElementById('sendBtn').disabled = selectedUsers.length === 0;
        }

        function selectAll() {
            selectedUsers = users.map(user => user.id);
            users.forEach(user => {
                document.getElementById(`user_${user.id}`).checked = true;
            });
            updateSelectedCount();
        }

        function deselectAll() {
            selectedUsers = [];
            users.forEach(user => {
                document.getElementById(`user_${user.id}`).checked = false;
            });
            updateSelectedCount();
        }

        async function sendEmails() {
            const sendBtn = document.getElementById('sendBtn');
            const status = document.getElementById('status');
            
            sendBtn.disabled = true;
            sendBtn.textContent = 'Sending...';
            status.style.display = 'none';

            try {
                const response = await fetch('send_emails.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        userIds: selectedUsers
                    })
                });

                const result = await response.json();
                
                if (result.success) {
                    status.className = 'status success';
                    status.textContent = `Successfully sent ${result.sent} emails!`;
                    deselectAll();
                } else {
                    status.className = 'status error';
                    status.textContent = `Error: ${result.message}`;
                }
            } catch (error) {
                status.className = 'status error';
                status.textContent = 'Failed to send emails. Please try again.';
            }

            status.style.display = 'block';
            sendBtn.disabled = false;
            sendBtn.textContent = 'Send Email to Selected Users';
        }

        // Initialize
        loadUsers();
    </script>
</body>
</html>