<?php

namespace App\Http\Controllers\BMControllers;
use EloquentBuilder;
use Illuminate\Http\Request;
use App\Models\bmmodels\CustomerWalletTransaction;
use App\Models\bmmodels\CustomerClientPayment;
use App\Models\bmmodels\ClientBatch;
use App\Models\bmmodels\Customer;
use App\Models\bmmodels\CustomerClient;
use App\Models\bmmodels\CustomerGroup;
use App\Models\bmmodels\CustomerWallet;
use App\Models\bmmodels\CustomerClientGroup;
use App\Models\bmmodels\AuditLog;
use App\Libs\Mpesa\Mpesa;
use App\Models\bmmodels\Mpesaresponse;
use App\Models\bmmodels\TransactionError;
use App\Models\bmmodels\Setting;
use Illuminate\Support\Facades\Log;
// use Carbon;
use Auth;
use Exception;
use ErrorException;
use File;
use App\Models\bmmodels\Rate;
use App\Libs\Mobisky;
use App\Models\bmmodels\BusinessNumber;
use App\Models\bmmodels\B2BRate;

class SuperviseController extends Controller
{
    // public function __construct()
    // {
    //     $this->middleware('auth:admin');
    // }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getUser(){
        return Auth::user();
    }
    
    public function index(Request $request)
    {
        $loggeduser=Auth::user();
       
        $id = '';
        
        if(Auth::user()->user_type == 'organization')
        {
            try
            {
                //get customer id
                $id = Auth::user()->bulk_cust_id;
                //get customer clients
                $clients = CustomerClient::where('customer_cust_id',$id)->pluck('cust_client_id');
                $client_batchs = ClientBatch::where('client_batch_customer_id',$id)->pluck('id');
                //get customer payments
                $batches = ClientBatch::where('client_batch_customer_id',$id)->get();
                $mygroups = CustomerGroup::where('customer_cust_id',$id)->get();
                $query = CustomerClientPayment::where('client_pay_tracking',0)->where('client_pay_status',0)->where('customer_cust_id',$id)->groupBy('client_pay_batch_id');/*orWhere('customer_cust_id',$id)
                        ->whereIn('customer_client_cust_client_id',$clients)->orWhereIn('customer_client_batch_id',$client_batchs);*/
                $payments = EloquentBuilder::to($query, $request->all())->get();
            }
            catch (ErrorException $e) {
                abort(401, $e->getMessage());
            }
        }
        else
        { 
            try
            {
                $batches = ClientBatch::all();
                $mygroups = CustomerGroup::all();
                // $payments = CustomerClientPayment::all();
                $payments = EloquentBuilder::to(CustomerClientPayment::class, $request->all())->get();
            }
            catch(Exception $e){
                abort(500, $e->getMessage());
            }
        }
        
        
        return view('bmviews.supervise.index',compact('payments','id','batches','mygroups'))->with('i');

    }
    

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('bmviews.payments.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    
    //pay approve
    public function store(Request $request)
    {
        ///if user status == 0 refuse request\
       if(Auth::user()->cust_status == 1)
       {
            $customer_id=Auth::user()->bulk_cust_id;
            
            if(isset($_POST['all']))
            {
                
                // request()->validate([
                //     'client_pay_batch_id' => 'required'
                // ],
                // ['client_pay_batch_id.required' => 'Please initiate a payment first']);
                //get phone numbers to pay
                $clients = $request->client_pay_batch_id;
                
                //pay approval
                $client_arr = [];
                //check if the total amount in the wallet is enough
                $customer=CustomerWallet::where(['customer_cust_id'=>$customer_id])->first();
                $customer_wallet_balance=(int)$customer['cust_wallet_bal'];
                //calculate the required amount to be disbursed
                $total_amount=0;
                $mob_charge=0;
                $mpesa_rate=0;
                $b2ctrans=0;
                $b2btrans=0;
                
                $clientsall_count=count($clients);
                
                foreach($clients as $client)
                {
                    //check if the account is a B2C or B2B
                    $accounttype=CustomerClientPayment::where('client_pay_batch_id',$client)->get();
                    
                    foreach($accounttype as $actype){
                        
                         if($actype['client_type']=='B2C'){
                        //do an assumption the recipient is registered, the exact amount is deducted depending on the reg status of the number
                         $rate_bracket = 'salary_payment_registered_customer';
                        //get the rate for the B2C for this amount
                         
                         $mpesarate = Rate::where('rate_min','<=',$actype['client_pay_amount'])->where('rate_max','>=',$actype['client_pay_amount'])->where('rate_type',$rate_bracket)->pluck('total_charges');
                        
                         //====get 7% of transcharge======//
                         //check for the existing records
                        // $mobiskycharge = 0.2*$mpesarate[0];
                         $mob_charge=$mob_charge+$mpesarate[0];
                         $b2ctrans=$b2ctrans+1;  
                        }
                        elseif($actype['client_type']=='B2B'){
                         //use the paybill/till number to get the corresponding tarriff
                         $paybillno=$actype['client_b2b_number'];
                         $business=BusinessNumber::where('business_number',$paybillno)->first();
                         
                         $b2b_tariff = $business['tariff_id'];
                        //get the rate level
                         $b2b_mpesa_level = B2BRate::where('rate_min','<=',$actype['client_pay_amount'])->where('rate_max','>=',$actype['client_pay_amount'])->where('tariff_id',$b2b_tariff)->pluck('rate_level');
                        //get the mpesa rate %
                        $b2b_mpesa_rate = B2BRate::where('rate_min','<=',$actype['client_pay_amount'])->where('rate_max','>=',$actype['client_pay_amount'])->where('tariff_id',$b2b_tariff)->pluck('rate_saf_charges');
                        
                        //get the mobisky %
                        $b2b_mobisky_rate = B2BRate::where('rate_min','<=',$actype['client_pay_amount'])->where('rate_max','>=',$actype['client_pay_amount'])->where('tariff_id',$b2b_tariff)->pluck('rate_charge');
                        
                        //create a variable to cater for the charges
                        $b2bcharge=0;
                        $mobiskycharge=0;
                     
                        
                        //know the rate max
                        if($b2b_mpesa_level[0]=="min"){
                           $b2bcharge= $b2b_mpesa_rate[0];
                           $mobiskycharge=0.00;
                           
                        }
                        elseif($b2b_mpesa_level[0]=="max"){
                           $b2bcharge= $b2b_mpesa_rate[0];
                           $mobiskycharge=($b2b_mobisky_rate[0]/100)*$b2bcharge;
                        }
                        elseif($b2b_mpesa_level[0]=="normal"){
                           //mpesa cut
                           $b2bcharge=($b2b_mpesa_rate[0]/100)*$actype['client_pay_amount'];
                           $mobiskycharge=($b2b_mobisky_rate[0]/100)*$b2bcharge;
                        }
                        //get the total charge
                         $mob_charge=$mob_charge+$mobiskycharge+$b2bcharge;
                         $b2btrans=$b2btrans+1;  
                        }
                    
                    }
                   
                    
                    $payment = CustomerClientPayment::where('client_pay_batch_id',$client)->sum('client_pay_amount');
                    //add the charge expected here
                    
                    $amount=(int)$payment;//->client_pay_amount;
                    
                    //add the transaction charge estimates
                    $total_amount=$total_amount+$amount+$mob_charge;


                }

                if($customer_wallet_balance>$total_amount){

                    
                foreach($clients as $client)
                {
                    $pay_id = CustomerClientPayment::where('client_pay_batch_id',$client)->pluck('client_pay_id');
                    $pay_arr = [];
                    foreach($pay_id as $payid)
                    {
                    $approve = CustomerClientPayment::find($payid);
                    $approve->client_pay_tracking = "1";
                    $approve->client_pay_status = "1";
                    $customer_id=Auth::user()->bulk_cust_id;
                    //cater for b2c customers
                    if(($approve->customer_client_cust_client_id!="") &&($approve->client_type=="B2C")){
                    
                        //get the phone number to receive the money from client table
                    $client=CustomerClient::find($approve->customer_client_cust_client_id);
                    
                            //$client->cust_client_phon
                        $disbursement= SuperviseController::b2cMpesa('254'.$client->cust_client_phone,(int)$approve->client_pay_amount);
                        //for successful transaction,reduce the wallet balance by the amount
                        $walletbal=$customer_wallet_balance-$amount;
                            //get wallet bal
                        $b2c_tariff ='salary_payment_registered_customer'; 
                        
                        $disbursement['cust_id'] = $customer_id;
                        $disbursement['client_pay_id'] = $payid;
                        $disbursement['cust_tariff'] = $b2c_tariff;
                        $disbursement['cust_type'] = 'B2C';
                        Mpesaresponse::create($disbursement);
                        
                        //log
                        SuperviseController::payauditLog($approve->client_pay_id);
                        
                            
                    }
                    elseif(($approve->customer_client_batch_id!="")&&($approve->customer_type=="B2C")){
                    
                        //find the phone number of the client from the batch table
                        $clientbatch=ClientBatch::where(['id'=>$approve->customer_client_batch_id])->first();
                        //send mpesa transaction
                    
                        $disbursement=SuperviseController::b2cMpesa('254'.$clientbatch['client_phone'],(int)$clientbatch['transfer_amount']);
                            //for successful transaction,reduce the wallet balance by the amount
                        $b2c_tariff ='salary_payment_registered_customer';   
                        $disbursement['cust_id'] = $customer_id;
                        $disbursement['cust_tariff'] = $b2c_tariff;
                        $disbursement['cust_type'] = 'B2C';
                        $disbursement['client_pay_id'] = $payid;
                        
                        Mpesaresponse::create($disbursement);
                        
                        //log
                        SuperviseController::payauditLog($approve->client_pay_id);
                        
                        
                        //check the amount in the wallet  
                    }
                    elseif(($approve->client_b2b_number !="")&&($approve->client_type=="B2B") ){
                        //send the money to the b2b using b2bapi
                        
                        //know the tariff for this b2b
                        $paybillno=$approve->client_b2b_number;
                        
                        $business=BusinessNumber::where('business_number',$paybillno)->first();
                        $b2b_tariff = $business['tariff_id'];
                        //store the tariff id in the mpesa reponse for effective deduction
                        $disbursement['cust_tariff'] = $b2b_tariff;
                        $disbursement['cust_type'] = 'B2B'; 
                        $disbursement=SuperviseController::b2bMpesa((int)$approve->client_pay_amount,$approve->client_b2b_number); //$approve->client_pay_amount,$approve->client_b2b_number
                        
                        
                        $disbursement['cust_id'] = $customer_id;
                        $disbursement['client_pay_id'] = $payid;
                        Mpesaresponse::create($disbursement);
                    
                        //log
                        SuperviseController::payauditLog($approve->client_pay_id);
                        
                        
                    }
                        array_push($pay_arr,$approve);
                        $approve->save();
                    
                }
                array_push($client_arr,$pay_id);
                
                
            }
                   if($b2ctrans>0 && $b2btrans>0){
                       // return response()->json($client_arr);
                    return redirect()->back()->
                    with('success',"You have approved ".$b2ctrans." B2C and ".$b2btrans." B2B Transactions. Total Amount sent is Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                  
                     }
                     elseif($b2ctrans>0 && $b2btrans<1){
                        // return response()->json($client_arr);
                    return redirect()->back()->
                     with('success',"You have approved ".$b2ctrans." B2C Transactions. Total Amount sent is Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                  
                     }
                     elseif($b2ctrans<1 && $b2btrans>0){
                      return redirect()->back()->
                     with('success',"You have approved ".$b2btrans." B2B Transactions. Total Amount sent is Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                  
                     }
                
               
                

            }
            elseif($customer_wallet_balance<$total_amount){
                    
                    $balrem=$total_amount-$customer_wallet_balance;
                    
                     if($b2ctrans>0 && $b2btrans>0){
                       // return response()->json($client_arr);
                    return redirect()->back()->
                    with('failure',"You dont have enough balance to send ".$b2ctrans." B2C and ".$b2btrans." B2B Transactions. Topup an additional Ksh.".$balrem." to send Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                  
                     }
                     elseif($b2ctrans>0 && $b2btrans<1){
                        // return response()->json($client_arr);
                    return redirect()->back()->
                    with('failure',"You dont have enough balance to send ".$b2ctrans." B2C Transactions. Topup an additional Ksh.".$balrem." to send Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                 
                     }
                     elseif($b2ctrans<1 && $b2btrans>0){
                      return redirect()->back()->
                     with('failure',"You dont have enough balance to send ".$b2btrans." B2B Transactions. Topup an additional Ksh.".$balrem." to send Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                     
                     }
                    }
            
            }
            else if(isset($_POST['selected']))
            {
            $this->validate(
                    $request, 
                    ['client_pay_batch_id' => 'required'],
                    ['client_pay_batch_id.required' => 'Please select payment(s) first']
                );
                $clients = $request->client_pay_batch_id;
                //pay
                $client_arr = [];

                //check if the total amount in the wallet is enough
                $customer=CustomerWallet::where(['customer_cust_id'=>$customer_id])->first();
                $customer_wallet_balance=(int)$customer['cust_wallet_bal'];
                //calculate the required amount to be disbursed
                $total_amount=0;
                $mob_charge=0;
                $mpesa_rate=0;
                $b2ctrans=0;
                $b2btrans=0;
                
                $clients_select_count=count($clients);
                foreach($clients as $client)
                {
                    
                    //check if the account is a B2C or B2B
                    $accounttype=CustomerClientPayment::where('client_pay_batch_id',$client)->get();
                    
                    foreach($accounttype as $actype){
                        
                         if($actype['client_type']=='B2C'){
                        //do an assumption the recipient is registered, the exact amount is deducted depending on the reg status of the number
                         $rate_bracket = 'salary_payment_registered_customer';
                        //get the rate for the B2C for this amount
                         
                         $mpesarate = Rate::where('rate_min','<=',$actype['client_pay_amount'])->where('rate_max','>=',$actype['client_pay_amount'])->where('rate_type',$rate_bracket)->pluck('total_charges');
                        
                         //====get 7% of transcharge======//
                         //check for the existing records
                         //$mobiskycharge = 0.2*$mpesarate[0];
                         $mob_charge=$mob_charge+$mpesarate[0];
                         $b2ctrans=$b2ctrans+1;  
                        }
                        elseif($actype['client_type']=='B2B'){
                         //use the paybill/till number to get the corresponding tarriff
                         $paybillno=$actype['client_b2b_number'];
                         $business=BusinessNumber::where('business_number',$paybillno)->first();
                         
                         $b2b_tariff = $business['tariff_id'];
                        //get the rate level
                         $b2b_mpesa_level = B2BRate::where('rate_min','<=',$actype['client_pay_amount'])->where('rate_max','>=',$actype['client_pay_amount'])->where('tariff_id',$b2b_tariff)->pluck('rate_level');
                        //get the mpesa rate %
                        $b2b_mpesa_rate = B2BRate::where('rate_min','<=',$actype['client_pay_amount'])->where('rate_max','>=',$actype['client_pay_amount'])->where('tariff_id',$b2b_tariff)->pluck('rate_saf_charges');
                        
                        //get the mobisky %
                        $b2b_mobisky_rate = B2BRate::where('rate_min','<=',$actype['client_pay_amount'])->where('rate_max','>=',$actype['client_pay_amount'])->where('tariff_id',$b2b_tariff)->pluck('rate_charge');
                        
                        //create a variable to cater for the charges
                        $b2bcharge=0;
                        $mobiskycharge=0;
                     
                        
                        //know the rate max
                        if($b2b_mpesa_level[0]=="min"){
                           $b2bcharge= $b2b_mpesa_rate[0];
                           $mobiskycharge=0.00;
                           
                        }
                        elseif($b2b_mpesa_level[0]=="max"){
                           $b2bcharge= $b2b_mpesa_rate[0];
                           $mobiskycharge=($b2b_mobisky_rate[0]/100)*$b2bcharge;
                        }
                        elseif($b2b_mpesa_level[0]=="normal"){
                           //mpesa cut
                           $b2bcharge=($b2b_mpesa_rate[0]/100)*$actype['client_pay_amount'];
                           $mobiskycharge=($b2b_mobisky_rate[0]/100)*$b2bcharge;
                        }
                        //get the total charge
                         $mob_charge=$mob_charge+$mobiskycharge+$b2bcharge;
                         $b2btrans=$b2btrans+1;  
                        }
                    
                    }
                    
                    
                    
                    
                    
                    $payment = CustomerClientPayment::where('client_pay_batch_id',$client)->sum('client_pay_amount');
                    $amount=(int)$payment;//->client_pay_amount;
                     //add the transaction charge estimates
                    $total_amount=$total_amount+$amount+$mob_charge;


                }

                if($customer_wallet_balance>$total_amount){

                foreach($clients as $client)
                {
                    
                    $pay_id = CustomerClientPayment::where('client_pay_batch_id',$client)->pluck('client_pay_id');
                    //pay each id in batch
                    $pay_arr = [];
                    foreach($pay_id as $payid)
                    {
                    $approve = CustomerClientPayment::find($payid);
                    $approve->client_pay_tracking = "1";
                    $approve->client_pay_status = "1";
                    $amount=$approve->client_pay_amount;
                    
                    $customer_id=Auth::user()->bulk_cust_id;
                    //cater for b2c customers
                    if(($approve->customer_client_cust_client_id!="") &&($approve->client_type=="B2C")){
                        
                        //get the phone number to receive the money from client table
                        $client=CustomerClient::find($approve->customer_client_cust_client_id);
                            //$client->cust_client_phon
                        $disbursement=SuperviseController::b2cMpesa('254'.$client->cust_client_phone,(int)$approve->client_pay_amount);
                        $b2c_tariff ='salary_payment_registered_customer'; 
                        //insert the originator and convesation ids for counterchecking with the responses
                        $disbursement['cust_id'] = $customer_id;
                        $disbursement['client_pay_id'] = $payid;
                        $disbursement['cust_tariff'] = $b2c_tariff;
                        $disbursement['cust_type'] = 'B2C';
                        
                        Mpesaresponse::create($disbursement);
                      
                        //log
                        SuperviseController::payauditLog($approve->client_pay_id);
                        
                        
                        
                    }
                    elseif(($approve->customer_client_batch_id!="") &&($approve->client_type=="B2C")){
                    
                        //find the phone number of the client from the batch table
                        $clientbatch=ClientBatch::where(['id'=>$approve->customer_client_batch_id])->first();
                        $b2c_tariff ='salary_payment_registered_customer'; 
                        //send mpesa transaction
                        $disbursement=SuperviseController::b2cMpesa('254'.$clientbatch['client_phone'],(int)$clientbatch['transfer_amount']);
                        
                        $disbursement['cust_id'] = $customer_id;
                        $disbursement['client_pay_id'] = $payid;
                        $disbursement['cust_tariff'] = $b2c_tariff;
                        $disbursement['cust_type'] = 'B2C';
                        
                        Mpesaresponse::create($disbursement);
                        //reduce wallet
                        //get wallet bal
                        $customer_wallet=CustomerWallet::where('customer_cust_id',$customer_id)->get('cust_wallet_bal');
                       
                        //log
                        SuperviseController::payauditLog($approve->client_pay_id);
                        
                        //check the amount in the wallet  
                    }
                    elseif(($approve->client_b2b_number!="") &&($approve->client_type=="B2B")){
                        //know the tariff for this b2b
                        $paybillno=$approve->client_b2b_number;
                        
                        $business=BusinessNumber::where('business_number',$paybillno)->first();
                        $b2b_tariff = $business['tariff_id'];
                        //store the tariff id in the mpesa reponse for effective deduction
                        //send the money to the b2b using b2bapi
                        $disbursement= $disbursement=SuperviseController::b2bMpesa((int)$amount,$approve->client_b2b_number);
                        
                        $disbursement['cust_id'] = $customer_id;
                        $disbursement['client_pay_id'] = $payid;
                        $disbursement['cust_tariff'] = $b2b_tariff;
                        $disbursement['cust_type'] = 'B2B';
                        Mpesaresponse::create($disbursement);
                        //get wallet bal
                        $customer_wallet=CustomerWallet::where('customer_cust_id',$customer_id)->get('cust_wallet_bal');
                        //reduce wallet
                        //log
                        SuperviseController::payauditLog($approve->client_pay_id);
                        
                        
                    }
                        
                        array_push($pay_arr,$approve);
                        $approve->save();
                        
                        //also update the wallet of the sent amount
                        
                        
                        
                }
                // return $disbursement;
                
                array_push($client_arr,$pay_id);
                }
                    if($b2ctrans>0 && $b2btrans>0){
                           // return response()->json($client_arr);
                        return redirect()->back()->
                        with('success',"You have approved ".$b2ctrans." B2C and ".$b2btrans." B2B Transactions. Total Amount sent is Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                      
                    }
                     elseif($b2ctrans>0 && $b2btrans<1){
                        // return response()->json($client_arr);
                    return redirect()->back()->
                     with('success',"You have approved ".$b2ctrans." B2C Transactions. Total Amount sent is Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                  
                     }
                     elseif($b2ctrans<1 && $b2btrans>0){
                      return redirect()->back()->
                     with('success',"You have approved ".$b2btrans." B2B Transactions. Total Amount sent is Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                  
                     }

                }
                elseif($customer_wallet_balance<$total_amount){

                    $balrem=$total_amount-$customer_wallet_balance;
                    
                     if($b2ctrans>0 && $b2btrans>0){
                       // return response()->json($client_arr);
                    return redirect()->back()->
                    with('failure',"You dont have enough balance to send ".$b2ctrans." B2C and ".$b2btrans." B2B Transactions. Topup an additional Ksh.".$balrem." to send Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                  
                     }
                     elseif($b2ctrans>0 && $b2btrans<1){
                        // return response()->json($client_arr);
                    return redirect()->back()->
                    with('failure',"You dont have enough balance to send ".$b2ctrans." B2C Transactions. Topup an additional Ksh.".$balrem." to send Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                 
                     }
                     elseif($b2ctrans<1 && $b2btrans>0){
                      return redirect()->back()->
                     with('failure',"You dont have enough balance to send ".$b2btrans." B2B Transactions. Topup an additional Ksh.".$balrem." to send Kshs.".$total_amount.".Total Estimated Transaction charges are Ksh.".$mob_charge);
                     
                     }

                }

            
            }
        }
        else
        {
            return redirect()->route('customer.login')->with('failure','Sorry! Your account is inactive.');
        }
    
    }
    
    //payauditlog
    
    public function payauditLog($client_pay_id){
        
                $payLog = new AuditLog();
                $payLog->audit_module = "Customer";
                $payLog->audit_activity = "Payment of ID#: ".$client_pay_id ." approved by customer ID# " .Auth::user()->bulk_cust_id;
                $payLog->user_category = "Customer";
                $payLog->user_id = Auth::user()->bulk_cust_id;
                $payLog->save();
                
        
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        return view('bmviews.payments.details');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        return view('bmviews.payments.edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    //get logged in user clients
    public function getMyClients()
    {
        $id = Auth::user()->customer_cust_id;
        $data = CustomerClient::where('customer_cust_id',$id)->get();
        return $data;
    }
    //get logged in user grouos
    public function getMyGroups()
    {
        $id = Auth::user()->customer_cust_id;
        $data = CustomerGroup::where('customer_cust_id',$id)->get();
        return $data;
    }
    //generate the credentialkeypublic
    
    public function getEncryption(){
        $settng=Setting::where('setting_type','mpesa_b2c')->first();
        $shortcode="3013953";
        $initiatorname=$settng['setting_key'];
        $initiatorpassword=$settng['setting_value'];
        $pubkey= File::get(storage_path('app/production.cer'));
        openssl_public_encrypt($initiatorpassword, $output, $pubkey, OPENSSL_PKCS1_PADDING);
        $credential = base64_encode($output);
        
        return $credential;
    }
    
    //for b2b
     public function getEncryption2(){
        $settng=Setting::where('setting_type','mpesa_b2b')->first();
        $shortcode="3013953";
        $initiatorname=$settng['setting_key'];
        $initiatorpassword=$settng['setting_value'];
        $pubkey= File::get(storage_path('app/production.cer'));
        openssl_public_encrypt($initiatorpassword, $output, $pubkey, OPENSSL_PKCS1_PADDING);
        $credential = base64_encode($output);
        
        return $credential;
    }

    //perform the b2c transaction
    public function b2cMpesa($phone,$amount){
        
            $settng=Setting::where('setting_type','mpesa_b2c')->first();
            $InitiatorName=$settng['setting_key'];
            $SecurityCredential=$this->getEncryption();
            $CommandID="SalaryPayment";
            $Amount=$amount;
            $PartyA="3013953";
            $PartyB=$phone;
            $Remarks="Customer Transfer";
            $QueueTimeOutURL="https://lipa.mobisky.biz/test/callbackurl.php"; 
            $ResultURL="https://dash.mobisky.biz/api/b2c_result";
            $Occasion="Client Payment to - ".$phone;
            $mpesa=new Mpesa();
            $b2cTransaction=$mpesa->b2c($InitiatorName, $SecurityCredential, $CommandID, $Amount,
            $PartyA, $PartyB, $Remarks, $QueueTimeOutURL, $ResultURL, $Occasion);
            
            
            $return_object=json_decode($b2cTransaction,true);
            $array=explode(",",$return_object);
            //get the conversation and the originatorid for the transaction
            $conversationid_string= explode(":",ltrim($array[0], '{'));
           
            $originatorconversationid_string=explode(":",$array[1]);
            $c_rtrim=rtrim($conversationid_string[1],'"');
            $o_rtrim=rtrim($originatorconversationid_string[1],'"');
            $checksum_array['conversation_id']=str_replace(' ','',str_replace('"', '',$c_rtrim));
            $checksum_array['originator_id']=str_replace(' ','',str_replace('"', '',$o_rtrim));
            
            
            //save the originator response
            
            
            
            return $checksum_array;
            
            
     
    }
    //perform the b2b transaction
    public function b2bMpesa($amount,$paybill){
      
        $mpesa=new Mpesa();
        $settng=Setting::where('setting_type','mpesa_b2b')->first();
        $Initiator= $settng['setting_key'];
        $SecurityCredential=$this->getEncryption2();
        $CommandID="BusinessPayBill";
        $SenderIdentifierType= "4";
        $RecieverIdentifierType= "4";
        $Amount=$amount;  //"500"
        $PartyA="3013953";
        $PartyB=$paybill; //"603094"
        $AccountReference= "business Transfer";
        $Remarks= "business Transfer";   
        $QueueTimeOutURL="https://dash.mobisky.biz/test/callbackurl.php"; 
        $ResultURL="https://dash.mobisky.biz/api/b2b_result";
        $b2bTransaction=$mpesa->b2b($Initiator, $SecurityCredential, $Amount, $PartyA, $PartyB, $Remarks, $QueueTimeOutURL, $ResultURL, $AccountReference, $CommandID, $SenderIdentifierType, $RecieverIdentifierType);
       
        $return_object=json_decode($b2bTransaction,true);
        $checksum_array['originator_id']=$return_object['OriginatorConversationID'];
           
        $checksum_array['conversation_id']=$return_object['ConversationID'];
           
        return $checksum_array;
    }

    //get results of b2c
    public function b2cResult(Request $request){
               
                $conversationid=$request->Result['ConversationID'];;
                $originatorid=$request->Result['OriginatorConversationID'];
                $resultdesc = $request->Result['ResultDesc'];
                
                $orecord=Mpesaresponse::where(['originator_id'=>$originatorid,'conversation_id'=>$conversationid])->first();
                //get the customerid
                $cust_id=$orecord['cust_id'];
                $pay_id=$orecord['client_pay_id'];
                
                
                
               
               //update the client pay_id
               if($resultdesc=='The service request is processed successfully.')
               {
                   $transid=$request->Result['TransactionID'];
                    //amount received
                    $transamount=$request->Result['ResultParameters']['ResultParameter'][0]['Value'];
                    $transphone=substr($request->Result['ResultParameters']['ResultParameter'][4]['Value'],0,13);
                    $transdate=$request->Result['ResultParameters']['ResultParameter'][5]['Value'];
                    //determine if client registered
                    $state="";
                    if($request->Result['ResultParameters']['ResultParameter'][6]['Value'] == 'Y')
                    {   
                        $sts = 'salary_payment_registered_customer';
                        $state='Y';
                    }
                    else if($request->Result['ResultParameters']['ResultParameter'][6]['Value'] == 'N')
                    {
                        $sts = 'salary_payment_unregistered_customer';
                         $state='N';
                    }
                    //====get set rate======//
                    $setrate = Rate::where('rate_min','<=',$transamount)->where('rate_max','>=',$transamount)->where('rate_type',$sts)->pluck('total_charges');
                    
                    //====get 2% of transamount======//
                    //check for the existing records
                    //$transpercent = 0.2*$setrate[0];
                    //=========GET TOTAL Charges====//
                    $totalcharges=$setrate[0];
                    
                    
                    //get the wallet details
                    $customer_wallet=CustomerWallet::where(['customer_cust_id'=>$cust_id])->first();
                    $wallet_balance=$customer_wallet['cust_wallet_bal'];
                    
                    $newbalance=$wallet_balance-($transamount+$totalcharges);
                    
                    //update the wallet
                    $customer_wallet_update=CustomerWallet::where(['customer_cust_id'=>$cust_id])->update(['cust_wallet_bal'=>$newbalance]);
                    
                   //create a new wallet transaction
                   $trans['cust_wallet_cust_wallet_id']=$customer_wallet['cust_wallet_id'];
                   $trans['wallet_trans_type']='B2C';
                   $trans['wallet_trans_amount']=$transamount;
                   $trans['wallet_trans_status']=1;
                   $trans['wallet_trans_ref']=$transid;
                   $trans['wallet_client_username']=$transphone;
                   $trans['wallet_transact_contact']='';
                   $trans['is_registered']= $state;
                   $trans['wallet_trans_charge']=$totalcharges;
                   
                   //insert the record
                   CustomerWalletTransaction::create($trans);
                   CustomerClientPayment::where(['client_pay_id'=>$pay_id])->update(['client_pay_ref'=>$transid,'client_pay_status'=>'1']);
               }
               else
               {
                   //logged
                   $logerror=TransactionError::create(['client_pay_id'=>$pay_id,'error_message'=>$resultdesc]);
                   
                   //log the error
                   CustomerClientPayment::where(['client_pay_id'=>$pay_id])->update(['client_pay_ref'=>"System Error Occurred.Contact Support",'client_pay_status'=>'2']);
                   
                   
               }
        
      
            
        
       
    }

    //get the results of b2b
    public function b2bResult(Request $request){
       
                $conversationid=$request->Result['ConversationID'];;
                $originatorid=$request->Result['OriginatorConversationID'];
                $resultdesc = $request->Result['ResultDesc'];
                
                 //check for the existing records
                $orecord=Mpesaresponse::where(['originator_id'=>$originatorid,'conversation_id'=>$conversationid])->first();
                //get the customerid
                $cust_id=$orecord['cust_id'];
                $pay_id=$orecord['client_pay_id'];
                
                //get the tariff of the client
                $sts = $orecord['cust_tariff'];
                
                
                
                if($resultdesc=='The service request is processed successfully.')
                {
                
                
                $transid=$request->Result['TransactionID'];
                //amount received
                $transamount=$request->Result['ResultParameters']['ResultParameter'][5]['Value']; //was 2
                $transpaybill=substr($request->Result['ResultParameters']['ResultParameter'][6]['Value'],0,6);
                $transtime=$request->Result['ResultParameters']['ResultParameter'][4]['Value'];
             
               
                //deduct the amount based on the tariff
                
                $b2b_tariff = $sts;
                
                $mob_charge=0;
                
                        //get the rate level
                         $b2b_mpesa_level = B2BRate::where('rate_min','<=',$transamount)->where('rate_max','>=',$transamount)->where('tariff_id',$b2b_tariff)->pluck('rate_level');
                        //get the mpesa rate %
                        $b2b_mpesa_rate = B2BRate::where('rate_min','<=',$transamount)->where('rate_max','>=',$transamount)->where('tariff_id',$b2b_tariff)->pluck('rate_saf_charges');
                        
                        //get the mobisky %
                        $b2b_mobisky_rate = B2BRate::where('rate_min','<=',$transamount)->where('rate_max','>=',$transamount)->where('tariff_id',$b2b_tariff)->pluck('rate_charge');
                        
                        //create a variable to cater for the charges
                        $b2bcharge=0;
                        $mobiskycharge=0;
                     
                        
                        //know the rate max
                        if($b2b_mpesa_level[0]=="min"){
                           $b2bcharge= $b2b_mpesa_rate[0];
                           $mobiskycharge=0.00;
                           
                        }
                        elseif($b2b_mpesa_level[0]=="max"){
                           $b2bcharge= $b2b_mpesa_rate[0];
                           $mobiskycharge=($b2b_mobisky_rate[0]/100)*$b2bcharge;
                        }
                        elseif($b2b_mpesa_level[0]=="normal"){
                           //mpesa cut
                           $b2bcharge=($b2b_mpesa_rate[0]/100)*$transamount;
                           $mobiskycharge=($b2b_mobisky_rate[0]/100)*$b2bcharge;
                        }
                        //get the total charge
                         $mob_charge=$mob_charge+$mobiskycharge+$b2bcharge;
                         
                         $totalcharges=$mob_charge;
                         
                $mynewbalance=$transamount+$totalcharges;
                
               
                
                //get the wallet details
                $customer_wallet=CustomerWallet::where(['customer_cust_id'=>$cust_id])->first();
                $wallet_balance=$customer_wallet['cust_wallet_bal'];
                
                $newbalance=$wallet_balance-$mynewbalance;
              
                //update the wallet
                $customer_wallet_update=CustomerWallet::where(['customer_cust_id'=>$cust_id])->update(['cust_wallet_bal'=>$newbalance]);
                
                //create a new wallet transaction
                $trans['cust_wallet_cust_wallet_id']=$customer_wallet['cust_wallet_id'];
                $trans['wallet_trans_type']='B2B';
                $trans['wallet_trans_amount']=$transamount;
                $trans['wallet_trans_status']=1;
                $trans['wallet_trans_ref']=$transid;
                $trans['wallet_client_username']=$transpaybill;
                $trans['wallet_transact_contact']='';
                $trans['is_registered']='Y';
                $trans['wallet_trans_charge']=$totalcharges;
                
                //insert the record
                CustomerWalletTransaction::create($trans);
                
               //update the client pay_id
               
                CustomerClientPayment::where(['client_pay_id'=>$pay_id])->update(['client_pay_ref'=>$transid,'client_pay_status'=>'1']);
               }
               else
               {
                   //logged
                   $logerror=TransactionError::create(['client_pay_id'=>$pay_id,'error_message'=>$resultdesc]);
                   
                   CustomerClientPayment::where(['client_pay_id'=>$pay_id])->update(['client_pay_ref'=>"System Error Occurred.Contact Support",'client_pay_status'=>'2']);
               
                   
               }
                
                
    }
    //test b2b code//works very well
    public function testMpesa(){
        
    $mpesa=new Mpesa();
        $Initiator= "testapi401";
        $SecurityCredential="nVX0XyiBzA4LPv5x3wVEetfUD1TgQxRm6x+KhHwZaPYvFtq7yP6k718q6PWCbrrgpU5DcPeChnw8stOVNaEfWn0750Vdiiw98KMuaPSHtRI2YvqyGzXeJ/m/t4Z52imRr0xFyYTux5tMf1k2+LYx+uY3+Zovrvi5KwlwS+eA48ICfQWixEyHRqi9dp9tNM4D2mmzfRe2ykRKIzMWQ2tHUgAm8M5zw7l41jYTvKsu2FVgcwBTpMEe2i+j+N47pwyr7UXeFWBmiAmlhgzjsdA+kjLVeRrIFG4mi+g7O6iPLgl1KGzxinjFk7g6Ms8gRLeZ6etDYUeC73WrlRw2SKcwag==";
        $CommandID="BusinessPayBill";
        $SenderIdentifierType= "4";
        $RecieverIdentifierType= "4";
        $Amount="100";
        $PartyA="601401";
        $PartyB="603094";
        $AccountReference= "raftesting";
        $Remarks= "fuelpayment";   
        $QueueTimeOutURL=""; 
        $ResultURL="https://lipa.mobisky.biz/api/testb2bresult";
        $b2bTransaction=$mpesa->b2b($Initiator, $SecurityCredential, $Amount, $PartyA, $PartyB, $Remarks, $QueueTimeOutURL, $ResultURL, $AccountReference, $CommandID, $SenderIdentifierType, $RecieverIdentifierType);
            $return_object=json_decode($b2bTransaction,true);
            
            return response()->json($b2bTransaction);
    }
    
  public function testb2bResult(Request $request){
     
  }
  
  //test b2c code
  
  public function testB2CCode(){
            $InitiatorName="testapi401";
            $SecurityCredential="nVX0XyiBzA4LPv5x3wVEetfUD1TgQxRm6x+KhHwZaPYvFtq7yP6k718q6PWCbrrgpU5DcPeChnw8stOVNaEfWn0750Vdiiw98KMuaPSHtRI2YvqyGzXeJ/m/t4Z52imRr0xFyYTux5tMf1k2+LYx+uY3+Zovrvi5KwlwS+eA48ICfQWixEyHRqi9dp9tNM4D2mmzfRe2ykRKIzMWQ2tHUgAm8M5zw7l41jYTvKsu2FVgcwBTpMEe2i+j+N47pwyr7UXeFWBmiAmlhgzjsdA+kjLVeRrIFG4mi+g7O6iPLgl1KGzxinjFk7g6Ms8gRLeZ6etDYUeC73WrlRw2SKcwag==";
            $CommandID="PromotionPayment";
            $Amount="100";
            $PartyA="601401";
            $PartyB="254708374149";
            $Remarks="thanks";
            $QueueTimeOutURL="https://lipa.mobisky.biz/test/callbackurl.php"; 
            $ResultURL="https://lipa.mobisky.biz/api/testb2cresult";
            $Occasion="salaries";
            $mpesa=new Mpesa();
            $b2cTransaction=$mpesa->b2c($InitiatorName, $SecurityCredential, $CommandID, $Amount,
            $PartyA, $PartyB, $Remarks, $QueueTimeOutURL, $ResultURL, $Occasion);
            
             return response()->json($b2cTransaction);
  }
  
    public function testb2cResult(Request $request){
        
  }
  
  public function reversalTest(){
      $CommandID="TransactionReversal";
      $Initiator="testapi401";
      $SecurityCredential="nVX0XyiBzA4LPv5x3wVEetfUD1TgQxRm6x+KhHwZaPYvFtq7yP6k718q6PWCbrrgpU5DcPeChnw8stOVNaEfWn0750Vdiiw98KMuaPSHtRI2YvqyGzXeJ/m/t4Z52imRr0xFyYTux5tMf1k2+LYx+uY3+Zovrvi5KwlwS+eA48ICfQWixEyHRqi9dp9tNM4D2mmzfRe2ykRKIzMWQ2tHUgAm8M5zw7l41jYTvKsu2FVgcwBTpMEe2i+j+N47pwyr7UXeFWBmiAmlhgzjsdA+kjLVeRrIFG4mi+g7O6iPLgl1KGzxinjFk7g6Ms8gRLeZ6etDYUeC73WrlRw2SKcwag==";
      $TransactionID="ODL71HBSVJ";
      $Amount="100";
      $ReceiverParty="601401";
      $RecieverIdentifierType="4";   ////1=MSISDN, 2=Till_Number, 4=Shortcode
      $ResultURL="https://lipa.mobisky.biz/api/testreversalresult";
      $QueueTimeOutURL="https://lipa.mobisky.biz/test/callbackurl.php";
      $Remarks="thanks";
      $Occasion="okay";
      $mpesa=new Mpesa();
      $reversalTransaction=$mpesa->reversal($CommandID, $Initiator, $SecurityCredential, $TransactionID, $Amount, $ReceiverParty, $RecieverIdentifierType, $ResultURL, $QueueTimeOutURL, $Remarks, $Occasion);
      return response()->json($reversalTransaction);
  }
  
    public function reversalTestResult(Request $request){
      
  }
   
   //check transaction status -WORKS VERY WELL
   public function checkStatus(){
       
       $Initiator="testapi401";
       $SecurityCredential="nVX0XyiBzA4LPv5x3wVEetfUD1TgQxRm6x+KhHwZaPYvFtq7yP6k718q6PWCbrrgpU5DcPeChnw8stOVNaEfWn0750Vdiiw98KMuaPSHtRI2YvqyGzXeJ/m/t4Z52imRr0xFyYTux5tMf1k2+LYx+uY3+Zovrvi5KwlwS+eA48ICfQWixEyHRqi9dp9tNM4D2mmzfRe2ykRKIzMWQ2tHUgAm8M5zw7l41jYTvKsu2FVgcwBTpMEe2i+j+N47pwyr7UXeFWBmiAmlhgzjsdA+kjLVeRrIFG4mi+g7O6iPLgl1KGzxinjFk7g6Ms8gRLeZ6etDYUeC73WrlRw2SKcwag==";
       $CommandID="TransactionStatusQuery";
       $TransactionID="ODL31HBSUL";
       $PartyA="601401";
       $IdentifierType="4";
       $ResultURL="https://lipa.mobisky.biz/api/teststatusresult";
       $QueueTimeOutURL="https://lipa.mobisky.biz/test/callbackurl.php";
       $Remarks="thanks";
       $Occasion="wrong receiver";
     
     $mpesa=new Mpesa();
     $transstatus=$mpesa->transactionStatus($Initiator, $SecurityCredential, $CommandID, $TransactionID, $PartyA, $IdentifierType, $ResultURL, $QueueTimeOutURL, $Remarks, $Occasion);
     return response()->json($transstatus);
     
       
   }
   
    public function testCheckStatus(Request $request){
       
  }
}
