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

// Validate and sanitize input data
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

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

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']) ? $_POST['exp_asset_name'] : [],
        'exp_asset_amount' => isset($_POST['exp_asset_amount']) ? $_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.');
    }

    // Prepare email content
    $to = 'carolyn.nelson@davidsonwealthteam.com';
    $subject = 'New Copy-Trading Setup Submission';
    
    // Build the email message
    $message = "<html><body>";
    $message .= "<h2>Copy-Trading Setup Questionnaire Submission</h2>";
    $message .= "<p><strong>Submitted:</strong> " . date('Y-m-d H:i:s') . "</p>";
    
    $message .= "<h3>Personal Information</h3>";
    $message .= "<p><strong>Name:</strong> " . $formData['full_name'] . "</p>";
    $message .= "<p><strong>Email:</strong> " . $formData['email'] . "</p>";
    $message .= "<p><strong>Phone:</strong> " . $formData['phone'] . "</p>";
    
    $country = $formData['country'] === 'other' ? $formData['other_country'] : $formData['country'];
    $message .= "<p><strong>Country:</strong> " . $country . "</p>";
    $message .= "<p><strong>Age Group:</strong> " . $formData['age_group'] . "</p>";
    
    $message .= "<h3>Trading Profile</h3>";
    $message .= "<p><strong>Experience Level:</strong> " . ($formData['experience_level'] === 'new' ? 'New to trading' : 'Experienced trader') . "</p>";
    
    if ($formData['experience_level'] === 'new') {
        $message .= "<h4>New Trader Details</h4>";
        $message .= "<p><strong>Starting Amount:</strong> $" . number_format($formData['starting_amount'], 2) . "</p>";
        $message .= "<p><strong>Source of Funds:</strong> " . $formData['new_funds_source'] . "</p>";
    } else {
        $message .= "<h4>Experienced Trader Details</h4>";
        $message .= "<p><strong>Investment Platforms:</strong> " . $formData['investment_platforms'] . "</p>";
        $message .= "<p><strong>Has Existing Investments:</strong> " . ($formData['has_investments'] === 'yes' ? 'Yes' : 'No') . "</p>";
        
        if ($formData['has_investments'] === 'yes') {
            $message .= "<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);
                    $message .= "<li>{$assetName}: $" . $amount . "</li>";
                }
            }
            $message .= "</ul>";
        } else {
            $message .= "<p><strong>Starting Amount:</strong> $" . number_format($formData['exp_starting_amount'], 2) . "</p>";
        }
        
        $message .= "<p><strong>Source of Funds:</strong> " . $formData['exp_funds_source'] . "</p>";
        $message .= "<p><strong>Trading Background:</strong> " . $formData['trading_background'] . "</p>";
        $message .= "<p><strong>Important Trading Features:</strong> " . $formData['trading_features'] . "</p>";
        $message .= "<p><strong>Desired Trading Effects:</strong> " . $formData['trading_effects'] . "</p>";
    }
    
    $message .= "<h3>Trading Preferences</h3>";
    $message .= "<p><strong>Main Goal:</strong> " . $formData['main_goal'] . "</p>";
    $message .= "<p><strong>Trading Involvement:</strong> " . $formData['trading_involvement'] . "</p>";
    $message .= "<p><strong>Portfolio Reaction to 15% Decline:</strong> " . $formData['portfolio_reaction'] . "</p>";
    $message .= "<p><strong>Expected Return Target:</strong> " . $formData['expected_return'] . "% " . $formData['return_period'] . "</p>";
    $message .= "<p><strong>Risk Tolerance:</strong> " . $formData['risk_tolerance'] . "</p>";
    
    $message .= "</body></html>";
    
    // Email headers
    $headers = "From: " . $formData['email'] . "\r\n";
    $headers .= "Reply-To: " . $formData['email'] . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    
    // Send email
    $mailSent = mail($to, $subject, $message, $headers);
    
    if (!$mailSent) {
        throw new Exception('Failed to send email. Please try again later.');
    }
    
    // Also save to a CSV file for backup
    $csvData = [
        date('Y-m-d H:i:s'),
        $formData['full_name'],
        $formData['email'],
        $formData['phone'],
        $country,
        $formData['age_group'],
        $formData['experience_level'],
        $formData['experience_level'] === 'new' ? $formData['starting_amount'] : ($formData['has_investments'] === 'yes' ? 'Existing assets' : $formData['exp_starting_amount']),
        $formData['main_goal'],
        $formData['risk_tolerance']
    ];
    
    $csvFile = 'submissions.csv';
    if (!file_exists($csvFile)) {
        $headers = [
            'Timestamp', 'Name', 'Email', 'Phone', 'Country', 'Age Group', 
            'Experience Level', 'Starting Amount', 'Main Goal', 'Risk Tolerance'
        ];
        file_put_contents($csvFile, implode(',', $headers) . "\n");
    }
    file_put_contents($csvFile, implode(',', $csvData) . "\n", FILE_APPEND);
    
    $response['success'] = true;
    $response['message'] = 'Thank you for your submission! We will contact you shortly.';
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

// Return JSON response
echo json_encode($response);
?>