<?php
require_once '../config/database.php';
require_once '../includes/company_config.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$user_id = isset($_GET['user_id']) ? mysqli_real_escape_string($conn, $_GET['user_id']) : 0;

if (!$user_id) {
    exit('No user ID provided');
}

// Get company details
$company = getCompanyDetails($conn);

// Get user details
$query = "SELECT * FROM users WHERE user_id = '$user_id'";
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);

if (!$user) {
    exit('User not found');
}

// Get email templates
$templates_query = "SELECT * FROM email_templates ORDER BY category, title";
$templates_result = mysqli_query($conn, $templates_query);

$templates = [];
while ($row = mysqli_fetch_assoc($templates_result)) {
    // Store templates as-is (they already have HTML)
    $templates[] = $row;
}

// Get email logs count
$logs_query = "SELECT COUNT(*) as sent_count FROM email_logs WHERE user_id = '$user_id' AND status = 'sent'";
$logs_result = mysqli_query($conn, $logs_query);
$sent_count = mysqli_fetch_assoc($logs_result)['sent_count'] ?? 0;
?>

<!-- Email Stats -->
<div class="email-stats">
    <div class="email-stat-item">
        <div class="email-stat-value"><?php echo $sent_count; ?></div>
        <div class="email-stat-label">Emails Sent</div>
    </div>
    <div class="email-stat-item">
        <div class="email-stat-value"><?php echo htmlspecialchars($company['name']); ?></div>
        <div class="email-stat-label">Company</div>
    </div>
</div>

<!-- User Email Info -->
<div class="user-email-info">
    <div class="d-flex align-items-center justify-content-between">
        <div>
            <small class="text-muted">Recipient</small>
            <h6 class="mb-0"><?php echo htmlspecialchars($user['email']); ?></h6>
            <small><?php echo htmlspecialchars($user['name']); ?></small>
        </div>
        <button class="btn btn-outline-primary btn-sm" onclick="editUserEmail('<?php echo $user['user_id']; ?>', '<?php echo addslashes($user['email']); ?>')">
            <i class="fas fa-edit"></i> Edit
        </button>
    </div>
</div>

<!-- Quick Compose -->
<button class="btn btn-primary w-100 mb-4" onclick="openEmailComposer(<?php echo $user['user_id']; ?>, '<?php echo addslashes($user['email']); ?>', '<?php echo addslashes($user['name']); ?>')">
    <i class="fas fa-paper-plane me-2"></i>Compose New Email
</button>

<!-- Templates -->
<h6 class="mb-3">Email Templates</h6>
<div class="template-grid">
    <?php foreach ($templates as $index => $template): ?>
        <div class="template-card" onclick="loadTemplate(<?php echo $index; ?>)">
            <div class="template-icon">
                <?php
                $icons = [
                    'welcome' => '🎉',
                    'general' => '🙏',
                    'account' => '✅',
                    'kyc' => '🔐',
                    'withdrawal' => '💰',
                    'pin' => '🔑',
                    'support' => '🎫',
                    'promo' => '🌟',
                    'legal' => '📋'
                ];
                echo $icons[$template['category']] ?? '📧';
                ?>
            </div>
            <div class="template-content">
                <h6><?php echo htmlspecialchars($template['title']); ?></h6>
                <small><?php echo htmlspecialchars($template['subject']); ?></small>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<style>
.email-stats {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin-bottom: 20px;
}

.email-stat-item {
    background: #f8fafc;
    border-radius: 10px;
    padding: 15px;
    text-align: center;
}

.email-stat-value {
    font-size: 1.5rem;
    font-weight: 700;
    color: #667eea;
}

.email-stat-label {
    font-size: 0.8rem;
    color: #64748b;
}

.user-email-info {
    background: #f8fafc;
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 20px;
}

.template-grid {
    display: grid;
    gap: 10px;
    max-height: 400px;
    overflow-y: auto;
}

.template-card {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    padding: 12px;
    display: flex;
    align-items: center;
    gap: 12px;
    cursor: pointer;
    transition: all 0.2s;
}

.template-card:hover {
    border-color: #667eea;
    transform: translateX(5px);
    box-shadow: 0 2px 10px rgba(102, 126, 234, 0.1);
}

.template-icon {
    font-size: 24px;
    width: 40px;
    height: 40px;
    background: #f8fafc;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.template-content {
    flex: 1;
}

.template-content h6 {
    margin: 0 0 3px 0;
    font-size: 0.95rem;
}

.template-content small {
    color: #64748b;
    font-size: 0.8rem;
}
</style>

<script>
// Store templates in JavaScript
const emailTemplates = <?php echo json_encode($templates); ?>;
const companyDetails = <?php echo json_encode($company); ?>;

function loadTemplate(index) {
    const template = emailTemplates[index];
    const userEmail = '<?php echo addslashes($user['email']); ?>';
    const userName = '<?php echo addslashes($user['name']); ?>';
    const userId = '<?php echo $user['user_id']; ?>';
    
    document.getElementById('emailUserId').value = userId;
    document.getElementById('emailTo').value = userEmail;
    document.getElementById('emailSubject').value = template.subject;
    
    // Replace placeholders in content
    let content = template.content;
    content = content.replace(/{user_name}/g, userName);
    content = content.replace(/{user_id}/g, userId);
    content = content.replace(/{user_email}/g, userEmail);
    content = content.replace(/{company_name}/g, companyDetails.name);
    content = content.replace(/{company_email}/g, companyDetails.email);
    content = content.replace(/{company_phone}/g, companyDetails.mobile);
    content = content.replace(/{date}/g, new Date().toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' }));
    
    document.getElementById('emailMessage').value = content;
    toggleEmailComposer();
}
    


// Override the form submission to format the content
const originalEmailFormSubmit = document.getElementById('emailForm')?.onsubmit;
document.getElementById('emailForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    // Prevent double submission
    if (window.isSending) {
        console.log('Already sending...');
        return;
    }
    
    const messageInput = document.getElementById('emailMessage');
    const originalMessage = messageInput.value;
    
    // Format the message
    const formattedMessage = formatEmailContent(originalMessage);
    
    // Create a hidden input with formatted message
    let hiddenInput = document.getElementById('formattedMessageInput');
    if (!hiddenInput) {
        hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = 'formatted_message';
        hiddenInput.id = 'formattedMessageInput';
        this.appendChild(hiddenInput);
    }
    hiddenInput.value = formattedMessage;
    
    // Validate
    const userId = document.getElementById('emailUserId').value;
    const toEmail = document.getElementById('emailTo').value;
    const subject = document.getElementById('emailSubject').value.trim();
    
    if (!userId || !toEmail || !subject || !originalMessage.trim()) {
        showAlert('Please fill in all fields', 'error');
        return;
    }
    
    // Disable button
    window.isSending = true;
    const sendBtn = document.getElementById('sendEmailBtn');
    const originalBtnText = sendBtn.innerHTML;
    sendBtn.disabled = true;
    sendBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
    
    try {
        const formData = new FormData(this);
        
        // Debug: log what we're sending
        console.log('Sending email to:', toEmail);
        console.log('Subject:', subject);
        console.log('Formatted message:', formattedMessage);
        
        const response = await fetch('ajax/send_email.php', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        console.log('Send result:', result);
        
        if (result.success) {
            showAlert('Email sent successfully!', 'success');
            // Clear form
            document.getElementById('emailSubject').value = '';
            document.getElementById('emailMessage').value = '';
            document.getElementById('emailTemplate').value = '';
            toggleEmailComposer();
        } else {
            showAlert('Error: ' + (result.error || 'Unknown error'), 'error');
        }
    } catch (error) {
        console.error('Send error:', error);
        showAlert('Failed to send email: ' + error.message, 'error');
    } finally {
        window.isSending = false;
        sendBtn.disabled = false;
        sendBtn.innerHTML = originalBtnText;
    }
});

// Update template loading to preserve formatting
const originalLoadTemplate = window.loadTemplate || function(index) {
    const templates = window.emailTemplates || [];
    const template = templates[index];
    
    if (!template) return;
    
    document.getElementById('emailUserId').value = '<?php echo $user['user_id'] ?? ''; ?>';
    document.getElementById('emailTo').value = '<?php echo addslashes($user['email'] ?? ''); ?>';
    document.getElementById('emailSubject').value = template.subject;
    
    // Replace placeholders
    let content = template.content;
    const userName = '<?php echo addslashes($user['name'] ?? 'User'); ?>';
    const userId = '<?php echo $user['user_id'] ?? ''; ?>';
    const companyName = '<?php echo addslashes($company['name'] ?? ''); ?>';
    const date = new Date().toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' });
    
    content = content.replace(/{user_name}/g, userName)
                     .replace(/{user_id}/g, userId)
                     .replace(/{user_email}/g, document.getElementById('emailTo').value)
                     .replace(/{company_name}/g, companyName)
                     .replace(/{date}/g, date);
    
    document.getElementById('emailMessage').value = content;
    toggleEmailComposer();
};
window.loadTemplate = originalLoadTemplate;

// Add a preview function
function previewEmail() {
    const message = document.getElementById('emailMessage').value;
    const formattedMessage = formatEmailContent(message);
    const subject = document.getElementById('emailSubject').value;
    const toEmail = document.getElementById('emailTo').value;
    const companyName = '<?php echo addslashes($company['name'] ?? ''); ?>';
    
    const previewWindow = window.open('', '_blank', 'width=800,height=600');
    previewWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Email Preview</title>
            <style>
                body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
                .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; }
                .content { padding: 30px; }
                .footer { background: #f8fafc; padding: 20px; text-align: center; border-top: 1px solid #e2e8f0; }
                .info-box { background: #f8fafc; border-left: 4px solid #667eea; padding: 15px; margin: 20px 0; }
                pre { background: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>${companyName}</h1>
                </div>
                <div class="content">
                    <h3>Email Preview</h3>
                    <p><strong>To:</strong> ${toEmail}</p>
                    <p><strong>Subject:</strong> ${subject}</p>
                    <hr>
                    <div class="email-body">
                        ${formattedMessage}
                    </div>
                    <hr>
                    <h4>Raw Content (for debugging):</h4>
                    <pre>${message.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>
                </div>
                <div class="footer">
                    <p>This is a preview only. No email has been sent.</p>
                </div>
            </div>
        </body>
        </html>
    `);
}

// Add a preview button to the email composer
function addPreviewButton() {
    const composerActions = document.querySelector('.composer-actions');
    if (composerActions) {
        const previewBtn = document.createElement('button');
        previewBtn.type = 'button';
        previewBtn.className = 'composer-btn secondary';
        previewBtn.innerHTML = '<i class="fas fa-eye me-2"></i>Preview';
        previewBtn.onclick = previewEmail;
        composerActions.insertBefore(previewBtn, composerActions.firstChild);
    }
}

// Call this when email composer opens
const originalToggleComposer = window.toggleEmailComposer;
window.toggleEmailComposer = function() {
    originalToggleComposer();
    if (document.getElementById('emailComposer').style.display !== 'none') {
        setTimeout(addPreviewButton, 100);
    }
};
</script>


