<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Management System - Tradewave Admin</title>
    <link rel="stylesheet" type="text/css" href="css/email.css">
</head>
<body>
    <div class="tw_admin_mail_container">
        

        <div class="tw_main_form_wrapper">
            <form id="tw_email_form" method="POST" enctype="multipart/form-data" action="send_custom_email.php">
                
                <!-- Basic Settings -->
                <div class="tw_form_section_divider">
                    <div class="tw_input_group_wrapper">
                        <label class="tw_custom_label">📝 Email Title</label>
                        <input type="text" name="email_title" class="tw_form_input_field" value="Tradewave TT" placeholder="Enter email title">
                    </div>
                    
                    <div class="tw_input_group_wrapper">
                        <label class="tw_custom_label">📋 Email Type/Subject</label>
                        <select name="email_type" class="tw_select_field" id="tw_email_type_select">
                            <option value="Package Departure">📦 Package Departure</option>
                            <option value="Package Arrival">🎯 Package Arrival</option>
                            <option value="Tracking Overview">🔍 Tracking Overview</option>
                            <option value="Pending Bill Notice">💰 Pending Bill Notice</option>
                            <option value="custom">✏️ Enter custom type/title</option>
                        </select>
                        <input type="text" name="custom_email_type" class="tw_form_input_field" style="display: none; margin-top: 10px;" placeholder="Enter custom email type">
                    </div>
                </div>

                <!-- Logo Upload Section -->
                <div class="tw_input_group_wrapper">
                    <label class="tw_custom_label">🎨 Brand Logos (Max 3)</label>
                    <div class="tw_logo_upload_section">
                        <p>Upload up to 3 logos for your email header (50x50px, rounded)</p>
                        <div class="tw_file_upload_wrapper">
                            <input type="file" name="logos[]" class="tw_file_input_hidden" id="tw_logo_input" accept="image/*" multiple>
                            <label for="tw_logo_input" class="tw_file_upload_btn">Choose Logo Files</label>
                        </div>
                        <div class="tw_logo_preview_grid" id="tw_logo_preview_container">
                            <!-- Logo previews will appear here -->
                        </div>
                    </div>
                </div>

                <!-- Recipients Selection -->
                <div class="tw_input_group_wrapper tw_full_width">
                    <label class="tw_custom_label">👥 Select Recipients</label>
                    <div class="tw_recipients_grid" id="tw_recipients_container">
                        <?php
                        try {
                            $stmt = $conn->prepare("
                                SELECT id, firstname, lastname, email, currency_symbol, country 
                                FROM users 
                                WHERE email IS NOT NULL AND email != '' 
                                ORDER BY firstname, lastname
                            ");
                            $stmt->execute();
                            $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                            
                            foreach ($users as $user) {
                                $fullName = trim($user['firstname'] . ' ' . $user['lastname']);
                                $currency = $user['currency_symbol'] ?: '$';
                                echo '<div class="tw_recipient_option">';
                                echo '<input type="checkbox" name="recipients[]" value="' . htmlspecialchars($user['id']) . '" data-currency="' . htmlspecialchars($currency) . '">';
                                echo '<div class="tw_recipient_info">';
                                echo '<span class="tw_recipient_name">' . htmlspecialchars($fullName) . '</span>';
                                echo '<span class="tw_recipient_email">' . htmlspecialchars($user['email']) . ' (' . htmlspecialchars($user['country']) . ' - ' . htmlspecialchars($currency) . ')</span>';
                                echo '</div>';
                                echo '</div>';
                            }
                            
                        } catch (PDOException $e) {
                            echo '<div style="color: red; padding: 10px;">Error loading recipients: ' . htmlspecialchars($e->getMessage()) . '</div>';
                        }
                        ?>
                    </div>
                </div>

                <!-- Message Body -->
                <div class="tw_input_group_wrapper tw_full_width">
                    <label class="tw_custom_label">✉️ Message Content</label>
                    <textarea name="message_body" class="tw_textarea_field" placeholder="Type your message content here... (Note: 'Dear [User]' will be automatically added at the beginning)" required></textarea>
                </div>

                <!-- Price Section -->
                <div class="tw_price_section_wrapper">
                    <label class="tw_custom_label">💰 Price/Amount Information (Optional)</label>
                    <div class="tw_form_section_divider">
                        <div class="tw_input_group_wrapper">
                            <input type="number" name="price_amount" class="tw_form_input_field" step="0.01" placeholder="Enter amount">
                        </div>
                        <div class="tw_input_group_wrapper">
                            <select name="price_currency" class="tw_select_field">
                                <option value="">Select Currency</option>
                                <option value="USD">USD ($)</option>
                                <option value="EUR">EUR (€)</option>
                                <option value="GBP">GBP (£)</option>
                                <option value="TTD">TTD (TT$)</option>
                            </select>
                        </div>
                    </div>
                    <div class="tw_price_style_options">
                        <div class="tw_radio_option_wrapper">
                            <input type="radio" name="price_style" value="pending" id="tw_price_pending">
                            <label for="tw_price_pending">🟠 Pending (Orange)</label>
                        </div>
                        <div class="tw_radio_option_wrapper">
                            <input type="radio" name="price_style" value="success" id="tw_price_success">
                            <label for="tw_price_success">🟢 Success (Green)</label>
                        </div>
                        <div class="tw_radio_option_wrapper">
                            <input type="radio" name="price_style" value="overdue" id="tw_price_overdue">
                            <label for="tw_price_overdue">🔴 Overdue (Red)</label>
                        </div>
                    </div>
                </div>

                <!-- File Attachment -->
                <div class="tw_input_group_wrapper">
                    <label class="tw_custom_label">📎 Attach Document (Optional)</label>
                    <div class="tw_file_upload_wrapper">
                        <input type="file" name="attachment" class="tw_file_input_hidden" id="tw_attachment_input">
                        <label for="tw_attachment_input" class="tw_file_upload_btn">Choose File to Attach</label>
                    </div>
                    <div id="tw_attachment_preview" style="margin-top: 10px; color: #4a5568;"></div>
                </div>

                <!-- Table Builder -->
                <div class="tw_table_builder_section">
                    <label class="tw_custom_label">📊 Add Data Table (Optional)</label>
                    <div class="tw_table_controls_wrapper">
                        <button type="button" class="tw_btn_small tw_btn_add" onclick="tw_addTableRow()">➕ Add Row</button>
                        <button type="button" class="tw_btn_small tw_btn_remove" onclick="tw_removeTableRow()">➖ Remove Row</button>
                        <button type="button" class="tw_btn_small tw_btn_add" onclick="tw_addTableColumn()">➕ Add Column</button>
                        <button type="button" class="tw_btn_small tw_btn_remove" onclick="tw_removeTableColumn()">➖ Remove Column</button>
                    </div>
                    <table class="tw_table_preview" id="tw_email_table">
                        <thead>
                            <tr>
                                <th><input type="text" class="tw_editable_cell" placeholder="Header 1" onchange="tw_updateTableData()"></th>
                                <th><input type="text" class="tw_editable_cell" placeholder="Header 2" onchange="tw_updateTableData()"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" class="tw_editable_cell" placeholder="Data 1" onchange="tw_updateTableData()"></td>
                                <td><input type="text" class="tw_editable_cell" placeholder="Data 2" onchange="tw_updateTableData()"></td>
                            </tr>
                        </tbody>
                    </table>
                    <input type="hidden" name="table_data" id="tw_table_data_input">
                </div>

                <!-- Button Options -->
                <div class="tw_form_section_divider">
                    
                    <div class="tw_checkbox_wrapper">
                        <input type="checkbox" name="include_tradewave" id="tw_tradewave_btn" value="1" checked>
                        <label for="tw_tradewave_btn">🚀 Include "Tradewave" button</label>
                    </div>
                </div>

                <!-- Submit Button -->
                <div class="tw_submit_btn_wrapper">
                    <button type="submit" class="tw_submit_main_btn">🚀 Send Email Campaign</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Loading Overlay -->
    <div class="tw_loading_overlay" id="tw_loading_overlay">
        <div class="tw_loading_content">
            <div class="tw_spinner"></div>
            <h3>Sending Emails...</h3>
            <p>Please wait while we send your email campaign.</p>
        </div>
    </div>

    <script>
        // Initialize form functionality
        document.addEventListener('DOMContentLoaded', function() {
            tw_initializeFormEvents();
        });

        function tw_initializeFormEvents() {
            // Email type selection
            document.getElementById('tw_email_type_select').addEventListener('change', function() {
                const customInput = document.querySelector('input[name="custom_email_type"]');
                if (this.value === 'custom') {
                    customInput.style.display = 'block';
                    customInput.required = true;
                } else {
                    customInput.style.display = 'none';
                    customInput.required = false;
                }
            });

            // Logo file input
            document.getElementById('tw_logo_input').addEventListener('change', function() {
                tw_previewLogos(this.files);
            });

            // Attachment file input
            document.getElementById('tw_attachment_input').addEventListener('change', function() {
                tw_previewAttachment(this.files[0]);
            });

            // Price style radio buttons
            document.querySelectorAll('input[name="price_style"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    document.querySelectorAll('.tw_radio_option_wrapper').forEach(wrapper => {
                        wrapper.classList.remove('tw_radio_selected');
                    });
                    this.parentElement.classList.add('tw_radio_selected');
                });
            });

            // Form submission
            document.getElementById('tw_email_form').addEventListener('submit', function(e) {
                // Validate recipients
                const selectedRecipients = document.querySelectorAll('input[name="recipients[]"]:checked');
                if (selectedRecipients.length === 0) {
                    e.preventDefault();
                    alert('Please select at least one recipient.');
                    return;
                }

                // Validate message body
                const messageBody = document.querySelector('textarea[name="message_body"]').value.trim();
                if (messageBody === '') {
                    e.preventDefault();
                    alert('Please enter a message body.');
                    return;
                }

                // Show loading overlay
                document.getElementById('tw_loading_overlay').style.display = 'block';
            });

            // Initialize table data
            tw_updateTableData();
        }

        function tw_previewLogos(files) {
            const container = document.getElementById('tw_logo_preview_container');
            container.innerHTML = '';
            
            for (let i = 0; i < Math.min(files.length, 3); i++) {
                const file = files[i];
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const div = document.createElement('div');
                        div.className = 'tw_logo_preview_item';
                        div.innerHTML = `<img src="${e.target.result}" class="tw_logo_preview_img" alt="Logo ${i + 1}">`;
                        container.appendChild(div);
                    };
                    reader.readAsDataURL(file);
                }
            }
        }

        function tw_previewAttachment(file) {
            const preview = document.getElementById('tw_attachment_preview');
            if (file) {
                const fileSize = (file.size / 1024).toFixed(2);
                const sizeUnit = fileSize > 1024 ? ((file.size / 1024 / 1024).toFixed(2) + ' MB') : (fileSize + ' KB');
                preview.innerHTML = `📎 Selected: <strong>${file.name}</strong> (${sizeUnit})`;
            } else {
                preview.textContent = '';
            }
        }

        function tw_addTableRow() {
            const table = document.getElementById('tw_email_table').getElementsByTagName('tbody')[0];
            const newRow = table.insertRow();
            const columnCount = table.parentElement.getElementsByTagName('thead')[0].rows[0].cells.length;
            
            for (let i = 0; i < columnCount; i++) {
                const cell = newRow.insertCell();
                cell.innerHTML = '<input type="text" class="tw_editable_cell" placeholder="Data" onchange="tw_updateTableData()">';
            }
            tw_updateTableData();
        }

        function tw_removeTableRow() {
            const tbody = document.getElementById('tw_email_table').getElementsByTagName('tbody')[0];
            if (tbody.rows.length > 1) {
                tbody.deleteRow(tbody.rows.length - 1);
                tw_updateTableData();
            }
        }

        function tw_addTableColumn() {
            const table = document.getElementById('tw_email_table');
            const thead = table.getElementsByTagName('thead')[0];
            const tbody = table.getElementsByTagName('tbody')[0];
            
            // Add header
            const headerRow = thead.rows[0];
            const headerCell = headerRow.insertCell();
            headerCell.innerHTML = '<input type="text" class="tw_editable_cell" placeholder="Header" onchange="tw_updateTableData()">';
            
            // Add cells to existing rows
            for (let row of tbody.rows) {
                const cell = row.insertCell();
                cell.innerHTML = '<input type="text" class="tw_editable_cell" placeholder="Data" onchange="tw_updateTableData()">';
            }
            tw_updateTableData();
        }

        function tw_removeTableColumn() {
            const table = document.getElementById('tw_email_table');
            const thead = table.getElementsByTagName('thead')[0];
            const tbody = table.getElementsByTagName('tbody')[0];
            
            if (thead.rows[0].cells.length > 1) {
                // Remove header
                thead.rows[0].deleteCell(-1);
                
                // Remove cells from all rows
                for (let row of tbody.rows) {
                    row.deleteCell(-1);
                }
                tw_updateTableData();
            }
        }

        function tw_updateTableData() {
            const table = document.getElementById('tw_email_table');
            const data = {
                headers: [],
                rows: []
            };
            
            // Get headers
            const headerRow = table.getElementsByTagName('thead')[0].rows[0];
            for (let cell of headerRow.cells) {
                data.headers.push(cell.querySelector('input').value);
            }
            
            // Get data rows
            const tbody = table.getElementsByTagName('tbody')[0];
            for (let row of tbody.rows) {
                const rowData = [];
                for (let cell of row.cells) {
                    rowData.push(cell.querySelector('input').value);
                }
                data.rows.push(rowData);
            }
            
            document.getElementById('tw_table_data_input').value = JSON.stringify(data);
        }

        // Auto-select all recipients functionality
        function tw_selectAllRecipients() {
            const checkboxes = document.querySelectorAll('input[name="recipients[]"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
        }

        function tw_deselectAllRecipients() {
            const checkboxes = document.querySelectorAll('input[name="recipients[]"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
        }
    </script>

    <!-- Add Select All/None buttons for recipients -->
    <style>
        .tw_recipient_controls {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            justify-content: flex-end;
        }

        .tw_control_btn {
            background: #e2e8f0;
            color: #4a5568;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .tw_control_btn:hover {
            background: #cbd5e0;
        }
    </style>

    <script>
        // Add control buttons after DOM content loaded
        document.addEventListener('DOMContentLoaded', function() {
            const recipientsContainer = document.getElementById('tw_recipients_container');
            const controlsDiv = document.createElement('div');
            controlsDiv.className = 'tw_recipient_controls';
            controlsDiv.innerHTML = `
                <button type="button" class="tw_control_btn" onclick="tw_selectAllRecipients()">✅ Select All</button>
                <button type="button" class="tw_control_btn" onclick="tw_deselectAllRecipients()">❌ Clear All</button>
            `;
            recipientsContainer.parentNode.insertBefore(controlsDiv, recipientsContainer);
        });
    </script>
</body>
</html>
