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

try {
    require_once 'db_connection.php';
    require_once '../files/guardiankey.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) {
        error_log("Error al decodificar JSON en leads-create.php: " . json_last_error_msg());
        throw new Exception('ERROR AL PROCESAR DATOS');
    }

    if (
        !isset($data['first_name']) || empty(trim($data['first_name'])) ||
        !isset($data['last_name']) || empty(trim($data['last_name'])) ||
        (empty(trim($data['email'] ?? '')) && empty(trim($data['phone'] ?? '')) && empty(trim($data['mobile'] ?? '')))
    ) {
        throw new Exception('DATOS OBLIGATORIOS FALTANTES');
    }

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

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

    if ($stmt_check_leads->fetch(PDO::FETCH_ASSOC)) {
        $response['message'] = 'DUPLICADO: EMAIL O TELEFONO EN PROSPECTOS';
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode($response);
        exit;
    }

    $stmt_check_clients = $pdo->prepare("
        SELECT id FROM clients
        WHERE (email IS NOT NULL AND email != '' AND email = :email_check_clients)
           OR (phone IS NOT NULL AND phone != '' AND phone = :phone_check_clients)
           OR (mobile IS NOT NULL AND mobile != '' AND mobile = :mobile_check_clients)
        LIMIT 1
    ");
    $stmt_check_clients->bindValue(':email_check_clients', $email, $email === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_clients->bindValue(':phone_check_clients', $phone, $phone === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_clients->bindValue(':mobile_check_clients', $mobile, $mobile === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_clients->execute();

    if ($stmt_check_clients->fetch(PDO::FETCH_ASSOC)) {
        $response['message'] = 'DUPLICADO: EMAIL O TELEFONO EN CLIENTES';
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode($response);
        exit;
    }

    $stmt = $pdo->prepare("
        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 (:first_name, :last_name, :company, :email, :phone, :mobile, :source, :status, :priority, :street_address, :city, :state_province, :zip_code, NOW(), NOW())
    ");

    $stmt->bindParam(':first_name', $first_name, PDO::PARAM_STR);
    $stmt->bindParam(':last_name', $last_name, PDO::PARAM_STR);
    $stmt->bindParam(':company', $company, $company === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':email', $email, $email === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':phone', $phone, $phone === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':mobile', $mobile, $mobile === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':source', $source, PDO::PARAM_STR);
    $stmt->bindParam(':status', $status, PDO::PARAM_STR);
    $stmt->bindParam(':priority', $priority, PDO::PARAM_STR);
    $stmt->bindParam(':street_address', $street_address, $street_address === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':city', $city, $city === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':state_province', $state_province, $state_province === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':zip_code', $zip_code, $zip_code === null ? PDO::PARAM_NULL : PDO::PARAM_STR);

    if ($stmt->execute()) {
        $response['success'] = true;
        $response['message'] = 'PROSPECTO CREADO';
        $lead_id = $pdo->lastInsertId();

        $response['prospect'] = [
            'id' => (string)$lead_id,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'nombre_completo' => $first_name . ' ' . $last_name,
            'empresa' => $company, 
            'email' => $email,
            'phone' => $phone,
            'mobile' => $mobile,
            'fuente' => $source, 
            'estado' => $status, 
            'prioridad' => $priority, 
            'direccion_calle' => $street_address, 
            'ciudad' => $city, 
            'state_province' => $state_province, 
            'zip_code' => $zip_code, 
            'created_at' => date('Y-m-d H:i:s')
        ];

    } else {
        error_log("Error PDO al insertar en leads en leads-create.php: " . implode(" ", $stmt->errorInfo()));
        $response['message'] = 'ERROR AL INSERTAR PROSPECTO';
    }

} catch (PDOException $e) {
    error_log("PDOException en leads-create.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("General Error en leads-create.php: " . $e->getMessage());
    $response['message'] = 'ERROR CRITICO';
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>