'Method not allowed'])); } // Get request body $body = file_get_contents('php://input'); // Always log to file first (this works) $logFile = __DIR__ . '/webhook_debug.log'; file_put_contents($logFile, date('Y-m-d H:i:s') . " - " . $body . " ", FILE_APPEND); // Try database, but don't fail if it doesn't work $dbSuccess = false; $dbError = null; $insertId = null; try { // Check if config exists $configPath = __DIR__ . '/config.php'; if (!file_exists($configPath)) { throw new Exception("config.php not found at: " . $configPath); } require_once $configPath; // Check if $pdo exists if (!isset($pdo)) { throw new Exception("PDO connection not established in config.php"); } // Parse Tiny Talk payload $data = json_decode($body, true); $eventType = $data['type'] ?? 'unknown'; $payload = $data['payload'] ?? []; // Extract fields $externalChatId = $payload['id'] ?? null; // Get customer name $firstName = $payload['name']['first'] ?? ''; $lastName = $payload['name']['last'] ?? ''; $customerName = trim($firstName . ' ' . $lastName); if (empty($customerName)) $customerName = 'Unknown'; // Get email and phone $customerEmail = $payload['email']['address'] ?? $payload['email']['pendingAddress'] ?? null; $customerPhone = $payload['phone']['number'] ?? null; // Parse the ISO date properly $createdAt = $payload['createdAt'] ?? null; if ($createdAt) { $createdAt = date('Y-m-d H:i:s', strtotime($createdAt)); } else { $createdAt = date('Y-m-d H:i:s'); } // Insert with all fields $stmt = $pdo->prepare("INSERT INTO chat_logs (external_chat_id, event_type, customer_name, customer_email, customer_phone, raw_payload, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)"); $stmt->execute([$externalChatId, $eventType, $customerName, $customerEmail, $customerPhone, $body, $createdAt]); $insertId = $pdo->lastInsertId(); $dbSuccess = true; } catch (Exception $e) { $dbError = $e->getMessage(); } // Always return 200 http_response_code(200); echo json_encode([ 'success' => true, 'logged_to_file' => true, 'db_success' => $dbSuccess, 'db_error' => $dbError, 'insert_id' => $insertId ]);