<?php

// Code within app\Helpers\Helper.php

namespace App\Helpers;
use App\SMSLogs;

class SMSGateway {

    const URL = "http://app.mobivatebulksms.com/gateway/api/simple/MT?";

    public static function send($responder_id, $invoiceNumber, $title, $number, $message) {
        echo $number = env('PHONE_CODE') . ltrim($number, 0);
        self::request($responder_id, $invoiceNumber, $title, $number, $message);
        die("aaaa");
    }

    public static function request($responder_id, $invoiceNumber, $title, $number, $message) {
        try {

            $array = array(
                'USER_NAME' => env("SMS_API_USERNAME"),
                'PASSWORD' => env("SMS_API_PASSWORD"),
                'ORIGINATOR' => str_replace(" ", "", str_replace("Love2", "Lov2", env("APP_NAME"))),
                'RECIPIENT' => $number,
                'ROUTE' => env("SMS_API_ROUTE"),
                'MESSAGE_TEXT' => $message
            );

            echo $url = self::URL . http_build_query($array, '', "&");
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $res = curl_exec($ch);
            $error = curl_error($ch);
            if (!empty($error)) {
                $res = $error;
            }
            curl_close($ch);
            $insert = array(
                'PKSMSID' => $responder_id,
                'InvoiceNumber' => $invoiceNumber,
                'Title' => $title,
                'Content' => $message,
                'Phone' => $number,
                'Response' => $res,
                'IPAddress' => $_SERVER['REMOTE_ADDR'],
                'CreatedDateTime' => date('Y-m-d H:i:s')
            );
            SMSLogs::insert($insert);
            //$xml = new SimpleXMLElement($res);
            //return $xml;
        } catch (Exception $e) {
            return null;
        }
    }

}
