<?php
require_once __DIR__ . '/_helpers.php';
require_post();

$f = [
    'firstName'      => clean($_POST['firstName']      ?? '', 80),
    'lastName'       => clean($_POST['lastName']       ?? '', 80),
    'email'          => clean_email($_POST['email']    ?? ''),
    'phone'          => clean($_POST['phone']          ?? '', 40),
    'address'        => clean($_POST['address']        ?? '', 255),
    'city'           => clean($_POST['city']           ?? '', 100),
    'state'          => clean($_POST['state']          ?? '', 60),
    'zip'            => clean($_POST['zip']            ?? '', 20),
    'patientName'    => clean($_POST['patientName']    ?? '', 120),
    'relationship'   => clean($_POST['relationship']   ?? '', 80),
    'preferredDate'  => clean($_POST['preferredDate']  ?? '', 40),
    'preferredTime'  => clean($_POST['preferredTime']  ?? '', 60),
    'insurance'      => clean($_POST['insurance']      ?? '', 120),
    'notes'          => clean($_POST['notes']          ?? '', 5000),
];
$services = $_POST['servicesNeeded'] ?? [];
if (!is_array($services)) $services = [];
$services = array_map(function ($s) { return clean($s, 120); }, $services);
$token = $_POST['g-recaptcha-response'] ?? '';

if (!$f['firstName'] || !$f['lastName'] || !$f['email'] || !$f['phone']) {
    send_json(400, ['ok' => false, 'error' => 'Please fill in all required fields.']);
}
if (!verify_recaptcha($token)) {
    send_json(400, ['ok' => false, 'error' => 'reCAPTCHA verification failed. Please try again.']);
}

$subject = "Assessment Request — {$f['firstName']} {$f['lastName']}";
$body  = "— CONTACT —\n";
$body .= "Name:     {$f['firstName']} {$f['lastName']}\n";
$body .= "Email:    {$f['email']}\n";
$body .= "Phone:    {$f['phone']}\n";
$body .= "Address:  {$f['address']}\n";
$body .= "City/ST/Zip: {$f['city']}, {$f['state']} {$f['zip']}\n\n";
$body .= "— PATIENT —\n";
$body .= "Patient Name:  {$f['patientName']}\n";
$body .= "Relationship:  {$f['relationship']}\n\n";
$body .= "— APPOINTMENT —\n";
$body .= "Preferred Date: {$f['preferredDate']}\n";
$body .= "Preferred Time: {$f['preferredTime']}\n";
$body .= "Insurance:      {$f['insurance']}\n";
$body .= "Services:       " . (count($services) ? implode(', ', $services) : '—') . "\n\n";
$body .= "— NOTES —\n{$f['notes']}\n";

if (!send_email($subject, $body)) {
    send_json(500, ['ok' => false, 'error' => 'Server could not send email. Please try again later.']);
}

send_json(200, ['ok' => true]);
