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

$sid = $_POST['MessageSid'] ?? null;
$st = $_POST['MessageStatus'] ?? null;

if ($sid && $st) {
  try {
    $map = [
      'queued' => 'queued',
      'accepted' => 'queued',
      'scheduled' => 'queued',
      'sending' => 'queued',
      'sent' => 'sent',
      'delivered' => 'sent',
      'read' => 'sent',
      'undelivered' => 'failed',
      'failed' => 'failed',
      'canceled' => 'failed'
    ];
    $mapped = $map[strtolower($st)] ?? null;

    if ($mapped) {
      $dbF->setRow("UPDATE wa_queue SET status = ?, twilio_sid = COALESCE(twilio_sid, ?) WHERE twilio_sid = ?", [$mapped, $sid, $sid]);

      $dbF->setRow("UPDATE whatsapp_messages SET status = ? WHERE twilio_sid = ?", [$mapped, $sid]);
    }

    $row = $dbF->getRow("SELECT id FROM wa_queue WHERE twilio_sid = ? ORDER BY id DESC LIMIT 1", [$sid]);
    if (!empty($row) && isset($row['id'])) {
      $dbF->setRow("INSERT INTO wa_audit (queue_id, event, payload) VALUES (?, ?, ?)", [$row['id'], $st, json_encode($_POST)]);
    }

  } catch (Exception $e) {
    // swallow
  }
}

http_response_code(204);