<?php


namespace App\Helpers;
use Illuminate\Support\Facades\Artisan;
use function GuzzleHttp\Psr7\build_query;

class Sms {

    private static $userSender = 'Legalvision';

    public function __construct()
    {
        Artisan::call('config:clear');
        if (config('app.sms_mode') == 'test'){
            self::$userSender = 'OTP';
        }
    }

    public static function send($to, $message)
    {

        $re = '/^((966)|(\+966)|(0))?([0-9]{7,9})$/';
        preg_match($re, $to, $matches);

        // 581524713
        if($matches && $matches[5]) {
            $url = 'https://www.msegat.com/gw/sendsms.php';
            $fields = [
                'userName' => 'Legalvision',
                'numbers' => '966'.$to,
                'userSender' => self::$userSender,
                'apiKey' => '4ba58d56980093046afc22e21782e803',
                "msg" => $message,
            ];

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
//                CURLOPT_HEADER => true,
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/json"
                ],
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => json_encode($fields),
            ));
            $response = curl_exec($curl);
            $info = curl_getinfo($curl);
            curl_close($curl);

            $response = json_decode($response);
            if ($info['http_code'] == 200 && in_array($response->code, [1, 'M0000']) && $response->message == 'Success'){
                return true;
            } else {
                return false;
            }
        }
    }
}
