<?php

namespace App\Services;

use App\Models\SmsApi;
use Illuminate\Support\Facades\Http;

class Sms
{

  public function send_sms($contact, $message, $api = '')
  {

    $contact = $contact;

    $result =  cache()->remember('smsapiForSendSms', 60 * 1, function () {
      return SmsApi::where('status', 'enable')->first();
    });

    if ($result) {

        if($result->username == "textcart"){

            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => $result->url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',

                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'Accept: application/json',
                    'Authorization: Bearer '.$result->apikey.''
                ),
            ));

            $req['recipient'] = "88$contact";
            $req['sender_id'] = $result->sender;
            $req['type'] = "plain";
            $req['message'] = $message;
            $request_data_json = json_encode($req);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $request_data_json);

            $response =curl_exec($curl);
            $response_return = "";

            foreach (json_decode($response) as $key => $value) {
                if($key == "message"){
                    $response_return = $value;

                }
            }
            curl_close($curl);

            return $response_return;
        }else{

            $link = str_replace(
              [
                '{apikey}',
                '{contactNumber}',
                '{senderNumber}',
                '{messageBody}'
              ],
              [
                $result->apikey,
                $contact,
                $result->sender,
                $message
              ],
              $result->url
            );


            $response = Http::get($link);
            return $response;
        }



    } else {

      if (config('app.sms_api') == 'm2mbd') {

        $url = "http://bulksms.m2mbd.net/smsapi?api_key=" . config('app.sms_api_key') . "&type=text&contacts=$contact&senderid=" . config('app.sms_sender') . "&msg=$message";
      }

      if (config('app.sms_api') == 'yetfix-sms-api') {

        $url = "https://sms-api.yetfix.com/api/v1/channels/sms?apiKey=" . config('app.sms_api_key') . "&recipient=$contact&from=" . config('app.sms_sender') . "&message=$message";
      }


      $contact = ltrim($contact, '+');

      if ($contact) {
        $response = Http::get($url);
        echo $response;
      } else {
        echo 'something is worng';
      }

      return $response;
    }
  }
}
