<?php
namespace App;

class SMSHelper
{


    public static function sendSms($smsdata) {

        // TODO : Restrict number for sending too many messages
        try{

            $uri_param = array(
                "messageText"       => $smsdata['message'],
                "senderName"   => config('services.cequens.sender_id'),
                "recipients"  => ltrim($smsdata['mobileNumber'], '+'),
                "messageType" => 'text'
            );

            $access_token = config('services.cequens.access_token');

            $url = config('services.cequens.endpoint');

            $curl = curl_init();


            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 300,
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => json_encode($uri_param),
                CURLOPT_HTTPHEADER => [
                    "Authorization: Bearer $access_token",
                    "Cache-Control: no-cache",
                    "Content-Type: application/json"
                ]
            ]);

            // TODO : uncomment when go live
            $response = curl_exec($curl);
            // $err = curl_error($curl);
            curl_close($curl);

            $jsonRes = json_decode($response,true);
            $status = $jsonRes['replyCode'] == 0 ?? 'ApiCalled';

            \DB::table('sms_log')->insert([
                'ph_num' => $smsdata['mobileNumber'],
                'message' => $smsdata['message'],
                'response' => $response,
                'status' => $status
            ]);

        }
        catch( Exception $ex )
        {
            \DB::table('sms_log')->insert([
                'ph_num' => $smsdata['mobileNumber'],
                'message' => $smsdata['message'],
                'response' => $ex->getMessage(),
                'status' => $ex->getCode()
            ]);
        }

    }
}

?>
