<?php

namespace App\Services\Plugins\Sms;

use GuzzleHttp\Client;

class FarazsmsService
{
    private static $url = "https://api2.ippanel.com/api/v1/sms/pattern/normal/send";
    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;
            }
        }

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

        // data
        $data = [
            'code' => $template,
            'sender' => '3000505',
            'recipient' => '98' . substr($receptor, 1),
            "variable" => $newParams
        ];

        // headers
        $headers = [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'apikey' => static::$apiKey,
        ];

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

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