<?php

namespace App\Http\Controllers\BundlesControllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\atmodels\Airtime_group;
use App\Models\atmodels\Airtime_sending_credential;
use App\Models\atmodels\Currency_expenditure;
use App\Models\atmodels\Airtime_contact;
use App\Models\atmodels\Airtime_customer;
use App\Models\bmmodels\CustomerClient;
use App\Classes\FCClasses\SendBandles;
use App\Classes\FCClasses\SendSms;
use App\Models\atmodels\DataBundlesCredits;
use App\Models\bundles\Data_Topups;
use App\Models\fcmodels\Contact;
use App\Models\atmodels\SmsApiUser;
use App\Models\atmodels\Currency_credit;
use App\Models\atmodels\Databandles;
use App\Models\atmodels\Datacategory;
use App\Models\atmodels\DataBandlesExpenditure;
use App\Models\bundles\TailMessage;
use App\Models\bundles\Data_Bundles_TopUp;
use App\Classes\FCClasses\SMSCounter;
use Illuminate\Support\Str;
use EloquentBuilder;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use \stdClass;
use DB;
use Carbon\Carbon;

use Auth;
use Log;
use Exception;
use App\Libs\MobiskyAirtime;

class BundlesTopupController extends Controller
{
    
  
    public function getDataInfo(Request $request){

        $dataadd = new Data_Topups();
        $dataadd->category = $request->category;
        $dataadd->clientAccount = $request->clientAccount;
        $dataadd->description = $request->description;
        $dataadd->destination = $request->destination;
        $dataadd->destinationType = $request->destinationType;
        $dataadd->direction = $request->direction;
        $dataadd->origin = $request->origin;
        $dataadd->productName = $request->productName;
        $dataadd->provider = $request->provider;
        $dataadd->providerChannel = $request->providerChannel;
        $dataadd->providerRefId = $request->providerRefId;
        $dataadd->source = $request->source;
        $dataadd->sourceType = $request->sourceType;
        $dataadd->status = $request->status;
        $dataadd->transactionDate = $request->transactionDate;
        $dataadd->transactionId = $request->transactionId;
        $dataadd->value = $request->value;
        $dataadd->save ();
        // $shop_id=Auth::user()->shop_id;
        // $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
        // $databundles = DataBundlesCredits::findOrFail($shop_id);
        // $databundles->amount = $datawallet[0]+$request->value;
        // $databundles->save ();

    }
    
    public function getDataInfocallback(Request $request)
    {   //https://api.africastalking.com/version1/user  status
       
     
       Log::info($request->status);
       Log::info($request);
     // $transactionId= Str::between($body, '"transactionId":"', '","value"');
       $data = Data_Bundles_TopUp::where('transactionId',$request->transactionId)->update(['status'=>$request->status]);
    //   $data->status = $request->status;t
    //   $data->save();
      $shop_ids = Data_Bundles_TopUp::where('transactionId', $request->transactionId)->pluck('ShopID')->first();

        if($request->status='Success'){
 
                   $datawallet = DataBundlesCredits::where('shopid',$shop_ids)->pluck('amount'); 
                
                       $data2 = DataBundlesCredits::where('ShopID',$shop_ids)->first();
                if($data2){
                    
                    $value = str_replace("KES ", "", $request->value); // $value is now "5.0000"
                DataBundlesCredits::find($data2->data_bundles_credits_id);
                $data2->amount = $datawallet[0]-$value;
                 
            
                 $data2 = DataBundlesCredits::where('ShopID',$shop_ids)->update(['amount'=>$data2->amount]);
                 Log::info($shop_ids);
                        Log::info( $datawallet);
                
                }
      }
    

   return $request->status;
   

    }


    public function getdata_balance(Request $request)
    {   //https://api.africastalking.com/version1/user
        //$my_serial=explode('=',$my_serial);
        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
     
            $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
            $groups = Airtime_group::where('ShopID',$shop_id)->get();
            $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
            $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 

        }
        Log::info($request->all());
        Log::info($shop_id);



        $databundles = DataBundlesCredits::findOrFail($shop_id);
        $databundles->amount = $request->amount;
        $data->save ();

        $url="https://api.africastalking.com/version1/user?username=mobisky";
        $client=new Client();
                    
        $response=$client->request('GET',$url,[
          'headers' => [
              'Content-Type' => 'application/json',
              'Authorization'     => 'Bearer 2'
             ]]);
        $body= $response->getBody();
        $account=json_decode($body,true);
        Log::info($request);
    }


    //return topup groupbundles view
    public function groupbundles()
    {
        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
     
            $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
            $groups = Airtime_group::where('ShopID',$shop_id)->get();
            $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
            $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
            $topup_datawallet  = Data_Bundles_TopUp::where('shopid',$shop_id)->where('status','Success')->where('qnty','10')->sum('qnty');

            $topup_7mb  = Data_Bundles_TopUp::where('shopid',$shop_id)->where('status','Success')->where('qnty','7')->sum('qnty');       
            //$s7mb = $topup_7mb
            
            $rt= ($topup_datawallet * 100 * 1024) + $topup_7mb;
          
            return view('bundleviews.topup.groupbundles', compact('rt','datawallet','wallet','groups','wallet'));
        }
    }
    
    
    
    //get contacts
    public function getdatabandlescategory()
    
    {
   
            $databandlescategory = Datacategory::with('Databandlescategory')->get();
            return $databandlescategory;
    }


     
    //get contacts
    public function getdatabandles($id)
    {
   
   // $contacts = Databandles::where('organization_id',$id)->get();
            $contacts = Databandles::with('Databandlescategory')->where('data_category_id',$id)->get();
            return $contacts;
    }
    //return topup contact bundles view
    public function contactbundles()
    {Log::info(Auth::user());

        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
      
            
            $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
            $shop_id=Auth::user()->shop_id;            
            $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
            $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
            $contactsAirtime = Airtime_contact::where('ShopID',$shop_id)->where('bundle',1)->with('contactGroup')->get();
               $c=array();
            ////////////////////////////////added/////////////////////////
            
             $shop_id=Auth::user()->shop_id;
             $customer_id=Auth::user()->userShopUser['customer_id'];
             $contacts1 = Airtime_contact::where('ShopID',$shop_id)->where('send_bundles_status',0)->get()->toArray();
             
               foreach($contacts1 as $d){
                    $e['contact']="+254".substr($d['contact'],-9);
                    $e['fname']=$d['fname'];
                    $e['contact_id']=$d['contact_id'];
                    array_push($c,$e);
                
                }
            
            
            
            if(Auth::user()->cust_id){
             
                 $fcuser_id = Auth::user()->organization_id;
                 $contacts2=Contact::where('organization_id',$fcuser_id)->get(['phone AS contact','name AS fname','contact_id'])->toArray();
       
                foreach($contacts2 as $a){
                    $b['contact']="+254".substr($a['contact'],-9);
                    $b['fname']=$a['fname'];
                    $b['contact_id']=$a['contact_id'];
                    array_push($c,$b);
                
                }
            }
            
            if(Auth::user()->bulk_cust_id){
                $id=Auth::user()->bulk_cust_id;
                $data = CustomerClient::where('customer_cust_id',$id)->where('cust_client_status',1)->get(['cust_client_phone AS contact','cust_client_fullname AS fname','cust_client_id AS contact_id'])->toArray();
               
                foreach($data as $a){
                    $mdata['contact']="+254".$a['contact'];
                    $mdata['fname']=$a['fname'];
                    $mdata['contact_id']=$a['contact_id'];
                    array_push($c,$mdata);
                
                }
            }
            
           $contacts=$c;
            
            $groups = Airtime_group::where('ShopID',$shop_id)->get();
            return view('bundleviews.topup.contactbundles', compact('datawallet','contacts','groups','wallet','contactsAirtime'));
        }
    }
    //topup group    
    public function topupGroupbundles(Request $request)
    {
        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
            $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
        }
        else{
            return abort(401);
        }
        $request->validate([
            'group_id'=>'required',
        
            'data_category_id'=>'required',
            'amount'=>'required|integer|min:5',
        ],
         
   
        [
            'group_id.required'=>'Please select group',
            'amount.required'=>'Please enter amount',
            'amount.integer'=>'Please enter a whole number',
            'amount.integer'=>'Please enter amount not less than 5',
        ]);
 
        $credentials = Airtime_sending_credential::where('customer_id',$customer_id)->first();
        $username = $credentials['username'];
        $password = $credentials['password'];
        $amount=$request->amount;
        //get the airtime_customer
        $user_sms_api = SmsApiUser::where('shop_id',$shop_id)->pluck('username');
        $pass_sms_api = SmsApiUser::where('shop_id',$shop_id)->pluck('password');

        $apiuser = Airtime_customer::where('customer_id',$customer_id)->pluck('username');
        
        //get contacts
        $group_id = $request->group_id['group_id'];
        
        $contacts_customer_id= Airtime_contact::where('ShopID',$shop_id)->pluck('ime','contact','group_id');
        
        
        $groupscontacts= $request->group_id['group_id'];
 
        $var1 = $groupscontacts;
        $var2 = str_replace("$groupscontacts", "[$groupscontacts]", $var1);
        $contacts = Airtime_contact::where('group_id',$var1)->select(['contact_id','fname','contact','ime','send_bundles_status'])->get();
        $imes = Airtime_contact::where('group_id',$var1)->get()->pluck('ime');
       
        //call the function that returns the contacts for this group
     
      
        $contacts_array= $contacts;
        $data_contacts = array();
     
                        foreach($contacts as $contactss){
                            $phone = $contactss->contact;
                            $fname= $contactss->fname;
                            $ime= $contactss->ime;
                            $contact_id= $contactss->contact_id;
                            $send_bundles_status= $contactss->send_bundles_status;
                    //get contacts
                    $contactsee = $request;


                //     $current_time_string_year = \Carbon\Carbon::now()->format('Y');
                //     $current_time_string_month = intval(\Carbon\Carbon::now()->format('m'));
                //     $created_at = Data_Bundles_TopUp::select('contact','created_at')->where('ShopID', $shop_id)->where('contact', $phone)->latest('created_at')->first();
                
                // $year = \Carbon\Carbon::parse($created_at->created_at)->year;
                // $month = \Carbon\Carbon::parse($created_at->created_at)->month;
                //     //  Log::info($month);
                //     //  Log::info($current_time_string_year);
                //     //  Log::info($current_time_string_month);
                //   // exit();  $year>=$current_time_string_year && 
                   
                //     if($year>=$current_time_string_year && $month>=$current_time_string_month+2){
                //     return response()->json(["errors"=>["amount"=>["Duplicates: The device with (IMEI) ".$ime." has already received data bundles"]]],422);
                //     }



                  $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
                  $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
        
                  if($datawallet[0]<$request->amount ){
                     
                    return response()->json(["errors"=>["amount"=>["Please topup your account, Your Current balance is low)"]]],422);
                   }
         
                        
                        //get the Data category id
                        $validity=$request->data_category_id['data_category_name'];
                        $quantity=$request->databandles_id['databandles_package'];
                        //get the val
                        $qnty=0;
                        $unit="";
                        
                        if($validity=="Day"){
                             $quantity_mx =explode("MB",$quantity);
                             $qnty=$quantity_mx[0];
                             $unit="MB";
                        }
                        elseif($validity=="Week"){
                             $quantity_mx =explode("GB",$quantity);
                             $qnty=$quantity_mx[0];
                             $unit="GB";
                        }
                        elseif($validity=="Month"){
                             $quantity_mx =explode("GB",$quantity);
                             $qnty=$quantity_mx[0];
                             $unit="GB";
                        }
                       // return $contact; 
         //send Bundles
     $object = new stdClass();
     $pr= $phone;
     Log::info($phone);

     /***************************/
     Log::info( $phone);
     $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' => $pr,
             'quantity'=>(int)$qnty,
             'unit'=>$unit,
             'validity'=>$validity,
             'metadata'=>$object
         ]]
     ]
   ]); 

   $body= $response->getBody();
   Log::info($body);
//       $tailmessage = TailMessage::where('ShopID',$shop_id)->first();
//       //Log::info($firstnames);
//       $message = 'Dear '.$fname.' thank you for your loyalty. You have received '.$qnty.'  '.$unit.' from Samsung Galaxy S23 preorder . Expiry date 3/07/2024 ';
//   // $message = 'Dear '.$fname.' you have received FREE '.$qnty.' '.$unit.' Data Bundles for your product with IMEI '.$ime.' ';
//       $phone=$phone;
//       $smsobject=new SendSms($username,$password);

//       $smscountclass = new SMSCounter();
//       $SmsApiUsers = SmsApiUser::where('shop_id',$shop_id)->get();
//       Log::info($SmsApiUsers);
       
//       foreach($SmsApiUsers as $SmsApiUser)
//       {
//       // Log::info($SmsApiUser);
//       $username=$SmsApiUser->username;
//       $password=$SmsApiUser->password;
//       $smsobject=new SendSms($username,$password);

//       $smscount = $smscountclass->count($message)->messages;
//       $textstatus=$smsobject->sendMessage($phone,$message);
//       }


                  
                // $data = DataBundlesCredits::where('ShopID',$shop_id)->first();
                // if($data){
                // DataBundlesCredits::find($data->data_bundles_credits_id);
                // $data->amount = $datawallet[0]-$request->amount;
                 
                // $data->save ();
       


                // $contacts_customer_id= Airtime_contact::where('ShopID',$shop_id)->pluck('customer_id','send_bundles_status');
                // $cdata = Airtime_contact::where('contact_id', $contactss->customer_id)->first();
                // if($data){
                // $dda=  Airtime_contact::find($contactss->customer_id);
                // $dda->send_bundles_status  = '1';         
                // $dda->save ();

               // $cdata = Airtime_contact::where('contact_id',$contactss->customer_id)->first();
              
               $cdata = Airtime_contact::find($contact_id);
               if ($cdata) {
                 $cdata->send_bundles_status = '1';
                 $cdata->save();
               } else {
                 Log::error('Airtime contact not found for customer ID: '.$contact_id);
               }
                

              $logData = json_decode(substr($body, strpos($body, '{')), true);
                $status = $logData['entries'][0]['status'];
            //  $entries = ['entries'];
              
 
                $datatopups = new Data_Bundles_TopUp();
                $datatopups->ShopID = $shop_id;   
                $datatopups->contact = $phone;
                $datatopups->customer = $fname;
                $datatopups->qnty = $qnty;
                $datatopups->unit = $unit;
                $datatopups->ime = $ime;
                $datatopups->status = $status;  
                $datatopups->transactionId = Str::between($body, '"transactionId":"', '","value"');
             //  $datatopups->status = $this->getDataInfocallback($request->status);
             // Log::info($status);
               // $datatopups->status = 'Success';
              // Log::info($datatopups->transactionId);
                $datatopups->save ();
             //   }
        

            
        }
        
          
//      $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' => $data_contacts
//      ]
//    ]);
                        
    }

    
    //get contacts for a group 
    public function getGroupeContacts($group_id){
        
        //get the contacts with this group id
       $contacts = Airtime_contact::select('group_id', 'contact')->get();
       $groupes=$contacts->toArray();
      
       foreach($groupes as $grp){
         $group_ee=$grp['group_id'];
         $replace1=str_replace('[','',$group_ee);
         $replace2=str_replace(']','',$replace1);
         //convert into array
         $new_grp=explode(",",$replace2);
         $count1=AirtimeGroupController::count_array_values($new_grp, $idtofind);
         $count+=$count1;
         array_push($array1,$new_grp);
       }
       return $count; 
    
    }
    //topup topupContact bundles
    public function topupContactbundles(Request $request)
    {
       
        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
            $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
        }
        else{
            return abort(401);
        }
        $request->validate([
            'contact'=>'required',
            'amount'=>'required|integer|min:5',
        ],
        [
            'contact.required'=>'Please select contact',
            'amount.required'=>'Please enter amount',
            'amount.integer'=>'Please enter a whole number',
            'amount.min'=>'Please enter amount not less than 5',
        ]);
        //get credentials
        $credentials = Airtime_sending_credential::where('customer_id',$customer_id)->first();
        $username = $credentials['username'];
        $password = $credentials['password'];

        $amount=$request->amount;
        //get the airtime_customer
        $user_sms_api = SmsApiUser::where('shop_id',$shop_id)->pluck('username');
        $pass_sms_api = SmsApiUser::where('shop_id',$shop_id)->pluck('password');

        $apiuser = Airtime_customer::where('customer_id',$customer_id)->pluck('username');
 
        //get contacts
        $contacts = $request->contact;


        $contactf=$contacts[0]['send_bundles_status'];
        if($contactf=="1"){
      // return response()->json(["errors"=>["contact"=>["Duplicates: This device(IMEI) has already received data bundles"]]],422);
        }
       
      foreach($contacts as $contact)
        {
             $request->validate([
            'contact' => 'required',
            'data_category_id' => 'required',
            
        ]); 
        $ime = $contact['ime'];
        $current_time_string_year = \Carbon\Carbon::now()->format('Y');
        $current_time_string_month = intval(\Carbon\Carbon::now()->format('m'));
        $created_at = Data_Bundles_TopUp::select('contact','created_at')->where('ShopID', $shop_id)->where('contact', $contact['contact'])->latest('created_at')->first();
    
    // $year = \Carbon\Carbon::parse($created_at->created_at)->year;
    // $month = \Carbon\Carbon::parse($created_at->created_at)->month;
    //     //  Log::info($month);
    //     //  Log::info($current_time_string_year);
    //     //  Log::info($current_time_string_month);
    //   // exit();  $year>=$current_time_string_year && 
       
    //     if($year>=$current_time_string_year && $month>=$current_time_string_month+3){
    //     return response()->json(["errors"=>["amount"=>["Duplicates: The device with (IMEI) ".$ime." has already received data bundles"]]],422);
    //     }

 
          //check if the client has the money
          $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
          $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
              
         $datawallet[0];
        
       //  Log::info($datawallet);
        
                 if($datawallet[0]<$request->amount ){
                     
                  return response()->json(["errors"=>["amount"=>["Please topup your account, Your Current balance is low)"]]],422);
                 }
                 $returnvalue= (count($request->contact));
                      if($datawallet[0]< $request->value*$returnvalue){
                     
                  return response()->json(["errors"=>["amount"=>["Please topup your account, Your Current balance is low)"]]],422);
                 }
             
        // else
        {
            
            //get the Data category id
            $validity=$request->data_category_id['data_category_name'];
            $quantity=$request->databandles_id['databandles_package'];
            //get the val
            $qnty=0;
            $unit="";
            if($validity=="Day"){
                 $quantity_mx =explode("MB",$quantity);
                 $qnty=$quantity_mx[0];
                 $unit="MB";
            }
            elseif($validity=="Week"){
                 $quantity_mx =explode("GB",$quantity);
                 $qnty=$quantity_mx[0];
                 $unit="GB";
            }
            
            elseif($validity=="Month"){
                $quantity_mx =explode("GB",$quantity);
                $qnty=$quantity_mx[0];
                $unit="GB";
           }


            //send Bundles
            $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' => $contact['contact'],
                    'quantity'=>(int)$qnty,
                    'unit'=>$unit,
                    'validity'=>$validity,
                  'metadata'=>$object
                ]]
            ]
          ]);
          $body= $response->getBody();
          Log::info($body);
          
          
          
             foreach($body as $bodyuser)
          {
          $bo=$bodyuser->status;
        Log::info($bo);
          }
          
          $data = json_decode($body, true);


          
      
          
          
          
         $Customer=$contact['fname'];
         if($Customer=='NULL') {
            $Customer='Customer';
         }
         else {
            $Customer=$contact['fname'];
         }
         
        //  $tailmessage = TailMessage::where('ShopID',$shop_id)->first();
        //  //$message = 'Dear '.$Customer.' thank you for your loyalty. You have received 10GB from Samsung Galaxy S23 preorder . Expiry date 3/07/2024';
        //  $message = 'Dear '.$Customer.' thank you for your loyalty. You have received '.$qnty.'  '.$unit.' from Samsung Galaxy S23 preorder .';
        //  $phone=$contact['contact'];
        
        //   $smscountclass = new SMSCounter();
        //   $SmsApiUsers = SmsApiUser::where('shop_id',$shop_id)->get();
          
          
        //   foreach($SmsApiUsers as $SmsApiUser)
        //   {
        //   $username=$SmsApiUser->username;
        //   $password=$SmsApiUser->password;
        //   $smsobject=new SendSms($username,$password);
        //   Log::info($SmsApiUser);
        //   $smscount = $smscountclass->count($message)->messages;
        //   $textstatus=$smsobject->sendMessage($phone,$message);
        //   }
          $var=$datawallet[0]-$request->amount;
         $data = DataBundlesCredits::where('ShopID',$shop_id)->first();
         if($data){
         DataBundlesCredits::find($data->data_bundles_credits_id);
         $data->amount =
          $datawallet[0]-$request->amount;         
         $data->save ();




         $contacts_customer_id= Airtime_contact::where('ShopID',$shop_id)->pluck('customer_id','send_bundles_status');
         $cdata = Airtime_contact::where('contact_id', $contact['contact_id'])->first();
         if($data){
         Airtime_contact::find($cdata->contact_id);
         $cdata->send_bundles_status = '1';         
         $cdata->save ();

         $body= $response->getBody();
         $data3 = json_decode($body, true);
       //  $status3 = $entry['status'];

 $data3 = json_decode($body, true);
foreach ($data3['entries'] as $entry) {
    $status3 = $entry['status'];
          Log::info($status3);
         $status="Success";
         $datatopups = new Data_Bundles_TopUp();
         $datatopups->ShopID = $shop_id;   
         $datatopups->contact = $contact['contact'];
         $datatopups->customer = $Customer;
         $datatopups->qnty = $qnty;
         $datatopups->unit = $unit;
         $datatopups->ime = $ime;
         $datatopups->status = $status3;
        // $datatopups->status = $this->getDataInfocallback($request->status);
         $datatopups->save ();

}
         }
       
            return 'success';
           
         
            
        }
        
        /****************************************************************************************/
       
        }
       
    }
}
    
    //topup all contacts
    public function topupMyContactsbundles(Request $request)
    {
        //
        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
            $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
        }
        else{
            return abort(401);
        }
        $request->validate([
            'amount'=>'required|integer|min:5',
        ],
        [
            'amount.required'=>'Please enter amount',
            'amount.integer'=>'Please enter a whole number',
            'amount.min'=>'Please enter amount not less than 5',
        ]);
        // get credentials
        $credentials = Airtime_sending_credential::where('customer_id',$customer_id)->first();
        $username = $credentials['username'];
        $password = $credentials['password'];

        $amount=$request->amount;
        //get the airtime_customer
        $user_sms_api = SmsApiUser::where('shop_id',$shop_id)->pluck('username');
        $pass_sms_api = SmsApiUser::where('shop_id',$shop_id)->pluck('password');

        $apiuser = Airtime_customer::where('customer_id',$customer_id)->pluck('username');
        //get contacts
        $contacts = Airtime_contact::where('ShopID',$shop_id)->pluck('contact');
        
        
        Log::info($contacts);
        Log::info($request->all());
        
        foreach($contacts as $contact)
        {
             //check if the client has the money
          $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
          $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
                

         $datawallet[0];
         if($datawallet[0]<$request->amount ){
                     
            return response()->json(["errors"=>["amount"=>["Please topup your account, Your Current balance is low)"]]],422);
           }
           $returnvalue= (count($request->contact));
                if($datawallet[0]< $request->value*$returnvalue){
               
            return response()->json(["errors"=>["amount"=>["Please topup your account, Your Current balance is low)"]]],422);
           }
         
        // else
        {
            
            //get the Data category id
            $validity=$request->data_category_id['data_category_name'];
            $quantity=$request->databandles_id['databandles_package'];
            //get the val
            $qnty=0;
            $unit="";
            if($validity=="Day"){
                 $quantity_mx =explode("MB",$quantity);
                 $qnty=$quantity_mx[0];
                 $unit="MB";
            }
            elseif($validity=="Week"){
                 $quantity_mx =explode("GB",$quantity);
                 $qnty=$quantity_mx[0];
                 $unit="GB";
            }
            elseif($validity=="Month"){
                 $quantity_mx =explode("GB",$quantity);
                 $qnty=$quantity_mx[0];
                 $unit="GB";
            }
          
        
            //send Bundles
      //send Bundles
      $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' => $contact,
              'quantity'=>(int)$qnty,
              'unit'=>$unit,
              'validity'=>$validity,
            'metadata'=>$object
          ]]
      ]
    ]);
      //Send SMS
    $message = 'Dear Customer you have received '.$qnty.'  '.$unit.' from Mobisky.';
    $phone=$contact;
    $smsobject=new SendSms($username,$password);

    $textstatus=$smsobject->sendMessage($phone,$message);
              
            $x=$response->getBody();
            $x1=json_decode($x,true);
           // Log::info($contact['contact']);
            Log::info($x1['entries']);
            
            return 'success';
        
            if(empty($x1['entries']) && $x1['errorMessage']=='A duplicate request was received within the last 5 minutes'){
          
                return response()->json(["errors"=>["amount"=>["Kindly wait for 5 minutes to resend Data to same contact"]]],422);
            }
            else if(empty($x1['array']['0'])){
          
                return response()->json(["errors"=>"Error! Contact Support for Assistance."],422);
            }
      
          Log::info($x1['entries']);
                $phonenumber =$x1['entries']['0']['phoneNumber'];
                $provider =$x1['entries']['0']['provider'];
                $status =$x1['entries']['0']['status'];
                $transactionId =$x1['entries']['0']['transactionId'];
                $value =$x1['entries']['0']['value'];
                
                $data = new DataBandlesExpenditure();
                $data->shopid = $shop_id;
                $data->transactionId =$transactionId;
                $data->transactiondate ='2021-11-18 14:53:19.000000';
                $data->description = 'Data Bundles';
                $data->destination= $phonenumber;
                $data->value = $value;
                $data->status = $status;
                $data->save ();

          $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
        Log::info($wallet[0]);
        $figure= round($wallet[0],0);
        $ff=   $figure-$value;

         $users = Currency_credit::findOrFail($shop_id);
        $users->amount = $ff;
        $users->save();   
                
    
                
        
            
                
            }
            
        }
        }

  
    

   //return topupMyLine contact view
   public function mylinebundles()
   {
       if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
       {
           $customer_id=Auth::user()->userShopUser['customer_id'];
           $shop_id=Auth::user()->shop_id;            
            $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
           $contacts = Airtime_contact::where('ShopID',$shop_id)->with('contactGroup')->get();
           $myline = Airtime_customer::where('customer_id',$customer_id)->get();
           $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
        
             return view('bundleviews.topup.mylinebundles', compact('contacts','myline','wallet','datawallet'));
       }
   }
   //Topup Mycontact
   public function bundlestopupMyLine(Request $request)
   {
       //
       if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
       {
           $shop_id=Auth::user()->shop_id;
           $customer_id=Auth::user()->userShopUser['customer_id'];
       }
       else{
           return abort(401);
       }
       $request->validate([
           'phone'=>'required',
           'amount'=>'required|integer|min:5',
       ],
       [
           'phone.required'=>'Please select contact',
           'amount.required'=>'Please enter amount',
           'amount.integer'=>'Please enter a whole number',
           'amount.min'=>'Please enter amount not less than 5',
       ]);
       //get credentials
        $credentials = Airtime_sending_credential::where('customer_id',$customer_id)->first();
       $username = $credentials['username'];
       $password = $credentials['password'];

       $amount=$request->amount;
       //get the airtime_customer
       $user_sms_api = SmsApiUser::where('shop_id',$shop_id)->pluck('username');
       $pass_sms_api = SmsApiUser::where('shop_id',$shop_id)->pluck('password');

       $apiuser = Airtime_customer::where('customer_id',$customer_id)->pluck('username');
       //get contacts
       //get contacts
       $contact = $request->phone;
       
       
         
           
          //check if the client has the money
          $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount'); 
          
                

         $wallet[0];
                 if($wallet[0]<1){
                     
                  return response()->json(["errors"=>["amount"=>["Please topup your account, Your Current balance is low)"]]],422);
                 }
               
                $returnvalue= (count($request->contact));
                      if($wallet[0]< $request->value*$returnvalue){
                     
                  return response()->json(["errors"=>["amount"=>["Please topup your account, Your Current balance is low)"]]],422);
                 }
         
        // else
        {
            
            //get the Data category id
            $validity=$request->data_category_id['data_category_name'];
            $quantity=$request->databandles_id['databandles_package'];
            //get the val
            $qnty=0;
            $unit="";
            if($validity=="Day"){
                 $quantity_mx =explode("MB",$quantity);
                 $qnty=$quantity_mx[0];
                 $unit="MB";
            }
            elseif($validity=="Week"){
                 $quantity_mx =explode("GB",$quantity);
                 $qnty=$quantity_mx[0];
                 $unit="GB";
            }
            elseif($validity=="Month"){
                 $quantity_mx =explode("GB",$quantity);
                 $qnty=$quantity_mx[0];
                 $unit="GB";
            }
          
        
            //send Bundles
                $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' => $contact,
                        'quantity'=>(int)$qnty,
                        'unit'=>$unit,
                        'validity'=>$validity,
                       'metadata'=>$object
                    ]]
                ]
              ]);
              
            $x=$response->getBody();
            $x1=json_decode($x,true);
           // Log::info($contact['contact']);
            Log::info($x1['entries']);
            if(empty($x1['entries']) && $x1['errorMessage']=='A duplicate request was received within the last 5 minutes'){
          
                return response()->json(["errors"=>["amount"=>["Kindly wait for 5 minutes to resend Data to same contact"]]],422);
            }
            else if(empty($x1['array']['0'])){
          
                return response()->json(["errors"=>"Error! Contact Support for Assistance."],422);
            }

          Log::info($x1['entries']);
                $phonenumber =$x1['entries']['0']['phoneNumber'];
                $provider =$x1['entries']['0']['provider'];
                $status =$x1['entries']['0']['status'];
                $transactionId =$x1['entries']['0']['transactionId'];
                $value =$x1['entries']['0']['value'];
                
                $data = new DataBandlesExpenditure();
                $data->shopid = $shop_id;
                $data->transactionId =$transactionId;
                $data->transactiondate ='2021-11-18 14:53:19.000000';
                $data->description = 'Data Bundles';
                $data->destination= $phonenumber;
                $data->value = $value;
                $data->status = $status;
                $data->save ();

          $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
        Log::info($wallet[0]);
        $figure= round($wallet[0],0);
        $ff=   $figure-$value;

         $users = Currency_credit::findOrFail($shop_id);
        $users->amount = $ff;
        $users->save();                   
    
                
                return 'success';
                
              
                
            }
            
        }
       

   



  public function dataassignment()
    {
        //

        if(Auth::user()->user_type == 'organization_user' || Auth::user()->user_type == 'organization')
        {
            $shop_id=Auth::user()->shop_id;
            $customer_id=Auth::user()->userShopUser['customer_id'];
            $query = DataBandlesExpenditure::where('shopid',$shop_id);
      $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
            $groups = Airtime_group::where('ShopID',$shop_id)->get();
           $history=EloquentBuilder::to($query,request()->all())->get();          
            return view('bundleviews.history.bundles', compact('wallet','history','groups','customer_id'));
        }
        else{
            return abort(401);
        }
 
    }

    //export excel
    public function exportExcel()
    {
        return new AirtimeHistory(request()->all());
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */


// Display user data in view
public function showHistory(){
    $customer_id=Auth::user()->userShopUser['customer_id'];
    $history = Airtime_sending_record::where('customer_id',$customer_id)->get();
    return view('bundleviews.history.pdf_view', compact('history'));
  }

  // Generate PDF
  public function createPDF() {
    // retreive all records from db
    $customer_id=Auth::user()->userShopUser['customer_id'];
    $query = Airtime_sending_record::where('customer_id',$customer_id);
    $history=EloquentBuilder::to($query,request()->all())->get();

    // share data to view
    //view()->share('history',$data);
    $shop_id=Auth::user()->shop_id;
    $customer_id=Auth::user()->userShopUser['customer_id'];
    $shopname=Auth::user()->userShopUser['customer_id'];
    $wallet = Currency_credit::where('shopid',$shop_id)->pluck('amount');
    $datawallet = DataBundlesCredits::where('shopid',$shop_id)->pluck('amount'); 
    $query = Airtime_sending_record::where('customer_id',$customer_id);
    $groups = Airtime_group::where('ShopID',$shop_id)->get();
   $history=EloquentBuilder::to($query,request()->all())->get();   
    $pdf = PDF::loadView('bundleviews.history.pdf_view', compact('datawallet','wallet','shopname','history','groups','customer_id'));


    // download PDF file with download method
    return $pdf->download('AirtimeHistory.pdf');
  }

}