<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NotificationController extends Controller
{
    /**
     * Twilio WhatsApp delivery status webhook.
     * Accepts typical fields like MessageSid, MessageStatus, To, From, ErrorCode.
     */
    public function whatsappStatus(Request $request)
    {
        $sid = $request->input('MessageSid') ?? $request->input('SmsSid');
        $status = $request->input('MessageStatus') ?? $request->input('SmsStatus');
        $to = $request->input('To');
        $from = $request->input('From');
        $errorCode = $request->input('ErrorCode');

        if (!$sid) {
            return response()->json(['ok' => true]);
        }

        DB::table('messages')->updateOrInsert(
            ['twilio_sid' => $sid],
            [
                'direction' => 'outbound',
                'channel' => 'whatsapp',
                'to_number' => $to,
                'status' => $status ?? 'unknown',
                'payload' => json_encode($request->all()),
                'updated_at' => now(),
                'created_at' => now(),
            ]
        );

        return response()->json(['ok' => true]);
    }
}
