<?php

namespace App\Http\Controllers;

use App\Models\SmsLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class SmsWebhookController extends Controller
{
    /**
     * Handle smsapi.si delivery reports (GET) and replies (POST).
     * This endpoint accepts both methods as the provider may use either.
     */
    public function __invoke(Request $request)
    {
        // Delivery report via GET: id (int) and status (string)
        if ($request->query->has('id')) {
            $providerId = (string) ((int) $request->query('id'));
            $status = trim(strip_tags((string) $request->query('status', '')));

            $log = SmsLog::query()->where('provider_message_id', $providerId)->first();
            if ($log) {
                $meta = (array) $log->meta;
                $meta['delivery_report'] = [
                    'raw_status' => $status,
                    'received_at' => now()->toIso8601String(),
                ];

                // Naive mapping: mark delivered for common success statuses
                $normalized = strtoupper($status);
                if (in_array($normalized, ['DELIVERED', 'DELIVRD', 'OK'], true)) {
                    $log->status = 'delivered';
                    $log->delivered_at = now();
                } elseif (in_array($normalized, ['FAILED', 'UNDELIV', 'UNDELIVERED', 'ERROR'], true)) {
                    $log->status = 'failed';
                    $log->failed_at = now();
                    $log->error_code = $normalized;
                }

                $log->meta = $meta;
                $log->save();
            } else {
                Log::warning('sms.webhook.delivery.unknown_id', ['provider_id' => $providerId, 'status' => $status]);
            }

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

        // Reply via POST: smsId, m (message), from, to, time
        if ($request->isMethod('post') && $request->post('smsId')) {
            $providerId = (string) ((int) $request->post('smsId'));
            $msg = trim(strip_tags((string) $request->post('m', '')));
            $fromNumber = (string) $request->post('from', '');
            $toNumber = (string) $request->post('to', '');
            $timestamp = (int) $request->post('time', time());

            $log = SmsLog::query()->where('provider_message_id', $providerId)->first();
            if ($log) {
                $meta = (array) $log->meta;
                $replies = isset($meta['replies']) && is_array($meta['replies']) ? $meta['replies'] : [];
                $replies[] = [
                    'message' => $msg,
                    'from' => $fromNumber,
                    'to' => $toNumber,
                    'time' => date('c', $timestamp),
                ];
                $meta['replies'] = $replies;
                $log->meta = $meta;
                $log->save();
            } else {
                Log::warning('sms.webhook.reply.unknown_id', [
                    'provider_id' => $providerId,
                    'from' => $fromNumber,
                    'to' => $toNumber,
                ]);
            }

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

        // Unknown payload
        return response()->json(['ok' => false, 'reason' => 'unsupported payload'], 400);
    }
}
