<?php

namespace App\Notifications\WhatsApp;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Twilio-based WhatsApp delivery. Disabled until the credentials land in
 * config('services.whatsapp.*') — see config/services.php.
 */
class TwilioWhatsAppGateway implements WhatsAppGateway
{
    public function send(string $toPhone, string $message): bool
    {
        $sid = config('services.whatsapp.twilio_sid');
        $token = config('services.whatsapp.twilio_token');
        $from = config('services.whatsapp.twilio_from'); // e.g. "whatsapp:+14155238886"

        if (! $sid || ! $token || ! $from) {
            Log::warning('whatsapp.misconfigured');

            return false;
        }

        $endpoint = "https://api.twilio.com/2010-04-01/Accounts/{$sid}/Messages.json";

        try {
            $response = Http::asForm()
                ->withBasicAuth($sid, $token)
                ->post($endpoint, [
                    'From' => $from,
                    'To' => 'whatsapp:'.$toPhone,
                    'Body' => $message,
                ]);

            if (! $response->successful()) {
                Log::warning('whatsapp.failed', ['status' => $response->status(), 'body' => $response->body()]);

                return false;
            }

            return true;
        } catch (\Throwable $e) {
            Log::error('whatsapp.exception', ['message' => $e->getMessage()]);

            return false;
        }
    }
}
