<?php
require __DIR__ . "/config/config.php";

// Read input
$input = file_get_contents("php://input");
$data = json_decode($input, true);

// Log raw webhook (for debugging)
file_put_contents("webhook_log.txt", date("Y-m-d H:i:s") . " - " . $input . PHP_EOL, FILE_APPEND);

// Check message
if (!empty($data['entry'][0]['changes'][0]['value']['messages'][0])) {

    $msg = $data['entry'][0]['changes'][0]['value']['messages'][0];
    $from = $msg['from'];
    $message_id = $msg['id'];
    $timestamp = $msg['timestamp'];
    $text = "";

    if ($msg['type'] === "text") {
        $text = $msg['text']['body'];
    } else {
        $text = "[Non-text message]";
    }

    // Save to database
    $stmt = $conn->prepare("
        INSERT INTO messages (wa_id, direction, message, message_id)
        VALUES (?, 'in', ?, ?)
    ");
    $stmt->bind_param("sss", $from, $text, $message_id);
    $stmt->execute();
    $stmt->close();
}

// Required response
http_response_code(200);
echo "EVENT_RECEIVED";