<?php
/**
 * Arrow funnel — "I want this site / I want hosting" lead capture.
 * Reliably appends every lead to data/leads.json (atomic) regardless of email
 * outcome, then attempts a best-effort notify to ARROW_LEAD_EMAIL.
 */
require_once __DIR__ . '/lib.php';

header('Content-Type: application/json; charset=UTF-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['ok' => false]); exit; }

$name    = trim($_POST['name']    ?? '');
$email   = trim($_POST['email']   ?? '');
$phone   = trim($_POST['phone']   ?? '');
$message = trim($_POST['message'] ?? '');
$want    = trim($_POST['want']    ?? ''); // "site" | "hosting" | "both"

if ($name === '' || ($email === '' && $phone === '')) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Name and a way to reach you are required.']);
    exit;
}
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'That email address looks off.']);
    exit;
}

/* ---- 1. ALWAYS capture the lead server-side (atomic append) ---- */
$lead = [
    'ts'      => date('c'),
    'name'    => arrow_trunc($name, 200),
    'email'   => arrow_trunc($email, 200),
    'phone'   => arrow_trunc($phone, 60),
    'want'    => arrow_trunc($want, 40),
    'message' => arrow_trunc($message, 4000),
    'ip'      => $_SERVER['REMOTE_ADDR'] ?? '',
    'ua'      => arrow_trunc($_SERVER['HTTP_USER_AGENT'] ?? '', 300),
];
$file  = arrow_data_path('leads.json');
$leads = arrow_read_json($file, []);
$leads[] = $lead;
$saved = arrow_write_json($file, $leads);

/* ---- 2. Best-effort email notify (never blocks the capture) ---- */
$sent = false;
$to      = ARROW_LEAD_EMAIL;
$subject = 'New Arrow lead: ' . $name . ($want ? ' (' . $want . ')' : '');
$body    = "New lead from the Arrow funnel\n"
         . "-----------------------------------\n"
         . "Name:    {$name}\n"
         . "Email:   {$email}\n"
         . "Phone:   {$phone}\n"
         . "Wants:   {$want}\n"
         . "When:    {$lead['ts']}\n\n"
         . "Message:\n{$message}\n";
$headers = 'From: ' . ARROW_MAIL_FROM . "\r\n"
         . ($email ? 'Reply-To: ' . $email . "\r\n" : '')
         . "Content-Type: text/plain; charset=UTF-8\r\n";
if (function_exists('mail')) {
    $sent = @mail($to, $subject, $body, $headers);
}

echo json_encode(['ok' => (bool)$saved, 'emailed' => (bool)$sent]);
