<?php 
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    require_once __DIR__ . '/../core/api.php';
    
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

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

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('JSON INVALIDO RECIBIDO');
    }

    if (empty($data['first_name']) || empty($data['last_name'])) {
        throw new Exception('Nombre y Apellido son obligatorios.');
    }

    $first_name = trim($data['first_name']);
    $last_name = trim($data['last_name']);
    $company = !empty($data['company']) ? trim($data['company']) : null;
    $email = !empty($data['email']) ? filter_var(trim($data['email']), FILTER_SANITIZE_EMAIL) : null;
    
    $phone = !empty($data['phone']) ? preg_replace('/[^0-9]/', '', $data['phone']) : null;
    $mobile = !empty($data['mobile']) ? preg_replace('/[^0-9]/', '', $data['mobile']) : null;
    
    $source = $data['source'] ?? 'Desconocida';
    $status = $data['status'] ?? 'New';
    $priority = $data['priority'] ?? 'Medium';
    
    $street_address = !empty($data['street_address']) ? trim($data['street_address']) : null;
    $city = !empty($data['city']) ? trim($data['city']) : null;
    $state_province = !empty($data['state_province']) ? trim($data['state_province']) : null;
    $zip_code = !empty($data['zip_code']) ? trim($data['zip_code']) : null;

    $sql_check = "SELECT id FROM leads WHERE 
        (email IS NOT NULL AND email != '' AND email = :email) OR 
        (phone IS NOT NULL AND phone != '' AND phone = :phone) OR 
        (mobile IS NOT NULL AND mobile != '' AND mobile = :mobile) 
        LIMIT 1";
    
    $stmt = $pdo->prepare($sql_check);
    $stmt->bindValue(':email', $email, $email ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':phone', $phone, $phone ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':mobile', $mobile, $mobile ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->execute();

    if ($stmt->fetch()) {
        throw new Exception('DUPLICADO: El prospecto ya existe (Email o Teléfono coinciden).');
    }

    if ($email) {
        try {
            $sql_client = "SELECT id FROM clients WHERE email = :email LIMIT 1";
            $stmtC = $pdo->prepare($sql_client);
            $stmtC->bindValue(':email', $email);
            $stmtC->execute();

            if ($stmtC->fetch()) {
                 throw new Exception('DUPLICADO: Este contacto ya es un CLIENTE activo.');
            }
        } catch (PDOException $e) {
            error_log("Advertencia checking clients: " . $e->getMessage());
        }
    }

    $sql_insert = "INSERT INTO leads (
        first_name, last_name, company, email, phone, mobile, source, status, priority, 
        street_address, city, state_province, zip_code, created_at, updated_at
    ) VALUES (
        :fn, :ln, :co, :em, :ph, :mo, :so, :st, :pr, 
        :addr, :ci, :state, :zip, NOW(), NOW()
    )";

    $stmt = $pdo->prepare($sql_insert);
    $stmt->bindValue(':fn', $first_name);
    $stmt->bindValue(':ln', $last_name);
    $stmt->bindValue(':co', $company, $company ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':em', $email, $email ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':ph', $phone, $phone ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':mo', $mobile, $mobile ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':so', $source);
    $stmt->bindValue(':st', $status);
    $stmt->bindValue(':pr', $priority);
    $stmt->bindValue(':addr', $street_address, $street_address ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':ci', $city, $city ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':state', $state_province, $state_province ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':zip', $zip_code, $zip_code ? PDO::PARAM_STR : PDO::PARAM_NULL);

    if ($stmt->execute()) {
        $response['success'] = true;
        $response['message'] = 'PROSPECTO CREADO CORRECTAMENTE';
        $response['id'] = $pdo->lastInsertId();
    } else {
        throw new Exception('Error SQL al insertar.');
    }

} catch (Exception $e) {
    error_log("Error en leads-create: " . $e->getMessage());
    $response['message'] = $e->getMessage();
}

if (ob_get_length()) ob_clean();
echo json_encode($response);
exit;
?>