<?php

namespace App\Sms\Provider;

use App\Config\Repository\SiteConfigRepository;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class KavehNegarProvider implements SmsProviderInterface
{
    private const BASE = 'https://api.kavenegar.com/v1';

    public function __construct(
        private readonly HttpClientInterface  $httpClient,
        private readonly SiteConfigRepository $configRepo,
        private readonly string $apiKey = '',
        private readonly string $sender = '',
    ) {}

    private function key(): string   { return $this->configRepo->get('kavenegar_api_key') ?: $this->apiKey; }
    private function sender(): string { return $this->configRepo->get('kavenegar_sender') ?: $this->sender; }

    public function getName(): string { return 'kavenegar'; }

    public function send(string $mobile, string $message): bool
    {
        try {
            $resp = $this->httpClient->request('POST',
                self::BASE . '/' . $this->key() . '/sms/send.json', [
                    'body' => http_build_query([
                        'receptor' => $mobile,
                        'message'  => $message,
                        'sender'   => $this->sender(),
                    ]),
                    'timeout' => 10,
                ]
            );
            $data = $resp->toArray();
            return ($data['return']['status'] ?? 0) === 200;
        } catch (\Throwable) {
            return false;
        }
    }

    public function sendTemplate(string $mobile, string $templateCode, array $vars): bool
    {
        try {
            $params = ['receptor' => $mobile, 'template' => $templateCode];
            foreach (array_values($vars) as $i => $v) {
                $params['token' . ($i > 0 ? $i + 1 : '')] = $v;
            }
            $resp = $this->httpClient->request('POST',
                self::BASE . '/' . $this->key() . '/verify/lookup.json', [
                    'body' => http_build_query($params),
                    'timeout' => 10,
                ]
            );
            $data = $resp->toArray();
            return ($data['return']['status'] ?? 0) === 200;
        } catch (\Throwable) {
            return false;
        }
    }
}
