<?php
header('Content-Type: application/json');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Validate and sanitize input data
function sanitizeInput($data) {
    if (is_array($data)) {
        return array_map('sanitizeInput', $data);
    }
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    return $data;
}

// Sanitize data for CSV to prevent injection
function sanitizeForCSV($value) {
    $value = str_replace('"', '""', $value);
    $value = preg_replace("/[\r\n]/", " ", $value);
    return '"' . $value . '"';
}

// Initialize response array
$response = ['success' => false, 'message' => '', 'redirect' => ''];

try {
    // Check if form was submitted
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method.');
    }

    // Collect all form data
    $formData = [
        'email' => isset($_POST['email']) ? sanitizeInput($_POST['email']) : '',
        'full_name' => isset($_POST['full_name']) ? sanitizeInput($_POST['full_name']) : '',
        'phone' => isset($_POST['phone']) ? sanitizeInput($_POST['phone']) : '',
        'country' => isset($_POST['country']) ? sanitizeInput($_POST['country']) : '',
        'other_country' => isset($_POST['other_country']) ? sanitizeInput($_POST['other_country']) : '',
        'age_group' => isset($_POST['age_group']) ? sanitizeInput($_POST['age_group']) : '',
        'experience_level' => isset($_POST['experience_level']) ? sanitizeInput($_POST['experience_level']) : '',
        
        // New trader fields
        'starting_amount' => isset($_POST['starting_amount']) ? sanitizeInput($_POST['starting_amount']) : '',
        'new_funds_source' => isset($_POST['new_funds_source']) ? sanitizeInput($_POST['new_funds_source']) : '',
        
        // Experienced trader fields
        'investment_platforms' => isset($_POST['investment_platforms']) ? sanitizeInput($_POST['investment_platforms']) : '',
        'has_investments' => isset($_POST['has_investments']) ? sanitizeInput($_POST['has_investments']) : '',
        'exp_starting_amount' => isset($_POST['exp_starting_amount']) ? sanitizeInput($_POST['exp_starting_amount']) : '',
        'exp_funds_source' => isset($_POST['exp_funds_source']) ? sanitizeInput($_POST['exp_funds_source']) : '',
        'trading_background' => isset($_POST['trading_background']) ? sanitizeInput($_POST['trading_background']) : '',
        'trading_features' => isset($_POST['trading_features']) ? sanitizeInput($_POST['trading_features']) : '',
        'trading_effects' => isset($_POST['trading_effects']) ? sanitizeInput($_POST['trading_effects']) : '',
        
        // Common fields
        'main_goal' => isset($_POST['main_goal']) ? sanitizeInput($_POST['main_goal']) : '',
        'trading_involvement' => isset($_POST['trading_involvement']) ? sanitizeInput($_POST['trading_involvement']) : '',
        'portfolio_reaction' => isset($_POST['portfolio_reaction']) ? sanitizeInput($_POST['portfolio_reaction']) : '',
        'expected_return' => isset($_POST['expected_return']) ? sanitizeInput($_POST['expected_return']) : '',
        'return_period' => isset($_POST['return_period']) ? sanitizeInput($_POST['return_period']) : '',
        'risk_tolerance' => isset($_POST['risk_tolerance']) ? sanitizeInput($_POST['risk_tolerance']) : '',
        
        // Asset data
        'exp_asset_name' => isset($_POST['exp_asset_name']) ? sanitizeInput($_POST['exp_asset_name']) : [],
        'exp_asset_amount' => isset($_POST['exp_asset_amount']) ? sanitizeInput($_POST['exp_asset_amount']) : []
    ];

    // Basic validation
    if (empty($formData['email'])) {
        throw new Exception('Email address is required.');
    }
    
    if (!filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Please enter a valid email address.');
    }

    if (empty($formData['full_name'])) {
        throw new Exception('Full name is required.');
    }

    // 1. Send notification email to Carolyn
    $toCarolyn = 'kenneth.larkin@davidsonwealthteam.com';
    $subjectCarolyn = 'New Copy-Trading Setup Submission';
    
    // Build the email message to Carolyn
    $messageCarolyn = "<html><body>";
    $messageCarolyn .= "<h2>Copy-Trading Setup Questionnaire Submission</h2>";
    $messageCarolyn .= "<p><strong>Submitted:</strong> " . date('Y-m-d H:i:s') . "</p>";
    
    $messageCarolyn .= "<h3>Personal Information</h3>";
    $messageCarolyn .= "<p><strong>Name:</strong> " . $formData['full_name'] . "</p>";
    $messageCarolyn .= "<p><strong>Email:</strong> " . $formData['email'] . "</p>";
    $messageCarolyn .= "<p><strong>Phone:</strong> " . $formData['phone'] . "</p>";
    
    $country = $formData['country'] === 'other' ? $formData['other_country'] : $formData['country'];
    $messageCarolyn .= "<p><strong>Country:</strong> " . $country . "</p>";
    $messageCarolyn .= "<p><strong>Age Group:</strong> " . $formData['age_group'] . "</p>";
    
    $messageCarolyn .= "<h3>Trading Profile</h3>";
    $messageCarolyn .= "<p><strong>Experience Level:</strong> " . ($formData['experience_level'] === 'new' ? 'New to trading' : 'Experienced trader') . "</p>";
    
    if ($formData['experience_level'] === 'new') {
        $messageCarolyn .= "<h4>New Trader Details</h4>";
        $messageCarolyn .= "<p><strong>Starting Amount:</strong> $" . number_format($formData['starting_amount'], 2) . "</p>";
        $messageCarolyn .= "<p><strong>Source of Funds:</strong> " . $formData['new_funds_source'] . "</p>";
    } else {
        $messageCarolyn .= "<h4>Experienced Trader Details</h4>";
        $messageCarolyn .= "<p><strong>Investment Platforms:</strong> " . $formData['investment_platforms'] . "</p>";
        $messageCarolyn .= "<p><strong>Has Existing Investments:</strong> " . ($formData['has_investments'] === 'yes' ? 'Yes' : 'No') . "</p>";
        
        if ($formData['has_investments'] === 'yes') {
            $messageCarolyn .= "<p><strong>Assets to Trade:</strong></p><ul>";
            foreach ($formData['exp_asset_name'] as $index => $assetName) {
                if (!empty($assetName) && isset($formData['exp_asset_amount'][$index])) {
                    $amount = number_format($formData['exp_asset_amount'][$index], 2);
                    $messageCarolyn .= "<li>{$assetName}: $" . $amount . "</li>";
                }
            }
            $messageCarolyn .= "</ul>";
        } else {
            $messageCarolyn .= "<p><strong>Starting Amount:</strong> $" . number_format($formData['exp_starting_amount'], 2) . "</p>";
        }
        
        $messageCarolyn .= "<p><strong>Source of Funds:</strong> " . $formData['exp_funds_source'] . "</p>";
        $messageCarolyn .= "<p><strong>Trading Background:</strong> " . $formData['trading_background'] . "</p>";
        $messageCarolyn .= "<p><strong>Important Trading Features:</strong> " . $formData['trading_features'] . "</p>";
        $messageCarolyn .= "<p><strong>Desired Trading Effects:</strong> " . $formData['trading_effects'] . "</p>";
    }
    
    $messageCarolyn .= "<h3>Trading Preferences</h3>";
    $messageCarolyn .= "<p><strong>Main Goal:</strong> " . $formData['main_goal'] . "</p>";
    $messageCarolyn .= "<p><strong>Trading Involvement:</strong> " . $formData['trading_involvement'] . "</p>";
    $messageCarolyn .= "<p><strong>Portfolio Reaction to 15% Decline:</strong> " . $formData['portfolio_reaction'] . "</p>";
    $messageCarolyn .= "<p><strong>Expected Return Target:</strong> " . $formData['expected_return'] . "% " . $formData['return_period'] . "</p>";
    $messageCarolyn .= "<p><strong>Risk Tolerance:</strong> " . $formData['risk_tolerance'] . "</p>";
    
    $messageCarolyn .= "</body></html>";
    
    // Email headers for Carolyn
    $headersCarolyn = "From: " . $formData['email'] . "\r\n";
    $headersCarolyn .= "Reply-To: " . $formData['email'] . "\r\n";
    $headersCarolyn .= "MIME-Version: 1.0\r\n";
    $headersCarolyn .= "Content-Type: text/html; charset=UTF-8\r\n";
    
    // Send email to Carolyn
    $mailSentToCarolyn = mail($toCarolyn, $subjectCarolyn, $messageCarolyn, $headersCarolyn);
    
    if (!$mailSentToCarolyn) {
        throw new Exception('Failed to send notification email. Please try again later.');
    }

    // 2. Send welcome email to the user
    $toUser = $formData['email'];
    $subjectUser = "WELCOME TO CAROLYN'S COPYTRADING";
    
    // Build the welcome email message
    $messageUser = "
    <html>
    <head>
        <title>WELCOME TO CAROLYN'S COPYTRADING</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background-color: #3a86ff; color: white; padding: 20px; text-align: center; }
            .content { padding: 20px; background-color: #f9f9f9; }
            .footer { padding: 10px; text-align: center; font-size: 12px; color: #777; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>WELCOME TO CAROLYN'S COPYTRADING</h1>
            </div>
            <div class='content'>
                <p>Dear " . $formData['full_name'] . ",</p>
                <p>Thank you for completing our copy-trading setup form. We're excited to have you on board!</p>
                <p>Our team will review your information and contact you within 24 hours to help set up your copy-trading account.</p>
                <p>In the meantime, if you have any questions, please don't hesitate to reply to this email or contact our support team.</p>
                <p>Best regards,</p>
                <p><strong>Carolyn Greenwood Nelson</strong><br>
                Registered Broker with SEC and FINRA<br>
                CRD# 2081477</p>
            </div>
            <div class='footer'>
                <p>This email was sent to " . $formData['email'] . " as part of your copy-trading setup process.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    // Email headers for user
    $headersUser = "From: Carolyn Greenwood Nelson <carolyn.nelson@davidsonwealthteam.com>\r\n";
    $headersUser .= "Reply-To: carolyn.nelson@davidsonwealthteam.com\r\n";
    $headersUser .= "MIME-Version: 1.0\r\n";
    $headersUser .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headersUser .= "X-Mailer: PHP/" . phpversion();
    
    // Send welcome email to user
    $mailSentToUser = mail($toUser, $subjectUser, $messageUser, $headersUser);
    
    if (!$mailSentToUser) {
        error_log('Failed to send welcome email to: ' . $toUser);
        // Don't throw exception here as the form submission was still successful
    }

    // Prepare CSV data
    $startingAmount = $formData['experience_level'] === 'new' 
        ? $formData['starting_amount'] 
        : ($formData['has_investments'] === 'yes' ? 'Existing assets' : $formData['exp_starting_amount']);
    
    $csvData = [
        date('Y-m-d H:i:s'),
        $formData['full_name'],
        $formData['email'],
        $formData['phone'],
        $country,
        $formData['age_group'],
        $formData['experience_level'],
        $startingAmount,
        $formData['main_goal'],
        $formData['risk_tolerance']
    ];
    
    // Sanitize CSV data
    $csvData = array_map('sanitizeForCSV', $csvData);
    
    // Save to CSV file
    $csvFile = 'submissions.csv';
    if (!file_exists($csvFile)) {
        $headers = [
            'Timestamp', 'Name', 'Email', 'Phone', 'Country', 'Age Group', 
            'Experience Level', 'Starting Amount', 'Main Goal', 'Risk Tolerance'
        ];
        $headers = array_map('sanitizeForCSV', $headers);
        file_put_contents($csvFile, implode(',', $headers) . "\n");
        chmod($csvFile, 0666); // Make sure the file is writable
    }
    
    // Append data to CSV
    file_put_contents($csvFile, implode(',', $csvData) . "\n", FILE_APPEND);
    
    $response['success'] = true;
    $response['message'] = 'We are creating your investment portfolio. Please check your email inbox or spam for updates.';
    $response['redirect'] = 'https://www.davidsonwealthteam.com';
    
} catch (Exception $e) {
    error_log('Form submission error: ' . $e->getMessage());
    $response['message'] = $e->getMessage();
}

// Return JSON response
echo json_encode(['success' => true, 'redirect' => 'https://www.davidsonwealthteam.com/creating_portfolio.html']); 
exit;
?>