<?php

namespace App\Http\Controllers\Public;

use App\Domain\WhatsApp\WhatsAppManager;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

/**
 * Meta Cloud API webhook. GET verifies the subscription; POST receives
 * delivery/read receipts and inbound messages (e.g. YES/NO replies).
 * Lives on the central domain (provider-facing, no tenant subdomain).
 */
class WhatsAppWebhookController extends Controller
{
    public function verify(Request $request)
    {
        if ($request->query('hub_mode') === 'subscribe'
            && $request->query('hub_verify_token') === config('whatsapp.meta.verify_token')) {
            return response($request->query('hub_challenge'));
        }

        return response('forbidden', 403);
    }

    public function handle(Request $request, WhatsAppManager $wa)
    {
        foreach ($request->input('entry', []) as $entry) {
            foreach ($entry['changes'] ?? [] as $change) {
                $value = $change['value'] ?? [];

                // Delivery/read status updates
                foreach ($value['statuses'] ?? [] as $status) {
                    $wa->applyStatusUpdate(
                        $status['id'] ?? '',
                        $status['status'] ?? '',
                        $status['errors'][0]['title'] ?? null,
                    );
                }
                // Inbound replies (YES/NO confirmations) handled in M6 follow-up.
            }
        }

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