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

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Validate action parameter
$action = $_POST['action'] ?? '';
if (!in_array($action, ['setup_done', 'need_help'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

// Recipient email address
$to = 'carolyn.nelson@davidsonwealthteam.com';

// Email subject based on action
$subject = ($action === 'setup_done') 
    ? 'Account Setup Completed' 
    : 'Need Help with Account Setup';

// Client information
$clientName = 'Chwee Chian';
$advisor = 'Carolyn Greenwood Nelson';
$crd = '2081477';

// Email body
$body = "
<html>
<head>
    <title>$subject</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; }
        .info { margin-bottom: 15px; }
        .label { font-weight: bold; color: #555; }
        ul { padding-left: 20px; }
        li { margin-bottom: 5px; }
    </style>
</head>
<body>
    <h2>$subject</h2>
    
    <div class='info'>
        <span class='label'>Client Name:</span> $clientName
    </div>
    <div class='info'>
        <span class='label'>Advisor:</span> $advisor
    </div>
    <div class='info'>
        <span class='label'>CRD:</span> $crd
    </div>
    
    <p>The client has " . ($action === 'setup_done' ? 'successfully completed' : 'requested assistance with') . " setting up the trading accounts:</p>
    
    
    <p>Please follow up with the client as needed.</p>
    
    <p>This is an automated message. Do not reply directly to this email.</p>
</body>
</html>
";

// Email headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: account-setup@davidsonwealthteam.com\r\n";
$headers .= "Reply-To: no-reply@davidsonwealthteam.com\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();

// Send the email
$mailSent = mail($to, $subject, $body, $headers);

// Return response
if ($mailSent) {
    echo json_encode(['success' => true, 'message' => 'Email sent successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to send email']);
}
?>