<?php
include_once '../db/db_connection.php';
include_once '../files/GuardianKey.php';

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_encode(['success' => false, 'message' => 'Invalid JSON input.']);
    exit;
}

// No recuperamos 'id' del input porque será AUTO_INCREMENT
$first_name = $input['first_name'] ?? null;
$last_name = $input['last_name'] ?? null;
$company = $input['company'] ?? null;
$email = $input['email'] ?? null;
$phone = $input['phone'] ?? null;
$mobile = $input['mobile'] ?? null;
$source = $input['source'] ?? null;
$status = $input['status'] ?? 'Nuevo'; // Default status
$street_address = $input['street_address'] ?? null;
$city = $input['city'] ?? null;
$state_province = $input['state_province'] ?? null;
$zip_code = $input['zip_code'] ?? null;

if (!$first_name || !$last_name || !$email) {
    echo json_encode(['success' => false, 'message' => 'First name, last name, and email are required.']);
    exit;
}

try {
    $pdo->beginTransaction();

    // MODIFICADO: No incluimos 'id' en la lista de columnas para que la DB lo genere automáticamente.
    // Y ajustamos el orden y número de placeholders.
    $stmt = $pdo->prepare("INSERT INTO leads (first_name, last_name, company, email, phone, mobile, source, status, street_address, city, state_province, zip_code, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmt->execute([$first_name, $last_name, $company, $email, $phone, $mobile, $source, $status, $street_address, $city, $state_province, $zip_code]);

    $newProspectId = $pdo->lastInsertId(); // Obtener el ID generado automáticamente

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Prospect added successfully.',
        'prospect' => [
            'id' => $newProspectId, // Devolvemos el ID numérico
            'first_name' => $first_name,
            'last_name' => $last_name,
            'company' => $company,
            'email' => $email,
            'phone' => $phone,
            'mobile' => $mobile,
            'source' => $source,
            'status' => $status,
            'street_address' => $street_address,
            'city' => $city,
            'state_province' => $state_province,
            'zip_code' => $zip_code,
            'created_at' => date('Y-m-d H:i:s') // O obtener de la DB si es necesario
        ]
    ]);

} catch (PDOException $e) {
    $pdo->rollBack();
    error_log("Error creating prospect: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>