<?php

namespace App\Services;

use App\Models\SmsGateway;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;

class SmsGatewayClient
{
    public const PROVIDERS = [
        'bulksmsbd' => 'BulkSMSBD',
        'greenweb' => 'GreenWeb',
        'sslwireless' => 'SSL Wireless',
        'muthofun' => 'MuthoFun',
        'boomcast' => 'BoomCast',
        'generic' => 'Custom / Generic API',
    ];

    public function send(SmsGateway $gateway, string $recipient, string $message): Response
    {
        $settings = $gateway->settings ?? [];
        $provider = strtolower($gateway->provider ?: 'generic');
        $payload = match ($provider) {
            'bulksmsbd' => ['api_key' => $gateway->api_key, 'senderid' => $gateway->sender_id, 'number' => $recipient, 'message' => $message],
            'greenweb' => ['token' => $gateway->api_key, 'to' => $recipient, 'message' => $message],
            'sslwireless' => ['api_token' => $gateway->api_key, 'sid' => $gateway->sender_id, 'msisdn' => $recipient, 'sms' => $message, 'csms_id' => 'ISP-'.now()->format('YmdHisv')],
            'muthofun' => ['api_key' => $gateway->api_key, 'sender_id' => $gateway->sender_id, 'receiver' => $recipient, 'message' => $message],
            'boomcast' => ['api_key' => $gateway->api_key, 'sender_id' => $gateway->sender_id, 'to' => $recipient, 'message' => $message],
            default => [
                $settings['api_key_field'] ?? 'api_key' => $gateway->api_key,
                $settings['sender_id_field'] ?? 'sender_id' => $gateway->sender_id,
                $settings['recipient_field'] ?? 'recipient' => $recipient,
                $settings['message_field'] ?? 'message' => $message,
            ],
        };
        $payload = array_merge($payload, (array) ($settings['extra_payload'] ?? []));
        $request = Http::acceptJson()->connectTimeout(5)->timeout(15);
        foreach ((array) ($settings['headers'] ?? []) as $key => $value) $request = $request->withHeader($key, $value);

        return strtolower($settings['method'] ?? 'post') === 'get'
            ? $request->get($gateway->api_url, $payload)
            : (($settings['content_type'] ?? 'form') === 'json'
                ? $request->asJson()->post($gateway->api_url, $payload)
                : $request->asForm()->post($gateway->api_url, $payload));
    }

    public function succeeded(SmsGateway $gateway, Response $response): bool
    {
        if (! $response->successful()) return false;
        $codes = (array) data_get($gateway->settings, 'success_codes', []);
        if ($codes === []) return true;
        $actual = data_get($response->json(), data_get($gateway->settings, 'response_code_path', 'response_code'));
        return in_array((string) $actual, array_map('strval', $codes), true);
    }
}
