<?php

namespace App\Libs;
use AfricasTalking\SDK\AfricasTalking;

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use App\Models\atmodels\Setting;
use Log;

class MobiskyAirtime{

    protected $username;
    protected $password;
    protected $client;
    protected $response;
    protected $uri='http://www.mobisky.biz/apiAirtime/sendairtime.php?'; 


    public function __construct($username_, $password_,$amount_,$recipient_,$apiuser_)
    {
    $this->username = $username_;
    $this->password  = $password_;
    $this->amount = $amount_;
    $this->recipient  = $recipient_;
    $this->apiuser = $apiuser_;
    $this->client=null;
    $this->response=null;

    }
    public function sendAirtime(){

        $parameters=[
            'username'=>$this->username,
            'password'=>$this->password,
            'amount'=>$this->amount,
            'recipient'=>$this->recipient,
            'user'=>$this->apiuser,
        ];
        Log::info($parameters);
        
        //create a guzzleclient
        $this->client=new Client();
        //send the message
        $this->response=$this->client->request('GET',$this->uri.http_build_query($parameters));
        $body= $this->response->getBody();
       Log::info($body);
       
        if (strpos($body, 'Sent') !== false) {
            return "Sent";
        }
        else{
            return "Failed";
        }
       
    }
    
    /**
         * Use this function to initiate send airtime.
         * @param $phone | string
         * @param $amount | string
         * @return mixed|string
         */

    public function sendAirtime2($phone,$amount){
        /*Log::info($phone." ".$amount);die();
           //do a select from the db where setting_type=mobisky_airtime,,get the usernam and the apikey
       	    //credentials
       	     $setting=Setting::where('setting_type','=','afts')->first();
             $username=$setting['setting_key'];
             $apiKey=$setting['setting_value'];
        
		    //Create an instance of our awesome gateway class and pass your credentials
	         $gateway= new AfricasTalking($username, $apiKey);
			
			 date_default_timezone_set("Africa/Nairobi");
	         $today = date("Y-m-d H:i:s");
	         
	         // Get the airtime service
            $airtime  = $gateway->airtime();
            // Set the phone number, currency code and amount in the format below
            $recipients = [[
                "phoneNumber"  => $phone,
                "currencyCode" => "KES",
                "amount"       => $amount
            ]];
            try {
                // That's it, hit send and we'll take care of the rest
                $result = $airtime->send([
                    "recipients" => $recipients
                ]);
                 Log::info(json_encode($result));
                      
                       $responses=$result['data']->responses;
                       
                       $sentstatus=array();
                       
                       $error = $result['data']->errorMessage;
                       
                       if(empty($responses)){
    				          if($error=="A duplicate request was received within the last 5 minutes"){
    				              
    				             $sentstatus['status']="Duplicate"; 
    				             
    				          }
    				          
    				      }
    				   else{
    				       
        				       foreach($responses as $response){
                                $amnt = $response->amount;
                                $phne = $response->phoneNumber;
                                $rid =  $response->requestId;
                                $stat = $response->status;
                                
        				        
                    				if($stat == 'Sent')
                    				{
                    					$amt_str = explode(" ", $response->amount);
                    					$price = $amt_str[1];
                    					$discount = explode(" ", $response->discount);
                    					$cost = $price;
                    					$cost_1 = $price - $discount[1];
                    					
                    					//log the transaction to successful logs for reporting purposes
                    					$sentstatus['status']=$response->status;
                    					$sentstatus['requestid']=$response->requestId;
                    				}
                    				elseif($stat == 'Failed')
                    				{
                    					// get reason for failure and log the error
                    					$sentstatus['status']="Failed";
                    				
                    				
                    				}
        				          
        				      }
                			   
                			  
                           }
                          
                          return $sentstatus; 
    				       
    				 
    	
            } catch(Exception $e) {
                	$err = $e->getMessage();
		           Log::info(json_encode($err));
				return response()->json($err);
				
            }*/

    }
  

}