<?php
require_once __DIR__ . '/../includes/api-helpers.php';
api_require_post();
if (api_is_spam()) api_json(true, 'Thank you! We will be in touch shortly.');

$name = api_str('name', 120);
$email = api_str('email', 160);
$phone = api_str('phone', 40);
$subject = api_str('subject', 200);
$message = api_str('message', 2000);
$serviceInterest = api_str('service_interest', 100);
$preferredContact = api_str('preferred_contact', 40);
$preferredVisitDate = api_str('preferred_visit_date', 20);
$ctaType = api_str('cta_type', 60) ?: 'General Enquiry';
$propertyId = !empty($_POST['property_id']) ? (int)$_POST['property_id'] : null;

if ($name === '' || !api_valid_email($email) || $phone === '' || $message === '') {
    api_json(false, 'Please fill in your name, phone number, a valid email and a message.');
}

$parts = [];
if ($subject !== '') $parts[] = "[$subject]";
$parts[] = "Request type: $ctaType.";
if ($serviceInterest !== '') $parts[] = "Service interested in: $serviceInterest.";
if ($preferredContact !== '') $parts[] = "Preferred contact method: $preferredContact.";
if ($preferredVisitDate !== '') $parts[] = "Preferred visit date: $preferredVisitDate.";
$parts[] = $message;
$fullMessage = implode(' ', $parts);

$date = null;
if ($preferredVisitDate !== '') {
    $ts = strtotime($preferredVisitDate);
    if ($ts) $date = date('Y-m-d', $ts);
}

$stmt = db()->prepare('INSERT INTO leads (type, property_id, name, email, phone, message, preferred_date) VALUES (?, ?, ?, ?, ?, ?, ?)');
$stmt->execute(['contact', $propertyId, $name, $email, $phone, $fullMessage, $date]);

api_json(true, 'Thank you! Your request has been received — we will respond within one business day.');
