<?php

namespace App\Http\Controllers\BundlesControllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use \stdClass;
use Log;



class BundleController extends Controller
{
    public function requestAft(Request $request){
        
        return "hello";
        //Log::info($request->all());
     
    }
    //check aft
    public function checkAft(){
        
        $object = new stdClass();
        $uri="https://payments.africastalking.com/mobile/data/request";
        $client=new Client();
        $response=$client->request('POST',$uri, ['headers' => ['Content-Type' => 'application/json','Accept'=>'application/json','apiKey' => '1ef1c6d568b18b19f104f0d13e29e75b38f8d08bf712a99257a8ac2a32925124'],
        'json' => [
            'username' => 'mobisky',
            'productName' => 'Mobile _Data',
            'recipients' => [[
                'phoneNumber' => '+254712516957',
                'quantity'=>7,
                'unit'=>'MB',
                'validity'=>'Day',
               'metadata'=>$object
            ]]
        ]
      ]);
      
      return $response->getBody();
       
    }
    
    
        public function bundlestopupMyLine(){
        
        $object = new stdClass();
        $uri="https://payments.africastalking.com/mobile/data/request";
        $client=new Client();
        $response=$client->request('POST',$uri, ['headers' => ['Content-Type' => 'application/json','Accept'=>'application/json','apiKey' => '1ef1c6d568b18b19f104f0d13e29e75b38f8d08bf712a99257a8ac2a32925124'],
        'json' => [
            'username' => 'mobisky',
            'productName' => 'Mobile _Data',
            'recipients' => [[
                'phoneNumber' => '+254712516957',
                'quantity'=>15,
                'unit'=>'MB',
                'validity'=>'Day',
               'metadata'=>$object
            ]]
        ]
      ]);
      
      return $response->getBody();
       
    }
    
    
    //callback
    public function getAft(Request $request){
        Log::info("from here");
        Log::info($request->all());
    }
    //request for callback
    public function requestCallBack(Request $request){
        $serial=$request->serial;
        
        $callback = array(
                    "callbackId"=>1,
                    "defaultMessage" => array(
                             "EN"=>"Callback accepted, please wait and you will be contacted by a member of our team shortly"
                     ),
                     "message"=>"Callback request 1 created for unit serial number ".$serial
                    
                );
                
        Log::info(json_encode($callback));
        
    }
    
    //return the units of the associated phone number
    public function returnUnits($phone){
        $array=array();
          $object = new stdClass();
          $object->unitSerialNumber =123456789;
          $object->phoneNumber ="254702142629";
          /*$object2 = new stdClass();
          $object2->unitSerialNumber =123456709;
          $object2->phoneNumber ="254718014207";
          $object3 = new stdClass();
          $object3->unitSerialNumber =123456789;
          $object3->phoneNumber ="254718014207";*/
       
       array_push($array,$object);
       /*array_push($array,$object2);
       
       array_push($array,$object3);*/
             
       return response()->json($array);
    }
    
    ///Raphael return units 2
    //return the units of the associated phone number
    public function returnUnits2($phone){
          $array=array();
          $object = new stdClass();
          $object->unitSerialNumber =123456745;
          $object->phoneNumber ="254718014207";
          
          $object2 = new stdClass();
          $object2->unitSerialNumber =123456745;
          $object2->phoneNumber ="254718014207";
         /* 
         $object3 = new stdClass();
          $object3->unitSerialNumber =123456745;
          $object3->phoneNumber ="254718014207";*/
       
       array_push($array,$object);
       array_push($array,$object2);
       
       //array_push($array,$object3);
             
       return response()->json($array);
    }
    //return the topup details
    public function returnTopupData($serial){
       
            $AccountInfo = array(
                    "serialNumber"=>123456745,
                     "defaultMessage" => array(
                             "EN"=>"Please top up unit 123456745 a minimum of KES 1"
                     ),
                      "minimumTopUp" => array(
                             "amount"=>12.34,
                             "currency"=> "KES"
                     ),
                     "message"=>"Please top up unit 123456745 a minimum of KES 1",
                     "destinationAccount" =>array(
                         "accountType"=> "M-PESA-KE",
                         "accountNumber"=> "ABC123456789" 
                         )
                    
                );
                
                return response()->json($AccountInfo);
                /*$body= $response->getBody();
                $j=json_decode($body,true);               return $AccountInfo['destinationAccount']['accountNumber'];*/
                
        
    }
    
    //get the last tcode
    public function returnLastTCode($phone){
        
      
            $AccountStatus = array(
                    "expiryDate"=> "2000-01-23T04:56:07.000Z",
                    "serialNumber"=> 123456745,
                    "lastTCode"=> "T 12 34 56 78",
                    "ewalletBalance" => array(
                         "amount"=> 12.34,
                         "currency"=> "KES"
                     ),
                  "defaultMessage"=>array(
                    "EN"=> "Your unit 123456745 last top up date 2020-12-01 (T 12 34 56 78) EXPIRING ON 2020-12-10 e-wallet balance of KES12.34. Thank you",
                  ),
                  "topUpDate"=> "2000-01-23T04:56:07.000Z",
                   "message"=> "Unit 123456745 last top up date 2020-12-01 (T 12 34 56 78) EXPIRING ON 2020-12-10 e-wallet balance of KES12.34"
                  
                );
                
                return response()->json($AccountStatus);
                
      
    }
    
    //get latest topup data
    public function getTopUpData ($phone){
        $data_object = (Object)[
            'data'=>"Your latest topup data is Ksh.50 for ".$phone];
            
            if(!empty($data_object)){
                return response()->json(["success"=>true,"message"=>$data_object]);  
            }
            else{
                 return response()->json(["success"=>false,"message"=>"invalid request"]);
            }
        
    }
    
    //account info data
    public function getAccountInfo($phone){
        
            $AccountInfo = array(
                    "serialNumber"=>123456745,
                    "contractCompletionDate"=>"2000-01-23T04:56:07.000+00:00",
                    "creditDays"=>0,
                    "defaultMessage"=>array(
                    "EN"=> "Your unit 123456745 is active and 10 days in\/out of credit current outstanding balance is KES12.34 10 weeks to contract completion. Thank you",
                  ),
                  "outstandingBalance"=>array(
                      "amount"=>12.339999999999999857891452847979962825775146484375,
                      "currency"=>"KES"
                      ),
                   "message"=> "Unit 123456745 is active and 10 days in\/out of credit current outstanding balance is KES12.34 10 weeks to contract completion",
                   "status"=>"active"
                  
                );
                
                return response()->json($AccountInfo);
                
      
    }
    
      //customer service number
    public function getCustomerService($phone){
        
            $CSInfo = array(
                    "customerServiceNumber"=> 0,
                    "defaultMessage"=>array(
                    "EN"=> "Customer service number: [01234 567 890]"
                  ),
                  
                   "message"=> "Customer service number for 123456745 is +0123 456 7890"
                  
                );
                
                return response()->json($CSInfo);
                
      
    }
    
      //customer service number
    public function getCallBack($phone){
        
            $Callback = array(
                    "callbackId"=>1,
                    "defaultMessage"=>array(
                    "EN"=>"Callback accepted, please wait and you will be contacted by a member of our team shortly"
                  ),
                  
                   "message"=> "Callback request 1 created for unit serial number 123456745"
                  
                );
                
                return response()->json($Callback);
                
      
    }
    
   //test checkunits api
     public function testgetUnitsApi($phone){
        
        //$number="+0123 456789";
        $url="https://staging.gcp.azuri-technologies.com/user-self-service/units?phoneNumber=".rawurlencode($phone);
        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization' => 'Bearer g'
             ]]);
        $body= json_decode($response->getBody());
        
        return $body;
    }
    
    //test login API
     //test checkunits api
     public function loginApi($phone){
        
        $url="https://staging.gcp.azuri-technologies.com/user-self-service/units?phoneNumber=".rawurlencode($phone);
        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization' => 'Bearer g'
             ]]);
        $body= json_decode($response->getBody());
        if ($body){
                 return response()->json(["success"=>true,"message"=>$body]);
            }
        else{
                return response()->json(["success"=>false,"message"=>"customer does not exist"]);
            }
    }
    
    //get the serials
    public function getAccountSerials($phone){
        
        $url="https://staging.gcp.azuri-technologies.com/user-self-service/units?phoneNumber=".rawurlencode($phone);
        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization' => 'Bearer g'
             ]]);
        $body= json_decode($response->getBody());
        $serials=[];
        foreach($body as $bd){
            array_push($serials,$bd->unitSerialNumber);
        }
        if ($serials){
                 return response()->json(["success"=>true,"message"=>$serials]);
            }
        else{
                return response()->json(["success"=>false,"message"=>"customer does not exist"]);
            }
    }
    
    
    //test the topup api
    public function testgetTopups($my_serial){
        
        //get the serial numbers
       /* $serials=TestController::testgetUnitsApi($phone);
        $serial="";
        $a_serials=array();
        foreach($serials as $s){
            array_push($a_serials,$s->unitSerialNumber);
        }
        
        $my_serial= $a_serials[0];*/
        
        $my_serial=explode('=',$my_serial);
       
        $url="https://staging.gcp.azuri-technologies.com/user-self-service/units/".$my_serial[0]."/topup";
        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization'     => 'Bearer 2'
             ]]);
        $body= $response->getBody();
        $account=json_decode($body,true);
        
        //returns the array object
         if ($account){
                  $x1=explode(" ",$account['defaultMessage']['EN']);
                 
                  $details_array["get_code"]="To get your next 7 day Top Up Code,";
                  $details_array["please_pay"]="Please pay:";
                  $x1=explode(" ",$account['message']);
                  $details_array["amount"]=$x1[0]." ".$x1[1]." ".$x1[2]." ".$x1[3]." ".$x1[4]." ".$x1[5];
                  
                  return response()->json(["success"=>true,"message"=>$details_array]);
            }
        else{
                return response()->json(["success"=>false,"message"=>"no topup record"]);
            }
        
        
        
    }
    //test the last tcode
    public function testAccountStatus($my_serial){
        
        //get the serial numbers
        /*$serials=TestController::testgetUnitsApi($phone);
        $serial="";
        $a_serials=array();
        foreach($serials as $s){
            array_push($a_serials,$s->unitSerialNumber);
        }
         
        $my_serial= $a_serials[0];
        */
        $my_serial=explode('=',$my_serial);
        $url="https://staging.gcp.azuri-technologies.com/user-self-service/units/".$my_serial[0]."/accountstatus";
        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization'     => 'Bearer 2'
             ]]);
        $body= $response->getBody();
        $account=json_decode($body,true);
        
        //returns the array object
        //returns the array object
         if ($account){
                // $details_array["balance"]="KSh.".round($account['outstandingBalance']['amount'],2);
                 //$details_array["contract_date"]=date("d-m-Y", strtotime($account['contractCompletionDate']));
                  $x1=explode(" ",$account['defaultMessage']['EN']);
                 
                  $details_array["code_for"]=$x1[13]." ".$x1[14]." Top-Up";
                  $details_array["Tcode"]=$account['lastTCode'];
                  $details_array["topup_date"]=date("d-m-Y", strtotime($account['topUpDate']));
                  $details_array["balance"]=$account['ewalletBalance']['currency']." ".round($account['ewalletBalance']['amount'],2);
                  return response()->json(["success"=>true,"message"=>$details_array]);
                
            }
        else{
                return response()->json(["success"=>false,"message"=>"no status available"]);
            }
        
        
        
    }
    
    //test the account information
    public function testAccountInformation($my_serial){
        
        //get the serial numbers
        /*$serials=TestController::testgetUnitsApi($phone);
        $serial="";
        $a_serials=array();
        foreach($serials as $s){
            array_push($a_serials,$s->unitSerialNumber);
        }
        
        $my_serial= $a_serials[0];
        
       */
        $my_serial=explode('=',$my_serial);
        
        $url="https://staging.gcp.azuri-technologies.com/user-self-service/units/".$my_serial[0]."/accountinfo";
        //$url="http://azr.mobisky.biz/api/accountinfo/".$my_serial."/accountinfo";
        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization'     => 'Bearer 2'
             ]]);
        $body= $response->getBody();
        
        $account=json_decode($body,true);
        
       
        //returns the array object
         if ($account){
                 $details_array["balance"]="KSh.".round($account['outstandingBalance']['amount'],2);
                 $details_array["contract_date"]=date("d-m-Y", strtotime($account['contractCompletionDate']));
                 $x1=explode(" ",$account['defaultMessage']['EN']);
                 $x2=date("d-m-Y", strtotime($x1[15]));
                 $details_array["topup_date"]=$x2;
                 $details_array["status"]=$account['status'];
                
                 //return response()->json($details_array);
                 
                 return response()->json(["success"=>true,"message"=>$details_array]);
            }
        else{
                return response()->json(["success"=>false,"message"=>"no account information"]);
            }
        
        
        
    }
    
     //test customer service number
    public function testCustomerServiceNumber($my_serial){
        
        //get the serial numbers
        /*$serials=TestController::testgetUnitsApi($phone);
        $serial="";
        $a_serials=array();
        foreach($serials as $s){
            array_push($a_serials,$s->unitSerialNumber);
        }
        
        $my_serial= $a_serials[0];
        
        */
        $my_serial=explode('=',$my_serial);
        $url="https://staging.gcp.azuri-technologies.com/user-self-service/contact/".rawurlencode($my_serial[1]);
        //$url="http://azr.mobisky.biz/api/units/".$my_serial."/customerservice";
        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization'     => 'Bearer 2'
             ]]);
        $body= $response->getBody();
        $csnumber=json_decode($body,true);
        
        //returns the array object
         if ($csnumber){
                 return response()->json(["success"=>true,"message"=>$csnumber]);
            }
        else{
                return response()->json(["success"=>false,"message"=>"customer service number unavailable"]);
            }
        
        
        
    }
    
     //test customer service request callback
        public function testCallback($my_serial){
       
        //get the serial numbers
        /*$serials=TestController::testgetUnitsApi($phone);
        $serial="";
        $a_serials=array();
        foreach($serials as $s){
            array_push($a_serials,$s->unitSerialNumber);
        }
        
        $my_serial= $a_serials[0];
        */
        $my_serial=explode('=',$my_serial);
        $url="https://staging.gcp.azuri-technologies.com/user-self-service/contact/".rawurlencode($my_serial[1]);
        //$url="http://azr.mobisky.biz/api/units/".$my_serial."/callback";
        $client=new Client();
                    
        $response=$client->request('POST',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization'     => 'Bearer 2'
             ]]);
        $body= $response->getBody();
        $callback=json_decode($body,true);
        
        //returns the array object
         if ($callback){
                 return response()->json(["success"=>true,"message"=>$callback]);
            }
        else{
                return response()->json(["success"=>false,"message"=>"callback recording failed"]);
            }
        
        
        
    }
    public function testFunction(){
        /*$serial="123456789";
        $url="http://azr.mobisky.biz/api/units/".$serial."/accountinfo";
                        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization'     => 'Bearer 2'
             ]]);
        $body= $response->getBody();
        $j=json_decode($body,true);
        
        return $j['message'];*/
        $m=array('20120504'=>44,'20120505'=>59);
        
        $j=array_search('20120504', array_keys($m));
        
       array_search('20120504', array_column($m, 'uid'));
        return response()->json($cv);
        
        //last tcode
        //return $j['lastTCode'];
        //returns the array object
        //return $j['ewalletBalance']['currency'].':'.$j['ewalletBalance']['amount'];
    }

}
        

