<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'php/adminconfig.php';

// Enhanced login and role check
if (!isset($_SESSION['admin_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: signin-admin.php');
    exit();
}

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

// Include PHPMailer
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';

// Email sending function with attachment support
function send_mail($recipient, $subject, $message, $attachments = []) {
    $mail = new PHPMailer();
    $mail->IsSMTP();
    
    $mail->SMTPDebug = 0;
    $mail->SMTPAuth = TRUE;
    $mail->SMTPSecure = "tls";
    $mail->Port = 587;
    $mail->Host = "mail.ifctrades.live";
    $mail->Username = "tradewave@ifctrades.live";
    $mail->Password = "#Trader00#";
    
    $mail->IsHTML(true);
    $mail->AddAddress($recipient, "esteemed customer");
    $mail->SetFrom("tradewave@ifctrades.live", "Tradewave Verification");
    $mail->Subject = $subject;
    $mail->Body = $message;
    
    // Add attachments if provided
    if (!empty($attachments)) {
        foreach ($attachments as $attachment) {
            if (file_exists($attachment['path'])) {
                $mail->addAttachment($attachment['path'], $attachment['name']);
            }
        }
    }
    
    return $mail->Send();
}

// File upload handling function
function handle_file_uploads() {
    $uploaded_files = [];
    $upload_dir = 'uploads/email_attachments/';
    
    // Create upload directory if it doesn't exist
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    if (isset($_FILES['attachments'])) {
        $files = $_FILES['attachments'];
        
        // Handle multiple files
        for ($i = 0; $i < count($files['name']); $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $file_name = $files['name'][$i];
                $file_tmp = $files['tmp_name'][$i];
                $file_size = $files['size'][$i];
                $file_type = $files['type'][$i];
                
                // Validate file size (max 10MB)
                if ($file_size > 10 * 1024 * 1024) {
                    continue; // Skip files larger than 10MB
                }
                
                // Validate file type
                $allowed_types = [
                    'application/pdf',
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'application/vnd.ms-excel',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'image/jpeg',
                    'image/png',
                    'image/gif',
                    'image/bmp',
                    'text/plain',
                    'application/zip',
                    'application/x-zip-compressed'
                ];
                
                if (!in_array($file_type, $allowed_types)) {
                    continue; // Skip unsupported file types
                }
                
                // Generate unique filename
                $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
                $unique_name = uniqid() . '_' . time() . '.' . $file_extension;
                $file_path = $upload_dir . $unique_name;
                
                if (move_uploaded_file($file_tmp, $file_path)) {
                    $uploaded_files[] = [
                        'path' => $file_path,
                        'name' => $file_name,
                        'size' => $file_size,
                        'type' => $file_type
                    ];
                }
            }
        }
    }
    
    return $uploaded_files;
}

// Email templates
function get_email_template($type, $custom_message, $user_data) {
    $logo_url = "https://tradewave.ifctrades.live/ifctrading/images/icon.png";
    $trinidad_colors = "linear-gradient(135deg, #ff0000 0%, #ffffff 33%, #000000 66%, #ffffff 100%)";
    
    $base_style = "
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
        line-height: 1.6;
        color: #333;
        max-width: 600px;
        margin: 0 auto;
        background: #f8f9fa;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    ";
    
    $header = "
        <div style='background: {$trinidad_colors}; padding: 3px 0;'></div>
        <div style='background: white; padding: 30px; text-align: center; border-bottom: 1px solid #e9ecef;'>
            <img src='{$logo_url}' alt='Tradewave TT' style='max-width: 80px; margin-bottom: 15px;'>
            <h1 style='color: #2c3e50; margin: 0; font-size: 24px; font-weight: 600;'>Tradewave TT</h1>
            <p style='color: #6c757d; margin: 5px 0 0 0; font-size: 14px;'>Trading Excellence Since Always</p>
        </div>
    ";
    
    $footer = "
        <div style='background: #f8f9fa; padding: 25px; text-align: center; border-top: 1px solid #e9ecef;'>
            <div style='margin-bottom: 15px;'>
                <svg width='20' height='20' viewBox='0 0 24 24' fill='none' stroke='#6c757d' stroke-width='2' style='margin: 0 5px;'>
                    <path d='M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z'></path>
                    <polyline points='22,6 12,13 2,6'></polyline>
                </svg>
                <span style='color: #6c757d; font-size: 14px;'>tradewave@ifctrades.live</span>
            </div>
            <p style='color: #6c757d; font-size: 12px; margin: 0;'>
                © 2024 Tradewave TT Company. All rights reserved.<br>
                This email was sent to {$user_data['email']}
            </p>
        </div>
        <div style='background: {$trinidad_colors}; padding: 3px 0;'></div>
    ";
    
    $templates = [
        'vat_alert' => [
            'subject' => 'VAT Alert - Action Required',
            'icon' => '<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#e74c3c" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>',
            'content' => "
                <div style='text-align: center; margin: 30px 0;'>
                    <div style='background: #fee; padding: 20px; border-radius: 8px; margin-bottom: 20px;'>
                        <svg width='40' height='40' viewBox='0 0 24 24' fill='none' stroke='#e74c3c' stroke-width='2' style='margin-bottom: 10px;'>
                            <path d='M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z'></path>
                            <line x1='12' y1='9' x2='12' y2='13'></line>
                            <line x1='12' y1='17' x2='12.01' y2='17'></line>
                        </svg>
                        <h2 style='color: #e74c3c; margin: 10px 0; font-size: 20px;'>VAT Alert</h2>
                    </div>
                    <p style='color: #555; font-size: 16px; margin-bottom: 25px;'>Dear {$user_data['firstname']} {$user_data['lastname']},</p>
                    <div style='background: white; padding: 25px; border-radius: 8px; text-align: left; border-left: 4px solid #e74c3c;'>
                        {$custom_message}
                    </div>
                </div>
            "
        ],
        'certificate_pending' => [
            'subject' => 'Certificate Verification Pending',
            'icon' => '<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#f39c12" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><polyline points="12,6 12,12 16,14"></polyline></svg>',
            'content' => "
                <div style='text-align: center; margin: 30px 0;'>
                    <div style='background: #fef9e7; padding: 20px; border-radius: 8px; margin-bottom: 20px;'>
                        <svg width='40' height='40' viewBox='0 0 24 24' fill='none' stroke='#f39c12' stroke-width='2' style='margin-bottom: 10px;'>
                            <circle cx='12' cy='12' r='10'></circle>
                            <polyline points='12,6 12,12 16,14'></polyline>
                        </svg>
                        <h2 style='color: #f39c12; margin: 10px 0; font-size: 20px;'>Certificate Pending</h2>
                    </div>
                    <p style='color: #555; font-size: 16px; margin-bottom: 25px;'>Dear {$user_data['firstname']} {$user_data['lastname']},</p>
                    <div style='background: white; padding: 25px; border-radius: 8px; text-align: left; border-left: 4px solid #f39c12;'>
                        {$custom_message}
                    </div>
                </div>
            "
        ],
        'certificate_verified' => [
            'subject' => 'Certificate Successfully Verified',
            'icon' => '<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#27ae60" stroke-width="2"><path d="M9 12l2 2 4-4"></path><circle cx="12" cy="12" r="10"></circle></svg>',
            'content' => "
                <div style='text-align: center; margin: 30px 0;'>
                    <div style='background: #eef7ed; padding: 20px; border-radius: 8px; margin-bottom: 20px;'>
                        <svg width='40' height='40' viewBox='0 0 24 24' fill='none' stroke='#27ae60' stroke-width='2' style='margin-bottom: 10px;'>
                            <path d='M9 12l2 2 4-4'></path>
                            <circle cx='12' cy='12' r='10'></circle>
                        </svg>
                        <h2 style='color: #27ae60; margin: 10px 0; font-size: 20px;'>Certificate Verified</h2>
                    </div>
                    <p style='color: #555; font-size: 16px; margin-bottom: 25px;'>Dear {$user_data['firstname']} {$user_data['lastname']},</p>
                    <div style='background: white; padding: 25px; border-radius: 8px; text-align: left; border-left: 4px solid #27ae60;'>
                        {$custom_message}
                    </div>
                </div>
            "
        ]
    ];
    
    $template = $templates[$type];
    
    return [
        'subject' => $template['subject'],
        'body' => "<div style='{$base_style}'>{$header}{$template['content']}{$footer}</div>"
    ];
}

// Handle form submission
$success_message = '';
$error_message = '';

if ($_POST) {
    $email_type = $_POST['email_type'] ?? '';
    $custom_message = $_POST['custom_message'] ?? '';
    $selected_users = $_POST['selected_users'] ?? [];
    
    if (empty($selected_users)) {
        $error_message = 'Please select at least one user.';
    } elseif (empty($custom_message)) {
        $error_message = 'Please enter a custom message.';
    } else {
        // Handle file uploads
        $uploaded_files = handle_file_uploads();
        
        $success_count = 0;
        $failed_emails = [];
        
        foreach ($selected_users as $user_id) {
            try {
                // Get user data
                $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($user) {
                    $email_data = get_email_template($email_type, $custom_message, $user);
                    
                    if (send_mail($user['email'], $email_data['subject'], $email_data['body'], $uploaded_files)) {
                        $success_count++;
                    } else {
                        $failed_emails[] = $user['email'];
                    }
                }
            } catch (Exception $e) {
                $failed_emails[] = $user['email'] ?? 'Unknown';
            }
        }
        
        // Log email sending
        $stmt = $conn->prepare("INSERT INTO email_logs (user_ids, email_type, custom_message, success_count, failed_emails, admin_id, attachments) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            json_encode($selected_users),
            $email_type,
            $custom_message,
            $success_count,
            json_encode($failed_emails),
            $_SESSION['admin_id'],
            json_encode($uploaded_files)
        ]);
        
        if ($success_count > 0) {
            $success_message = "Successfully sent {$success_count} emails.";
            if (!empty($failed_emails)) {
                $success_message .= " " . count($failed_emails) . " emails failed to send.";
            }
        } else {
            $error_message = "Failed to send all emails.";
        }
        
        // Clean up uploaded files after sending
        foreach ($uploaded_files as $file) {
            if (file_exists($file['path'])) {
                unlink($file['path']);
            }
        }
    }
}

// Fetch all users
$stmt = $conn->prepare("SELECT id, firstname, lastname, email, status FROM users ORDER BY firstname, lastname");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Management - Tradewave TT Admin</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="css/mailing.css">
    <style>
        .twv-file-upload {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            background: #f9f9f9;
            transition: all 0.3s ease;
            margin-bottom: 15px;
        }
        
        .twv-file-upload:hover {
            border-color: #007bff;
            background: #f0f8ff;
        }
        
        .twv-file-upload.dragover {
            border-color: #007bff;
            background: #e6f3ff;
        }
        
        .twv-file-input {
            display: none;
        }
        
        .twv-file-label {
            display: inline-block;
            padding: 10px 20px;
            background: #007bff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .twv-file-label:hover {
            background: #0056b3;
        }
        
        .twv-file-list {
            margin-top: 15px;
        }
        
        .twv-file-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-bottom: 5px;
        }
        
        .twv-file-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .twv-file-icon {
            font-size: 20px;
            color: #007bff;
        }
        
        .twv-file-details {
            flex: 1;
        }
        
        .twv-file-name {
            font-weight: 500;
            margin-bottom: 2px;
        }
        
        .twv-file-size {
            font-size: 12px;
            color: #666;
        }
        
        .twv-file-remove {
            background: #dc3545;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .twv-file-remove:hover {
            background: #c82333;
        }
        
        .twv-file-note {
            font-size: 12px;
            color: #666;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="twv-admin-container">
        <div class="twv-header">
            <h1>
                <div class="twv-logo">
                    <i class="fas fa-envelope"></i>
                </div>
                Email Management System
            </h1>
        </div>
        
        <div class="twv-content">
            <?php if ($success_message): ?>
                <div class="twv-alert twv-alert-success">
                    <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error_message): ?>
                <div class="twv-alert twv-alert-error">
                    <i class="fas fa-exclamation-circle"></i> <?php echo $error_message; ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" id="twv-email-form" enctype="multipart/form-data">
                <div class="twv-form-group">
                    <label for="email_type">Email Type:</label>
                    <select name="email_type" id="email_type" class="twv-select" required>
                        <option value="">Select Email Type</option>
                        <option value="vat_alert">VAT Alert</option>
                        <option value="certificate_pending">Certificate Pending</option>
                        <option value="certificate_verified">Certificate Verified</option>
                    </select>
                </div>
                
                <div class="twv-form-group">
                    <label for="custom_message">Custom Message:</label>
                    <textarea name="custom_message" id="custom_message" class="twv-textarea" placeholder="Enter your custom message here..." required></textarea>
                </div>
                
                <div class="twv-form-group">
                    <label>File Attachments (Optional):</label>
                    <div class="twv-file-upload" id="file-upload-area">
                        <i class="fas fa-cloud-upload-alt" style="font-size: 40px; color: #007bff; margin-bottom: 10px;"></i>
                        <p>Drag and drop files here or click to select</p>
                        <input type="file" name="attachments[]" id="file-input" class="twv-file-input" multiple accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif,.bmp,.txt,.zip">
                        <label for="file-input" class="twv-file-label">
                            <i class="fas fa-folder-open"></i> Choose Files
                        </label>
                    </div>
                    <div class="twv-file-list" id="file-list"></div>
                    <div class="twv-file-note">
                        <i class="fas fa-info-circle"></i> 
                        Supported formats: PDF, DOC, DOCX, XLS, XLSX, JPG, JPEG, PNG, GIF, BMP, TXT, ZIP (Max 10MB per file)
                    </div>
                </div>
                
                <div class="twv-form-group">
                    <label>Select Users:</label>
                    <div class="twv-select-all">
                        <input type="checkbox" id="select-all">
                        <label for="select-all">Select All Users</label>
                    </div>
                    <div class="twv-users-grid">
                        <?php foreach ($users as $user): ?>
                            <div class="twv-user-card" onclick="toggleUser(<?php echo $user['id']; ?>)">
                                <div class="twv-user-info">
                                    <input type="checkbox" name="selected_users[]" value="<?php echo $user['id']; ?>" id="user-<?php echo $user['id']; ?>">
                                    <div class="twv-user-avatar">
                                        <?php echo strtoupper(substr($user['firstname'], 0, 1)); ?>
                                    </div>
                                    <div class="twv-user-details">
                                        <h4><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></h4>
                                        <p><?php echo htmlspecialchars($user['email']); ?></p>
                                        <span class="twv-status-badge <?php echo $user['status'] === 'Active' ? 'twv-status-active' : 'twv-status-pending'; ?>">
                                            <?php echo $user['status']; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <button type="submit" class="twv-btn">
                    <i class="fas fa-paper-plane"></i> Send Emails
                </button>
            </form>
        </div>
    </div>
    
    <script>
        let selectedFiles = [];
        
        document.getElementById('select-all').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('input[name="selected_users[]"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
        
        function toggleUser(userId) {
            const checkbox = document.getElementById('user-' + userId);
            checkbox.checked = !checkbox.checked;
            
            // Update select all checkbox
            const selectAllCheckbox = document.getElementById('select-all');
            const allCheckboxes = document.querySelectorAll('input[name="selected_users[]"]');
            const checkedCheckboxes = document.querySelectorAll('input[name="selected_users[]"]:checked');
            
            selectAllCheckbox.checked = allCheckboxes.length === checkedCheckboxes.length;
        }
        
        // File upload handling
        const fileInput = document.getElementById('file-input');
        const fileUploadArea = document.getElementById('file-upload-area');
        const fileList = document.getElementById('file-list');
        
        // File type icons
        function getFileIcon(fileName) {
            const extension = fileName.split('.').pop().toLowerCase();
            const icons = {
                'pdf': 'fas fa-file-pdf',
                'doc': 'fas fa-file-word',
                'docx': 'fas fa-file-word',
                'xls': 'fas fa-file-excel',
                'xlsx': 'fas fa-file-excel',
                'jpg': 'fas fa-file-image',
                'jpeg': 'fas fa-file-image',
                'png': 'fas fa-file-image',
                'gif': 'fas fa-file-image',
                'bmp': 'fas fa-file-image',
                'txt': 'fas fa-file-alt',
                'zip': 'fas fa-file-archive'
            };
            return icons[extension] || 'fas fa-file';
        }
        
        // Format file size
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // Handle file selection
        fileInput.addEventListener('change', function(e) {
            handleFiles(e.target.files);
        });
        
        // Drag and drop functionality
        fileUploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            fileUploadArea.classList.add('dragover');
        });
        
        fileUploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            fileUploadArea.classList.remove('dragover');
        });
        
        fileUploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            fileUploadArea.classList.remove('dragover');
            handleFiles(e.dataTransfer.files);
        });
        
        function handleFiles(files) {
            Array.from(files).forEach(file => {
                // Check file size (10MB limit)
                if (file.size > 10 * 1024 * 1024) {
                    alert(`File "${file.name}" is too large. Maximum size is 10MB.`);
                    return;
                }
                
                // Check if file already exists
                if (selectedFiles.some(f => f.name === file.name && f.size === file.size)) {
                    alert(`File "${file.name}" is already selected.`);
                    return;
                }
                
                selectedFiles.push(file);
            });
            
            updateFileList();
            updateFileInput();
        }
        
        function updateFileList() {
            fileList.innerHTML = '';
            
            selectedFiles.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'twv-file-item';
                fileItem.innerHTML = `
                    <div class="twv-file-info">
                        <i class="${getFileIcon(file.name)} twv-file-icon"></i>
                        <div class="twv-file-details">
                            <div class="twv-file-name">${file.name}</div>
                            <div class="twv-file-size">${formatFileSize(file.size)}</div>
                        </div>
                    </div>
                    <button type="button" class="twv-file-remove" onclick="removeFile(${index})">
                        <i class="fas fa-times"></i>
                    </button>
                `;
                fileList.appendChild(fileItem);
            });
        }
        
        function removeFile(index) {
            selectedFiles.splice(index, 1);
            updateFileList();
            updateFileInput();
        }
        
        function updateFileInput() {
            // Create a new DataTransfer object to update the file input
            const dt = new DataTransfer();
            selectedFiles.forEach(file => dt.items.add(file));
            fileInput.files = dt.files;
        }
        
        // Prevent form submission if no users selected
        document.getElementById('twv-email-form').addEventListener('submit', function(e) {
            const selectedUsers = document.querySelectorAll('input[name="selected_users[]"]:checked');
            if (selectedUsers.length === 0) {
                e.preventDefault();
                alert('Please select at least one user.');
            }
        });
        
        // Auto-resize textarea
        document.getElementById('custom_message').addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    </script>
</body>
</html>s