<?php
// Set headers for JSON response
header('Content-Type: application/json');

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

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request method';
    echo json_encode($response);
    exit;
}

// Get and sanitize form data
$name = isset($_POST['name']) ? trim(htmlspecialchars($_POST['name'])) : '';
$email = isset($_POST['email']) ? trim(htmlspecialchars($_POST['email'])) : '';
$country = isset($_POST['country']) ? trim(htmlspecialchars($_POST['country'])) : '';
$experience = isset($_POST['experience']) ? trim(htmlspecialchars($_POST['experience'])) : '';

// Validate inputs
if (empty($name)) {
    $response['errors']['name'] = 'Name is required';
}

if (empty($email)) {
    $response['errors']['email'] = 'Email is required';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $response['errors']['email'] = 'Invalid email format';
}

if (empty($country)) {
    $response['errors']['country'] = 'Country is required';
}

// If there are validation errors
if (!empty($response['errors'])) {
    $response['message'] = 'Please correct the errors in the form';
    echo json_encode($response);
    exit;
}

// Send email to carolyn.nelson@davidsonwealthteam.com
$to = "carolyn.nelson@davidsonwealthteam.com";
$subject = "New Portfolio Request from $name";
$message = "
<html>
<head>
    <title>New Portfolio Request</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; }
        .header { color: #4CAF50; font-size: 18px; font-weight: bold; }
        .label { font-weight: bold; width: 120px; display: inline-block; }
    </style>
</head>
<body>
    <h2 class='header'>New Portfolio Request</h2>
    <p><span class='label'>Name:</span> $name</p>
    <p><span class='label'>Email:</span> $email</p>
    <p><span class='label'>Country:</span> $country</p>
    <p><span class='label'>Experience:</span><br>".nl2br($experience)."</p>
    <p>Received: ".date('Y-m-d H:i:s')."</p>
</body>
</html>
";

// Email headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: Portfolio Widget <noreply@yourdomain.com>" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";

// Attempt to send email
if (mail($to, $subject, $message, $headers)) {
    echo json_encode('Thank you! Your request has been successfully submitted. Please keep an eye on your inbox for follow-up emails.');
} else {
    echo json_encode('There was an error sending your request. Please try again later.');
}
?>