<?php
require_once __DIR__ . '/../config/config.php';

$id = $argv[1] ?? null;
if (!$id) { echo "Usage: php debug_process_message.php <webhook_log_id>\n"; exit; }
$db = Database::getInstance();
$row = $db->fetch('SELECT request_body FROM webhook_logs WHERE id = ?', [$id]);
if (!$row) { echo "Log not found\n"; exit; }
$data = json_decode($row['request_body'], true);
$messages = $data['entry'][0]['changes'][0]['value']['messages'] ?? null;
if (!$messages) { echo "No messages in log\n"; exit; }
foreach ($messages as $message) {
    echo "--- Message ---\n";
    print_r($message);
    $phoneNumber = $message['from'] ?? ($message['wa_id'] ?? null);
    $messageId = $message['id'] ?? ($message['message_id'] ?? null);
    $timestamp = $message['timestamp'] ?? null;
    echo "phone=$phoneNumber messageId=$messageId ts=$timestamp\n";

    if (empty($phoneNumber) || empty($messageId)) { echo "Missing phone or msg id\n"; continue; }

    $existing = $db->fetch('SELECT id FROM conversations WHERE message_id = ?', [$messageId]);
    echo "existing: "; var_export((bool)$existing); echo "\n";

    $user = $db->fetch('SELECT * FROM users WHERE phone_number = ?', [$phoneNumber]);
    if (!$user) { echo "User not found, creating...\n"; $id = $db->insert('users', ['phone_number' => $phoneNumber, 'status' => 'active', 'created_at' => date('Y-m-d H:i:s')]); $user = $db->fetch('SELECT * FROM users WHERE id = ?', [$id]); }
    echo "user id: " . $user['id'] . "\n";

    $messageText = '';
    $messageType = 'text';
    $mediaUrl = null; $mimeType = null; $filename = null;
    if (isset($message['text']) || (($message['type'] ?? '') === 'text')) {
        $messageText = isset($message['text']['body']) ? $message['text']['body'] : ($message['body'] ?? '');
        $messageType = 'text';
    } elseif (isset($message['image'])) {
        $messageText = $message['image']['caption'] ?? '';
        $messageType = 'image';
        $mediaUrl = $message['image']['url'] ?? ($message['image']['id'] ?? null);
        $mimeType = $message['image']['mime_type'] ?? null;
        $filename = $message['image']['filename'] ?? null;
    }
    echo "type=$messageType text=" . substr($messageText,0,100) . " mediaUrl=" . ($mediaUrl ?? 'NULL') . "\n";

    $saveData = [
        'user_id' => $user['id'],
        'message_id' => $messageId,
        'direction' => 'incoming',
        'message_type' => $messageType,
        'content' => $messageText,
        'media_url' => $mediaUrl,
        'filename' => $filename,
        'mime_type' => $mimeType,
        'status' => 'received',
        'is_read' => 0,
        'created_at' => date('Y-m-d H:i:s')
    ];

    try {
        $res = $db->insert('conversations', $saveData);
        echo "Insert returned: "; var_export($res); echo "\n";
    } catch (Exception $e) {
        echo "Insert failed: " . $e->getMessage() . "\n";
    }
}
