<?php
declare(strict_types=1);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';

$db = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

/**
 * Mandatory fields (frontend)
 */
Validator::required($data, [
    'name',
    'phone',
    'product_purpose',
    'source_type'
]);

$name           = trim($data['name']);
$phone          = trim($data['phone']);
$productPurpose = $data['product_purpose'];
$sourceType     = $data['source_type'];

/**
 * Validate name
 */
Validator::minLength($name, 2, 'name');

/**
 * Validate phone (basic)
 */
if (!preg_match('/^[0-9]{10,15}$/', $phone)) {
    Response::error('Invalid phone number', 422);
}

/**
 * Product purpose validation
 */
if (!in_array($productPurpose, ['Home', 'Hotel'], true)) {
    Response::error('Invalid product purpose', 422);
}

/**
 * Source type validation
 */
$allowedSources = [
    'dealer',
    'blog',
    'faq',
    'page',
    'contact',
    'brochure',
    'sleep_id',
    'other'
];

if (!in_array($sourceType, $allowedSources, true)) {
    Response::error('Invalid source type', 422);
}

/**
 * Optional fields
 */
$email        = $data['email'] ?? null;
$city         = $data['city'] ?? null;
$state        = $data['state'] ?? null;
$pincode      = $data['pincode'] ?? null;
$message      = $data['message'] ?? null;

$sourceId     = $data['source_id'] ?? null;
$sourceSlug   = $data['source_slug'] ?? null;
$sourceUrl    = $data['source_url'] ?? null;
$referrerUrl = $_SERVER['HTTP_REFERER'] ?? null;

$utmSource   = $data['utm_source'] ?? null;
$utmMedium   = $data['utm_medium'] ?? null;
$utmCampaign = $data['utm_campaign'] ?? null;

/**
 * Optional email validation
 */
if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    Response::error('Invalid email address', 422);
}

/**
 * Capture system data
 */
$ipAddress = $_SERVER['REMOTE_ADDR'] ?? null;
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;

/**
 * Insert lead
 */
$stmt = $db->prepare("
    INSERT INTO leads (
        name,
        email,
        phone,
        pincode,
        city,
        state,
        message,
        product_purpose,
        source_type,
        source_id,
        source_slug,
        source_url,
        referrer_url,
        utm_source,
        utm_medium,
        utm_campaign,
        ip_address,
        user_agent,
        created_at
    ) VALUES (
        :name,
        :email,
        :phone,
        :pincode,
        :city,
        :state,
        :message,
        :product_purpose,
        :source_type,
        :source_id,
        :source_slug,
        :source_url,
        :referrer_url,
        :utm_source,
        :utm_medium,
        :utm_campaign,
        :ip_address,
        :user_agent,
        NOW()
    )
");

$stmt->execute([
    'name'            => $name,
    'email'           => $email,
    'phone'           => $phone,
    'pincode'         => $pincode,
    'city'            => $city,
    'state'           => $state,
    'message'         => $message,
    'product_purpose' => $productPurpose,
    'source_type'     => $sourceType,
    'source_id'       => $sourceId,
    'source_slug'     => $sourceSlug,
    'source_url'      => $sourceUrl,
    'referrer_url'    => $referrerUrl,
    'utm_source'      => $utmSource,
    'utm_medium'      => $utmMedium,
    'utm_campaign'    => $utmCampaign,
    'ip_address'      => $ipAddress,
    'user_agent'      => $userAgent
]);

Response::success('Lead submitted successfully');
