<?php
/**
 * WebSMS Connexus webhook receiver.
 *
 * One URL handles both incoming SMS replies (type=mo) and delivery reports
 * (type=dlr). Configure the URL in Members Area -> API Keys.
 *
 * Always respond 200 within 5s; failed webhooks are retried up to 3 times.
 */

$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!is_array($data) || !isset($data['type'])) {
    http_response_code(400);
    echo json_encode(['error' => 'invalid payload']);
    exit;
}

switch ($data['type']) {
    case 'mo':
        // Incoming SMS reply.
        // Example fields: messageId, from (E.164), to (your shortcode), body, timestamp, encoding, network
        $from = $data['from'] ?? '';
        $body = $data['body'] ?? '';
        error_log("[websms-mo] {$from} -> {$body}");
        // TODO: persist to your DB / dispatch to your business logic
        break;

    case 'dlr':
        // Delivery report.
        // statusCode 1=DELIVRD, 2=UNDELIV, 4=QUEUED/expired, 8=ACCEPTD, 16=UNDELIV/rejected
        $messageId = $data['messageId'] ?? '';
        $status    = $data['status']    ?? '';
        $code      = $data['statusCode'] ?? null;
        error_log("[websms-dlr] {$messageId} status={$status} code={$code}");
        // TODO: update the status of the original send in your DB
        break;

    default:
        // Unknown type - acknowledge so we don't get retried, but log it.
        error_log('[websms] unknown webhook type: ' . $data['type']);
}

http_response_code(200);
header('Content-Type: application/json');
echo json_encode(['ok' => true]);
