<?php
require_once __DIR__ . '/../includes/api-helpers.php';
api_require_post();
if (api_is_spam()) api_json(true, 'Thank you! Your tour has been requested.');

$name = api_str('name', 120);
$email = api_str('email', 160);
$phone = api_str('phone', 40);
$preferredDate = api_str('preferred_date', 20);
$propertyId = !empty($_POST['property_id']) ? (int)$_POST['property_id'] : null;
$notes = api_str('notes', 1000);

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

$date = null;
if ($preferredDate !== '') {
    $ts = strtotime($preferredDate);
    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(['tour', $propertyId, $name, $email, $phone, $notes, $date]);

api_json(true, 'Thank you! We will confirm your tour time shortly by phone or email.');
