<?php
//session_start();
//if (!isset($_SESSION['user_id'])) {
//    header("Location: login.php");
//    exit();
//}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Email - SPARK</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Add Font Awesome for icons -->
    <script src="https://kit.fontawesome.com/475afa2c37.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>Create Email</h1>
        <a href="index.php" class="home-button"><i class="fas fa-house"></i></a>
    </div>

    <div class="content">
        <div class="input-section">
            <textarea id="bulletPoints" rows="10" placeholder="Enter your bullet points here..."></textarea>
            
            <div class="tone-selector">
                <label for="tone">Tone:</label>
                <select id="tone">
                    <option value="casual">Casual</option>
                    <option value="friendly">Friendly</option>
                    <option value="serious">Serious</option>
                    <option value="professional">Professional</option>
                </select>
            </div>

            <button onclick="generateEmail()" class="primary-button">Write Email</button>
        </div>

        <div id="loadingSection" style="display: none;" class="loading-section">
            <div class="loader"></div>
            <p>Generating your email...</p>
        </div>

        <div id="response-section" class="response-section">
            <div id="emailResponse" class="response-area"></div>
            
            <div class="button-group">
                <button onclick="copyToClipboard()" class="secondary-button">
                    <i class="fas fa-copy"></i> Copy
                </button>
                <button onclick="sendEmail()" class="secondary-button">
                    <i class="fas fa-envelope"></i> Email
                </button>
            </div>
        </div>
    </div>
</div>

<a href="index.php" class="home-button">
        <i class="fas fa-house"></i>
    </a>

    <script>
        async function generateEmail() {
    const bulletPoints = document.getElementById('bulletPoints').value;
    const tone = document.getElementById('tone').value;
    
    if (!bulletPoints) {
        alert('Please enter your bullet points');
        return;
    }

    const loadingSection = document.getElementById('loadingSection');
    const responseSection = document.getElementById('response-section');
    const emailResponse = document.getElementById('emailResponse');

    loadingSection.style.display = 'block';
    responseSection.style.display = 'none';

    const prompt = `Please convert these bullet points into a ${tone} email:\n${bulletPoints}`;

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

        const data = await response.json();
        emailResponse.innerHTML = data.response;
        loadingSection.style.display = 'none';
        responseSection.style.display = 'block';
    } catch (error) {
        console.error('Error:', error);
        alert('An error occurred while generating the email');
        loadingSection.style.display = 'none';
    }
}


async function copyToClipboard() {
    const responseText = document.getElementById('emailResponse').innerHTML;
    if (!responseText) {
        alert('No content to copy');
        return;
    }

    try {
        // Create a temporary textarea element to handle HTML content
        const tempTextArea = document.createElement('textarea');
        //tempTextArea.value = responseText.replace(/<br\s*[\/]?>/gi, "\n");
        tempTextArea.value = responseText.replace(/<br\s*[\/]?>/gi, "\n").replace(/<\/?p>/gi, "");
        //tempTextArea.value = responseText;
        document.body.appendChild(tempTextArea);
        
        // Select the text
        tempTextArea.select();
        
        // Try the modern clipboard API first
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(tempTextArea.value);
        } else {
            // Fallback to older method
            document.execCommand('copy');
        }
        
        // Clean up
        document.body.removeChild(tempTextArea);
        
        alert('Email copied to clipboard!');
    } catch (err) {
        console.error('Failed to copy text:', err);
        alert('Failed to copy text. Please try selecting and copying manually.');
    }
}


async function sendEmail() {
    const emailContent = document.getElementById('emailResponse').textContent;
    
    try {
        const response = await fetch('send_email.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ content: emailContent })
        });

        if (response.ok) {
            alert('Email sent successfully!');
        } else {
            throw new Error('Failed to send email');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error sending email: ' + error.message);
    }
}

    </script>
</head>
</body>
</html>
