<?php

namespace App\Services\Plugins\Sms;

use GuzzleHttp\Client;

class SmsirService
{
    private static $url = "https://api.sms.ir/v1/send/verify";
    private static $apiKey = null;

    // service construct
    private static function init($smsPanel)
    {
        static::$apiKey = $smsPanel['fields']['information']['api_key'];
    }

    /** send sms */
    public static function send($smsPanel, $receptor, $template, $params)
    {
        // init
        static::init($smsPanel);

        // validate template pattern
        $template = $smsPanel['fields']['pattern'][$template]['value'];

        // validate params
        $newParams = [];
        foreach ($params as $key => $param) {
            if ($key == 'token') {
                $newParams['token_one'] = $param;
            } else if ($key == 'token2') {
                $newParams['token_two'] = $param;
            } else if ($key == 'token3') {
                $newParams['token_three'] = $param;
            }
        }
        $newParamsArr = [];
        foreach ($newParams as $key => $value) {
            $newParamsArr[] = [
                "name" => $key,
                "value" => $value
            ];
        }

        // guzzle client
        $client = new Client();

        // data
        $data = [
            'templateId' => $template,
            'mobile' => $receptor,
            "parameters" => $newParamsArr
        ];

        // headers
        $headers = [
            'Accept' => 'text/plain',
            'Content-Type' => 'application/json',
            'x-api-key' => static::$apiKey,
        ];

        // send request
        $result = $client->request('POST', static::$url, [
            'body' => json_encode($data),
            'headers' => $headers
        ]);

        return $result->getStatusCode() == 200 ? true : false;
    }
}
