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

// Collect and sanitize input data
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
$action = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING);

// Validate inputs
if (empty($name) || empty($email) || empty($action)) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

// Email configuration
$to = 'carolyn.nelson@davidsonwealthteam.com';
$subject = 'Asset Conversion Portal - ' . ($action === 'conversion_done' ? 'Completion' : 'Help Request');
$headers = [
    'From' => $email,
    'Reply-To' => $email,
    'X-Mailer' => 'PHP/' . phpversion(),
    'Content-type' => 'text/plain; charset=utf-8'
];

// Build email body
$email_body = "Client Name: $name\n";
$email_body .= "Client Email: $email\n";
$email_body .= "Action Type: " . ($action === 'conversion_done' ? 'Conversion Completed' : 'Help Requested') . "\n\n";
$email_body .= "Message:\n$message\n\n";
$email_body .= "Submitted: " . date('Y-m-d H:i:s');

// Convert headers to string format
$headers_string = '';
foreach ($headers as $key => $value) {
    $headers_string .= "$key: $value\r\n";
}

// Send email
$mail_sent = mail($to, $subject, $email_body, $headers_string);

if ($mail_sent) {
    echo json_encode([
        'success' => true,
        'message' => 'Thank you! Your response has been sent to your Financial Advisor.'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to send email. Please try again later.'
    ]);
}
?>