<?php
require_once __DIR__ . '/../config/config_enhanced.php';
require_once __DIR__ . '/../classes/Database.php';

$file = __DIR__ . '/webhook_payload_ABGGFlA5Fpa.json';
if (!file_exists($file)) { echo "Payload not found\n"; exit(1); }
$payload = json_decode(file_get_contents($file), true);
if (!$payload) { echo "Invalid JSON\n"; exit(1); }

try {
    $db = Database::getInstance();
    foreach ($payload['entry'] as $entry) {
        foreach ($entry['changes'] as $change) {
            $val = $change['value'];
            if (!empty($val['conversations'])) {
                foreach ($val['conversations'] as $message) {
                    $phone = $message['from'];
                    $mid = $message['id'];
                    $text = $message['text']['body'] ?? '';
                    // Check user
                    $user = $db->fetch('SELECT id FROM users WHERE phone_number = ?', [$phone]);
                    if (!$user) {
                        echo "User not found, creating: $phone\n";
                        $db->insert('users', ['phone_number' => $phone, 'status' => 'active', 'created_at' => date('Y-m-d H:i:s')]);
                        $userId = $db->lastInsertId();
                        echo "Created user id: $userId\n";
                    } else {
                        $userId = $user['id'];
                        echo "User exists id: $userId\n";
                    }

                    // Attempt insert
                    echo "Attempting insert message_id: $mid\n";
                    $msg = [
                        'user_id' => $userId,
                        'message_id' => $mid,
                        'direction' => 'incoming',
                        'message_type' => 'text',
                        'content' => $text,
                        'media_url' => null,
                        'status' => 'received',
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    try {
                        // Manual insert using PDO to capture detailed errors
                        $pdo = $db->getConnection();
                        $keys = array_keys($msg);
                        $fields = implode(', ', $keys);
                        $placeholders = ':' . implode(', :', $keys);
                        $sql = "INSERT INTO conversations ({$fields}) VALUES ({$placeholders})";
                        $stmt = $pdo->prepare($sql);
                        echo "Prepared SQL\n";
                        $res = $stmt->execute($msg);
                        echo "Executed: " . ($res ? 'true' : 'false') . "\n";
                        $err = $stmt->errorInfo();
                        echo "Stmt errorInfo: " . json_encode($err) . "\n";
                        $lastId = $pdo->lastInsertId();
                        echo "Inserted conversation id (manual): $lastId\n";
                    } catch (Exception $e) {
                        echo "INSERT EXCEPTION: " . $e->getMessage() . PHP_EOL;
                    }
                }
            }
        }
    }
} catch (Exception $e) {
    echo "EXCEPTION: " . $e->getMessage() . PHP_EOL;
}
