prepare("SELECT * FROM leads WHERE company = ?"); // Using company to store phone number for simplicity $stmt->execute([$phone_number]); $lead = $stmt->fetch(); if (!$lead) { // Create new lead $stmt = $pdo->prepare("INSERT INTO leads (name, company, status) VALUES (?, ?, 'New')"); $stmt->execute([$name, $phone_number]); $lead_id = $pdo->lastInsertId(); } else { $lead_id = $lead['id']; } // Save the message $stmt = $pdo->prepare("INSERT INTO messages (lead_id, sender, message) VALUES (?, 'user', ?)"); $stmt->execute([$lead_id, $message_body]); } catch (PDOException $e) { // Log errors file_put_contents('webhook_error_log.txt', $e->getMessage() . "\n", FILE_APPEND); } }