<?php

namespace App\Http\Controllers;

use App\Currency;
use Illuminate\Http\Request;
use Auth;
use App\GeneralSettings;
use App\Internet;
use App\Internetbundle;
use App\Message;
use App\Bill;
use App\Plan;
use App\Power;
use App\Decoder;
use App\Voucher;
use App\Decodersub;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Hash;
use File;
use Carbon\Carbon;
use Image;
use Mail;
use App\User;
use Session;

class MerchantController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


      public function convertairtime()
    {
        $data['page_title'] = 'Convert Airtime';
        $data['network'] = Internet::whereSwap(1)->latest()->get();
        return view('user.merchant.convert-airtime', $data);
    }


    public function convertnow(Request $request)
    {
        $this->validate($request, [
            'phone' => 'required|numeric',
            'phone2' => 'required|numeric',
            'network' => 'required|numeric',
            'amount' => 'required|numeric|min:1000',

        ]);
        $user = Auth::user();
        $basic = GeneralSettings::first();
        $network = Internet::find($request->network);
        $api_id = $basic->merchantid;
        $api_key = $basic->merchantkey;
          $trx = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') , 0 , 10 );


        if(isset($request->pin)){
         try {
            $c_password = Auth::user()->transpin;
             if (Hash::check($request->pin, $c_password)) {

            } else {
                return back()->with('danger', 'Transaction Password Is Incorrect');
            }

        } catch (\PDOException $e) {
            return back()->with('danger', $e->getMessage());
        }

        }

        if($request->phone != $request->phone2){


            return back()->with('danger', 'You phone number confrimation is wrong. Please try again');
        }



            Message::create([
                    'user_id' => $user->id,
                    'title' => 'Airtime Conversion',
                    'details' => 'Your '.$network->name.' Airtime conversion from phone number '.$request->phone.' has been successfully sent to the admin for confirmation. The unit price of your airtime will be credited to your deposit balance once we verify your conversion, Thank you for choosing '.$basic->sitename.'',
                    'admin' => 1,
                    'status' =>  0
                ]);


              Bill::create([
                    'user_id' => $user->id,
                    'charge' => $request->amount * $network->rate/100,
                    'amount' => $request->amount,
                    'phone' => $request->phone,
                    'trx' => $trx,
                    'network' => $request->network,
                    'newbalance' => $user->balance,
                    'type' => 5,
                    'status' =>  0
                ]);


                $data = array(

                "name"=> $user->username,
                "email"=> $user->email,
                "body"=> "Your '.$network->name.' Airtime conversion from phone number '.$request->phone.' has been successfully sent to the admin for confirmation. The unit price of your airtime will be credited to your deposit balance once we verify your conversion, Thank you for choosing '.$basic->sitename.'",
                "heading"=> "Airtime Conversion",
                );



      Mail::send('mail', $data, function($message) {
    $user = User::find(Auth::user()->id);
    $message->to($user->email, $user->username)->subject('Airtime Conversion');
});



        $notification =  array('message' => 'Airtime Conversion Process Was Successful !!', 'alert-type' => 'success');
        return back()->with($notification);
	}


    public function printvoucher()
    {
        $data['page_title'] = 'Generate Voucher';
        $data['network'] = Internet::whereVoucher(1)->latest()->get();

        return view('user.merchant.voucherprint', $data);
    }

     public function printvouchernow(Request $request)
    {

       $basic = GeneralSettings::first();
       $this->validate($request, [
            'quantity' => 'required|numeric',
            'network' => 'required|numeric',
            'amount' => 'required|numeric|min:100',

        ]);
        $user = Auth::user();
        $basic = GeneralSettings::first();
        $network = Internet::find($request->network);
        $api_id = env('CLUBKUSERID');
        $api_key = env('CLUBKAPIKEY');

        $cost = $request->amount * $request->quantity;

        if (!$network)
        {
        return back()->with('danger', 'Invalid Network Request');
        }

        if ($user->balance < $cost){
        return back()->with('danger', 'You dont have enough funds in your deposit wallet to complete this transaction');
        }

        if(isset($request->pin)){
         try {
            $c_password = Auth::user()->transpin;
             if (Hash::check($request->pin, $c_password)) {

            } else {
                return back()->with('danger', 'Transaction Password Is Incorrect');
            }

        } catch (\PDOException $e) {
            return back()->with('danger', $e->getMessage());
        }

        }


$trx = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') , 0 , 10 );

$url = "https://www.nellobytesystems.com/APIEPINV1.asp?UserID=".$api_id."&APIKey=".$api_key."&MobileNetwork=".$request->network."&Value=".$request->amount."&Quantity=".$request->quantity."&RequestID=".$trx."&CallBackURL=callback_url";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Accept: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
$return = json_decode($resp,true);
//return $return;

            $user->balance -= $cost;
            $user->save();



        $auth = Auth::user();
        $to_name = $auth->username;
        $sitename = env('APP_NAME');
        $to_email = $auth->email;
       /* $heading = "Recharge Printing";
        $data = array("name"=> $auth->username,"heading"=>"Recharge Printing", "body" => "Your ".$network->name." ".$basic->currency." ".$request->amount." voucher printing of ".$request->quantity." units has been successfully processed. Thank you for choosing ".$basic->sitename."");

        Mail::send("mail", $data, function($message) use ($to_name,  $heading, $to_email) {
        $message->to($to_email, $to_name,  $heading)
        ->subject("Transaction Successful");

         $message->from(env('MAIL_USERNAME'),env('APP_NAME'));
        });*/

         Voucher::create([
                    'user_id' => $auth->id,
                    'amount' => $request->amount,
                    'trx' => $trx,
                    'network' => $network->name,
                    'quantity' => $request->quantity,
                ]);



        $notification =  array('message' => 'Airtime Purchased Successfully !!', 'alert-type' => 'success');
        return back()->with($notification);

}


    public function reprintvoucher()
    {

        $user = Auth::user();
        $data['page_title'] = 'Generated Voucher';
        $data['log'] = Voucher::whereUserId($user->id)->latest()->get();

        return view('user.merchant.voucher-log', $data);
    }




    public function reprintvouchernow($id)
    {

        $user = Auth::user();
        $data['page_title'] = 'Print Voucher';
        $voucher = Voucher::whereUserId($user->id)->whereTrx($id)->latest()->first();

        if(!$voucher)
        {
        return back()->with('danger', 'Invalid Voucher Batch Number');
        }

  $api_id = env('CLUBKUSERID');
  $api_key = env('CLUBKAPIKEY');

$url = "https://www.nellobytesystems.com/APIQueryV1.asp?UserID=".$api_id."&APIKey=".$api_key."&RequestID=".$id."";
$obj = json_decode(file_get_contents($url), true);

        $data['voucher'] = $voucher;
        $data['log'] = $obj['TXN_EPIN'];
        return view('user.merchant.voucher-reprint', $data);
    }






    public function mobilerecharge()
    {
        $data['page_title'] = 'Mobile Recharge';
        $data['network'] = Internet::wherePhone(1)->latest()->get();

        return view('user.merchant.mobile', $data);
    }




    public function rechargenow(Request $request)
    {
        $this->validate($request, [
            'phone' => 'required|numeric',
            'network' => 'required',
            'amount' => 'required|numeric|min:50',

        ]);
        $user = Auth::user();
        $basic = GeneralSettings::first();
        $network = Internet::whereSymbol($request->network)->first();

        if(!$network)
        {
         return back()->with('danger', 'Invalid Network');
        }
        $api_id = $basic->merchantid;
        $api_key = $basic->merchantkey;

        if ($user->balance < $request->amount)
        {
        return back()->with('danger', 'You dont have enough funds in your deposit wallet to complete this transaction');
        }

        if(isset($request->pin))
        {
         try {
            $c_password = Auth::user()->transpin;
             if (Hash::check($request->pin, $c_password)) {

            } else {
                return back()->with('danger', 'Transaction Password Is Incorrect');
            }

        } catch (\PDOException $e) {
            return back()->with('danger', $e->getMessage());
        }

        }

        $mode = env('MODE');
        $username = env('VTPASSUSERNAME');
        $password = env('VTPASSPASSWORD');
        $str = $username.':'.$password;
        $auth = base64_encode($str);

$trx = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') , 0 , 10 );
 if($mode == 0)
        {
        $url = 'https://sandbox.vtpass.com/api/pay';
        }
        else
        {
        $url = 'https://vtpass.com/api/pay';
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>'{
        "amount": "'.$request->amount.'",
        "phone": "'.$request->phone.'",
        "serviceID": "'.$request->network.'",
        "request_id": "'.$trx.'"
        }',
      CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth,
    'Content-Type: application/json',
      ),
    ));

    $resp = curl_exec($curl);
    $reply = json_decode($resp, true);
    curl_close($curl);
     if(!isset($reply['code']))
     {
    return back()->with('danger', 'Sorry, We cant process tbis payment at the moment');
    }


    if($reply['code'] == 014)
     {
    return back()->with('danger', $reply['response_description'] );
    }

    if($reply['code'] != 000)
     {
    return back()->with('danger', 'Sorry, We cant process tbis payment at the moment');
    }

     if($reply['code'] == 000)
     {

		    $basic = GeneralSettings::first();
		    $plan = Plan::whereId($user->plan_id)->first();
        if($plan)
        {
        $discount = $plan->discount*$request->amount/100;
        }
        else
        {
        $discount = 0;
        }

		$pay = $request->amount - $discount;

		 	$user->balance = $user->balance - $pay;
            $user->save();

            Message::create([
                    'user_id' => $user->id,
                    'title' => 'Phone Recharged',
                    'details' => 'Your Phone Number'.$request->phone.' has been successfully recharged with the sum of '.$basic->currency_sym.' '.$request->amount.' worth of  '.$network->name.' recharge card, Thank you for choosing '.$basic->sitename.'',
                    'admin' => 1,
                    'status' =>  0
                ]);

             $trx = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') , 0 , 10 );

              Bill::create([
                    'user_id' => $user->id,
                    'amount' => $request->amount,
                    'phone' => $request->phone,
                    'trx' => $trx,
                    'network' => $request->network,
                    'newbalance' => $user->balance,
                    'type' => 1,
                    'status' =>  1
                ]);

        $auth = Auth::user();
        $to_name = $auth->username;
        $sitename = env('APP_NAME');
        $to_email = $auth->email;
        $heading = "Airtime Recharge";
        $data = array("name"=> $auth->username,"heading"=>"Airtime Recharge", "body" => "Your ".$network->name." number ".$request->phone." has been successfully recharged with ".$basic->currency."".$request->amount." Recharge Card. Thank you for choosing ".$basic->sitename."");

        /*
        Mail::send("mail", $data, function($message) use ($to_name,  $heading, $to_email) {
        $message->to($to_email, $to_name,  $heading)
        ->subject("Trnasaction Successful");
         $message->from(env('MAIL_USERNAME'),env('APP_NAME'));
        });*/

        $notification =  array('message' => 'Airtime Purchased Successfully !!', 'alert-type' => 'success');
        return back()->with($notification);
        }
         return back()->with('danger', 'Sorry, We cant process tbis payment at the moment');

}




     public function cabletv()
    {
        $data['page_title'] = 'Cable TV';
        $data['network'] = Decoder::whereStatus(1)->latest()->get();
        $data['bill'] = Decodersub::whereStatus(1)->get();
        return view('user.merchant.cabletv', $data);
    }

      public function cabletvpost(Request $request)
    {
        $request->validate([
            'network' => 'required',
        ]);
         Session::put('Track', $request->network);

       return redirect()->route('cabletvpost2');

    }

        public function cabletvpost2()
    {
        $data['page_title'] = 'Cable TV';
        $track = Session::get('Track');
        $data['network'] = Decoder::whereCode($track)->first();
        //$data['bill'] = Decodersub::whereStatus(1)->get();

        $mode = env('MODE');
        if($mode == 1)
        {
        $url = "https://sandbox.vtpass.com/api/service-variations?serviceID=".$data['network']->symbol;
        }
        else
        {
        $url = "https://sandbox.vtpass.com/api/service-variations?serviceID=".$data['network']->symbol;
        }





$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Accept: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
//var_dump($resp);

 $return = json_decode($resp,true);

 if(!isset($return['response_description']))
 {
 return back()->with('danger', 'API Response Error');
 }

 if(!isset($resp))
 {
 return back()->with('danger', 'API Response Error');
 }

 if($return['response_description'] != '000')
 {
 return back()->with('danger', 'Sorry we cant fetch cable tv plans at the moment');
 }




        $basic = GeneralSettings::first();

        $data['planname'] = $return['content']['ServiceName'];
        $data['plan'] = $return['content']['varations'];
        $data['discount'] =  env('CABLETVDISCOUNT');
        //return $data['plan'];

        return view('user.merchant.cabletv_buy', $data);
    }


 public function cabletvpost3(Request $request)
    {
        $this->validate($request, [
            'plan' => 'required',
            'decoder' => 'required|numeric',
            'number' => 'required|numeric',

        ]);
        $user = Auth::user();
        $basic = GeneralSettings::first();
       //return $request->plan;
        $total = $request->amount+100;
        if ($user->balance < $total){
        return back()->with('danger', 'You dont have enough funds in your deposit wallet to complete this transaction');
        }

        if(isset($request->pin)){
         try {
            $c_password = Auth::user()->transpin;
             if (Hash::check($request->pin, $c_password)) {

            } else {
                return back()->with('danger', 'Transaction Password Is Incorrect');
            }

        } catch (\PDOException $e) {
            return back()->with('danger', $e->getMessage());
        }

        }



        $decoder = Decoder::whereCode($request->decoder)->first();
        $mode = env('MODE');
        $username = env('VTPASSUSERNAME');
        $password = env('VTPASSPASSWORD');
        $str = $username.':'.$password;
        $auth = base64_encode($str);

        //return $decoder->symbol;

         if($mode == 0)
        {
        $url = 'https://sandbox.vtpass.com/api/merchant-verify';
        }
        else
        {
        $url = 'https://vtpass.com/api/merchant-verify';
        }

        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>'{
         "billersCode": "'.$request->number.'",
        "serviceID": "'.$decoder->symbol.'"
        }',
      CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth,
    'Content-Type: application/json',
      ),
    ));

    $resp = curl_exec($curl);
    $reply = json_decode($resp, true);
    curl_close($curl);
    //return  $resp;

    if($reply['code'] != 000) {
    return back()->with('danger', 'Sorry, We cant validate this decoder/IUC number at the moment');
    }

          //$decoder = Decodersub::whereCode($request->decoder)->first();
         Session::put('plan', $request->plan);
		 Session::put('name', $reply['content']['Customer_Name']);
		 Session::put('number', $request->number);
		 Session::put('decoder', $decoder->name);
		 Session::put('planname', $request->planname);
		 Session::put('amount', $request->amount);
         Session::put('trx', substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') , 0 , 6 ));
		 return redirect()->route('cabletvpay');
	}

         public function cabletvpay()
    {

        $data['page_title'] = 'Cable TV';
        $data['name'] = Session::get('name');
        $data['decoder'] = Session::get('decoder');
        $data['amount'] = Session::get('amount');
        $data['plan'] = Session::get('plan');
        $data['planname'] = Session::get('planname');
        $data['number'] = Session::get('number');
        $data['trxcode'] = Session::get('trx');
        $data['time'] = Carbon::now();

        //$decoder = Decodersub::whereCode($data['decoder'])->wherePlan($data['plan'])->first();
        $data['amount'] =  $data['amount'];
        $data['plan2'] = $data['planname'];
        $data['plan'] = $data['plan'];
        $data['power'] = Decoder::whereSymbol($data['decoder'])->first();

        return view('user.merchant.cabletvpay', $data);
    }



        public function cabletvpay2(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
            'amount' => 'required|numeric',
            'plan' => 'required',
            'number' => 'required|numeric',
            'trx' => 'required|',

        ]);
        $user = Auth::user();
        $basic = GeneralSettings::first();
        $api_id = $basic->merchantid;
        $api_key = $basic->merchantkey;

        //return $request->plan;

        $decoder = Decoder::whereSymbol($request->code)->first();
        $basic = GeneralSettings::first();
        $plan = Plan::whereId($user->plan_id)->first();
        if($plan)
        {
        $discount = $plan->discount*$power->fee/100;
        }
        else
        {
        $discount = 0;
        }

		$pay = $request->amount - $discount;


         $mode = env('MODE');

        $username = env('VTPASSUSERNAME');
        $password = env('VTPASSPASSWORD');
        $str = $username.':'.$password;
        $auth = base64_encode($str);



        if ($user->balance < $pay){
        session()->flash('danger', 'You dont have enough funds in your deposit wallet to complete this transaction');

         return redirect()->route('home');

        }
 if($mode == 0)
        {
        $url = 'https://sandbox.vtpass.com/api/pay';
        }
        else
        {
        $url = 'https://vtpass.com/api/pay';
        }
        $code = getTrx();
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>'{
         "billersCode": "'.$request->number.'",
         "variation_code": "'.$request->plan.'",
         "phone": "'.$user->phone.'",
        "serviceID": "'.$decoder->symbol.'",
        "request_id": "'.$request->trx.'"
        }',
      CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth,
    'Content-Type: application/json',
      ),
    ));

    $resp = curl_exec($curl);
    $reply = json_decode($resp, true);
    curl_close($curl);
    //return  $resp;

    if(!isset($reply['code']))
     {
    return back()->with('danger', 'Sorry, We cant process tbis payment at the moment');
    }


    if($reply['code'] == 014)
     {
    return back()->with('danger', $reply['response_description'] );
    }

    if($reply['code'] != 000)
     {
    return back()->with('danger', 'Sorry, We cant process tbis payment at the moment');
    }

     if($reply['code'] == 000)
     {
    	    $basic = GeneralSettings::first();
		    $user->balance -= $pay;
            $user->save();
            $paid = $request->amount - $pay;



		   Message::create([
                    'user_id' => $user->id,
                    'title' => 'Paid TV Subscription',
                    'details' => 'Your '.$decoder->name.' decoder with decoder Number '.$request->number.' has been successfully recharged with '.$request->plan.'  Subscription Plan. Thank you for choosing '.$basic->sitename.'',
                    'admin' => 1,
                    'status' =>  0
                ]);


              Bill::create([
                    'user_id' => $user->id,
                    'amount' => $request->amount2,
                    'phone' => $request->number,
                    'trx' => $request->trx,
                    'network' => $request->code,
                    'newbalance' => $user->balance,
                    'plan' => $request->plan,
                    'type' => 4,
                    'status' =>  1
                ]);


        $auth = Auth::user();
        $to_name = $auth->username;
        $sitename = env('APP_NAME');
        $to_email = $auth->email;
        $heading = "Decoder Recharge";
        $data = array("name"=> $auth->username,"heading"=>"Decoder Recharge", "body" => "Your ".$power->name." decoder with decoder Number ".$request->number." has been successfully recharged with ".$decoder->name."  Subscription Plan. Thank you for choosing ".$basic->sitename."");

        Mail::send("mail", $data, function($message) use ($to_name,  $heading, $to_email) {
        $message->to($to_email, $to_name,  $heading)
        ->subject("Trnasaction Successful");

         $message->from(env('MAIL_USERNAME'),env('APP_NAME'));
        });

        session()->flash('success', $reply['response_description']);

         return redirect()->route('home');

}







	}







     public function internetdata()
    {
        $data['page_title'] = 'Internet Data';
        $data['network'] = Internet::whereStatus(1)->latest()->get();
        return view('user.merchant.internet', $data);
    }





    public function internetdatapost(Request $request)
    {
        $request->validate([
            'network' => 'required',
        ]);
         Session::put('Track', $request->network);


       return redirect()->route('internetdata2');

    }

       public function internetdata2()
    {
        $data['page_title'] = 'Internet Data';
        $track = Session::get('Track');

        $basic = GeneralSettings::first();
        $curl = curl_init();
        //return $track;


        $data['network'] = Internet::whereCode($track)->first();
        //$data['data'] = $plans;
        $data['plans'] = Internetbundle::whereCode($track)->whereStatus(1)->get();

         $user = Auth::user();
         $data['discount'] = 0;
        return view('user.merchant.internet_buy', $data);
    }


    public function internetdatapost2(Request $request)
    {
        $this->validate($request, [
            'phone' => 'required|numeric',
            'network' => 'required',
            'plan' => 'required',

        ]);
        $user = Auth::user();
        $basic = GeneralSettings::first();
        $network = Internet::whereCode($request->network)->first();
        $plan = Internetbundle::whereCode($request->network)->whereData_id($request->plan)->first();
        //return $request->plan;

         if (!$plan)
         {
        return back()->with('danger', 'Invalid Internet Data Plan');
        }
        if ($user->balance < $plan->cost){
        return back()->with('danger', 'You dont have enough funds in your deposit wallet to complete this transaction');
        }

        if(isset($request->pin)){
         try {
            $c_password = Auth::user()->transpin;
             if (Hash::check($request->pin, $c_password)) {

            } else {
                return back()->with('danger', 'Transaction Password Is Incorrect');
            }

        } catch (\PDOException $e) {
            return back()->with('danger', $e->getMessage());
        }

        }
  $husmotoken = env('HUSMOTOKEN');

$url = "https://www.husmodata.com/api/data/";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Accept: application/json",
   "Authorization: Token ".$husmotoken."",
   "Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = <<<DATA
{
"network": "$request->network",
"mobile_number": "$request->phone",
"plan": "$request->plan",
"Ported_number": "false"}
DATA;

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
$rep=json_decode($resp, true);


 $plan = Plan::whereId($user->plan_id)->first();
        if($plan)
        {
        $discount = $plan->discount*$plan->amount/100;
        }
        else
        {
        $discount = 0;
        }

		$pay = $request->amount - $discount;


		 	$user->balance = $user->balance - $pay;
            $user->save();

            Message::create([
                    'user_id' => $user->id,
                    'title' => 'Data Bundle Recharged',
                    'details' => 'Your Phone Number'.$request->phone.' has been successfully recharged with '.$network->name.$plan->name.' Data Bundle, Thank you for choosing '.$basic->sitename.'',
                    'admin' => 1,
                    'status' =>  0
                ]);

   $trx = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') , 0 , 10 );

              Bill::create([
                    'user_id' => $user->id,
                    'amount' => $plan->cost,
                    'phone' => $request->phone,
                    'trx' => $trx,
                    'network' => $network->name,
                    'accountname' => $plan->name,
                    'newbalance' => $user->balance,
                    'type' => 2,
                    'status' =>  1
                ]);


       /* $auth = Auth::user();
        $to_name = $auth->username;
        $sitename = env('APP_NAME');
        $to_email = $auth->email;
        $heading = "Data Bundle Subscription";
        $data = array("name"=> $auth->username,"heading"=>"Data Bundle Subscription", "body" => "Your ".$network->name." number ".$request->phone." has been successfully recharged with ".$request->amount."Worth of Internet Data Plan. Thank you for choosing ".$basic->sitename."");

        Mail::send("mail", $data, function($message) use ($to_name,  $heading, $to_email) {
        $message->to($to_email, $to_name,  $heading)
        ->subject("Trnasaction Successful");

         $message->from(env('MAIL_USERNAME'),env('APP_NAME'));
        });*/

       session()->flash('success', 'Data Subscription Was Successful');

         return redirect()->route('home');


}





	 public function electricity()
    {
        $data['page_title'] = 'Electricity Bill';
        $data['power'] = Power::whereStatus(1)->latest()->get();
        return view('user.merchant.power', $data);
    }



    public function electricitypost(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
            'amount' => 'required|numeric',
            'metertype' => 'required',
            'number' => 'required|numeric',

        ]);
        $user = Auth::user();
        $basic = GeneralSettings::first();

        if(isset($request->pin))
        {
         try {
            $c_password = Auth::user()->transpin;
             if (Hash::check($request->pin, $c_password)) {

            } else {
                return back()->with('danger', 'Transaction Password Is Incorrect');
            }

        } catch (\PDOException $e) {
            return back()->with('danger', $e->getMessage());
        }

        }
        $mode = env('MODE');
        $username = env('VTPASSUSERNAME');
        $password = env('VTPASSPASSWORD');
        $str = $username.':'.$password;
        $auth = base64_encode($str);


 if($mode == 0)
        {
        $url = 'https://sandbox.vtpass.com/api/merchant-verify';
        }
        else
        {
        $url = 'https://vtpass.com/api/merchant-verify';
        }

        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>'{
         "billersCode": "'.$request->number.'",
        "serviceID": "'.$request->code.'",
        "type": "'.$request->metertype.'"
        }',
      CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth,
    'Content-Type: application/json',
      ),
    ));

    $resp = curl_exec($curl);
    $reply = json_decode($resp, true);
    curl_close($curl);
    //return  $resp;

     if(!isset($reply['code']))
     {
    return back()->with('danger', 'Sorry, We cant process tbis payment at the moment');
    }



     if($reply['code']== 000)
     {

    if(!isset($reply['content']['Customer_Name']))
     {
    $notify[] = ['warning', 'Sorry, We cant validate this Meter Number at the moment'];
    return back()->withNotify($notify);
    }

     if(isset($reply['content']['Customer_Name']))
     {


		 Session::put('code', $request->code);
		 Session::put('name', $reply['content']['Customer_Name'] );
		 Session::put('number', $request->number);
		 Session::put('amount', $request->amount);
		 Session::put('type', $request->metertype);

         Session::put('trx', substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') , 0 , 6 ));
		 return redirect()->route('powerpay');

    }

    }

     $notify[] = ['warning', 'Sorry, We cant process this payment'];
    return back()->withNotify($notify);

    	}



	 public function electricitypay()
    {
        $data['page_title'] = 'Electricity Bill';
        $data['code'] = Session::get('code');
        $data['type'] = Session::get('type');
        $data['name'] = Session::get('name');
        $data['amount'] = Session::get('amount');
        $data['number'] = Session::get('number');
        $data['trxcode'] = Session::get('trx');
         $data['time'] = Carbon::now();
        $data['power'] = Power::wherePid($data['code'])->first();
        return view('user.merchant.powerpay', $data);
    }

       public function electricitypay2(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
            'amount' => 'required|numeric',
            'type' => 'required',
            'number' => 'required|numeric',

        ]);
        $user = Auth::user();
        $basic = GeneralSettings::first();
        $api_id = $basic->merchantid;
        $api_key = $basic->merchantkey;


        if ($user->balance < $request->amount){
        session()->flash('danger', 'You dont have enough funds in your deposit wallet to complete this transaction');

         return redirect()->route('home');

        }


         $power = Power::wherePid($request->code)->first();
        $mode = env('MODE');
        $username = env('VTPASSUSERNAME');
        $password = env('VTPASSPASSWORD');
        $str = $username.':'.$password;
        $auth = base64_encode($str);


        if($mode == 0)
        {
        $url = 'https://sandbox.vtpass.com/api/pay';
        }
        else
        {
        $url = 'https://vtpass.com/api/pay';
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>'{
         "billersCode": "'.$request->number.'",
         "variation_code": "'.$request->type.'",
         "phone": "'.$user->phone.'",
        "serviceID": "'.$request->code.'",
        "amount": "'.$request->amount2.'",
        "request_id": "'.$request->trx.'"
        }',
      CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth,
    'Content-Type: application/json',
      ),
    ));

    $resp = curl_exec($curl);
    $reply = json_decode($resp, true);
    curl_close($curl);

    //return $resp;

     if($reply['code'] == 014)
     {
    return back()->with('danger', $reply['response_description'] );
    }



    if($reply['code'] != 000) {
    $notify[] = ['warning', 'Sorry, We cant process tbis payment at the moment'];
    return back()->withNotify($notify);
    }

    if($reply['code']== 000) {

       $plan = Plan::whereId($user->plan_id)->first();
        if($plan)
        {
        $discount = $plan->discount*$power->fee/100;
        }
        else
        {
        $discount = 0;
        }

		$pay = $request->amount2 - $discount;

//       $pay = $request->amount2;
		$user->balance = $user->balance - $pay;
        $user->save();
        $power = Power::wherePid($request->code)->first();


		   Message::create([
                    'user_id' => $user->id,
                    'title' => 'Paid Electricity Bill',
                    'details' => 'Your Electricity Meter with meter Number '.$request->number.' has been successfully recharged with '.$request->amount2.'  '.$basic->currency.' power units from '.$power->name.', Thank you for choosing '.$basic->sitename.'',
                    'admin' => 1,
                    'status' =>  0
                ]);


              Bill::create([
                    'user_id' => $user->id,
                    'amount' => $request->amount2,
                    'phone' => $request->number,
                    'trx' => $request->trx,
                    'network' => $request->code,
                    'newbalance' => $user->balance,
                    'plan' => $request->type,
                    'accountname' => 'Customer Name: '.$reply['customerName'].'<br> Address: '.$reply['customerAddress'].'<br>Meter Number: '.$reply['content']['transactions']['unique_element'],
                    'accountnumber' => 'Token: '.$reply['token'].'<br> Units: '.$reply['units'],
                    'type' => 3,
                    'status' =>  1
                ]);

        $auth = Auth::user();
        $to_name = $auth->username;
        $sitename = env('APP_NAME');
        $to_email = $auth->email;
        $heading = "Electricity BIll Payment";
        $data = array("name"=> $auth->username,"heading"=>"Electricity BIll Payment", "body" => "Your Electricity Meter with meter Number ".$request->number." has been successfully recharged with ".$request->amount."".$basic->currency." power units from ".$power->name.", Thank you for choosing ".$basic->sitename."");

        Mail::send("mail", $data, function($message) use ($to_name,  $heading, $to_email) {
        $message->to($to_email, $to_name,  $heading)
        ->subject("Trnasaction Successful");

         $message->from(env('MAIL_USERNAME'),env('APP_NAME'));
        });


            return redirect()->route('electricity')->with("success", "Transaction Successful");
        }



        }











     public function rechargelog()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Recharge Log';
        $data['log'] = Bill::wheretype(1)->whereUser_id($user->id)->latest()->paginate(10);
        return view('user.merchant.recharge-log', $data);
    }




     public function conversionlog()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Conversion Log';
        $data['log'] = Bill::wheretype(5)->whereUser_id($user->id)->latest()->paginate(10);
        return view('user.merchant.conversion-log', $data);
    }

       public function conversionsearch(Request $request)
    {
        $request->validate([
            'trx' => 'required',
        ]);
        $data['page_title'] = 'Conversion Log Result';
        $user = User::find(Auth::user()->id);
          $count = Bill::whereTrx($request->trx)->wheretype(5)->whereUser_id($user->id)->count();

       if($count > 0){

         $data['log'] = Bill::whereTrx($request->trx)->wheretype(5)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.conversion-log', $data);
        }
          else
        {
        return back()->with('alert', 'There is no transaction with this entry .');
        }}


        public function conversionsearchget()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Conversion Log';
        $track = Session::get('Track');



       $count = Bill::whereTrx($track)->wheretype(5)->whereUser_id($user->id)->count();

       if($count > 0){

         $data['log'] = Bill::whereNetwork($track)->wheretype(5)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.conversion-log', $data);
        }
          else
        {
        return back()->with('alert', 'There is no transaction with this entry .');
        }}







     public function internetlog()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Internet Data Subscriptions';
        $data['log'] = Bill::wheretype(2)->whereUser_id($user->id)->latest()->paginate(10);
        return view('user.merchant.internet-log', $data);
    }



     public function tvlog()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Cable TV Subscriptions';
        $data['log'] = Bill::wheretype(4)->whereUser_id($user->id)->latest()->paginate(10);
        return view('user.merchant.tv-log', $data);
    }


     public function powerlog()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Electricity Bill Payments';
        $data['log'] = Bill::wheretype(3)->whereUser_id($user->id)->latest()->paginate(10);
        return view('user.merchant.power-log', $data);
    }

       public function rechargesearch(Request $request)
    {
        $request->validate([
            'trx' => 'required',
        ]);
         Session::put('Track', $request->trx);

       return redirect()->route('rechargesearchget');

    }

        public function rechargesearchget()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Internet Data';
        $track = Session::get('Track');


       if($track == 'MTN')
       {
       $code = 01;
       $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}
        if($track == 'mtn')
       {
       $code = 01;
        $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}
          if($track == 'glo')
       {
       $code = 02;
         $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}
          if($track == 'GLO')
       {
       $code = 02;
         $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

        if($track == 'GLOBACOM')
            if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}

            if($track == 'GLOBACOM')

       {
       $code = 02;
         $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

        if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data); }
        }

        if($track == 'Globacom')
       {
       $code = 02;
         $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}

        if($track == '9mobile')
       {
       $code = 03;
      $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}

        if($track == 'Etisalat')
       {
       $code = 03;
      $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}

        if($track == 'etisalat')
       {
       $code = 03;
      $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}

        if($track == 'Airtel')
       {
       $code = 04;
      $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}


        if($track == 'airtel')
       {
       $code = 04;
         $count2 = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }}








        $count1 = Bill::whereTrx($track)->wheretype(1)->whereUser_id($user->id)->count();
        if($count1 > 0){
         $data['log'] = Bill::whereTrx($track)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }




        $count3 = Bill::wherePhone($track)->wheretype(1)->whereUser_id($user->id)->count();
        if($count3 > 0){
         $data['log'] = Bill::whereTrx($track)->wheretype(1)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.recharge-log', $data);
        }

        else
        {
        return back()->with('alert', 'There is no transaction with this entry .');
        }




    }



        public function datasearch(Request $request)
    {
        $request->validate([
            'trx' => 'required',
        ]);
         Session::put('Track', $request->trx);

       return redirect()->route('datasearchget');

    }

        public function datasearchget()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Internet Data';
        $track = Session::get('Track');


       if($track == 'MTN')
       {
       $code = 01;
       $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}
        if($track == 'mtn')
       {
       $code = 01;
        $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}
          if($track == 'glo')
       {
       $code = 02;
         $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}
          if($track == 'GLO')
       {
       $code = 02;
         $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();


            if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}

            if($track == 'GLOBACOM')

       {
       $code = 02;
         $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

        if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data); }
        }

        if($track == 'Globacom')
       {
       $code = 02;
         $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}

        if($track == '9mobile')
       {
       $code = 03;
      $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}

        if($track == 'Etisalat')
       {
       $code = 03;
      $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}

        if($track == 'etisalat')
       {
       $code = 03;
      $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}

        if($track == 'Airtel')
       {
       $code = 04;
      $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}


        if($track == 'airtel')
       {
       $code = 04;
         $count2 = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->count();

       if($count2 > 0){
         $data['log'] = Bill::whereNetwork($code)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }}








        $count1 = Bill::whereTrx($track)->wheretype(2)->whereUser_id($user->id)->count();
        if($count1 > 0){
         $data['log'] = Bill::whereTrx($track)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }

        $count3 = Bill::wherePhone($track)->wheretype(2)->whereUser_id($user->id)->count();
        if($count1 > 0){
         $data['log'] = Bill::whereTrx($track)->wheretype(2)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.internet-log', $data);
        }

        else
        {
        return back()->with('alert', 'There is no transaction with this entry .');
        }




    }





        public function tvsearch(Request $request)
    {
        $request->validate([
            'trx' => 'required',
        ]);
         Session::put('Track', $request->trx);

       return redirect()->route('tvsearchget');

    }

        public function tvsearchget()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'TV Subscription';
        $track = Session::get('Track');


       if($track == 'DSTV')
       {
       $code = 01;
       $count2 = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.tv-log', $data);
        }}

         if($track == 'GOTV')
       {
       $code = 02;
       $count2 = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.tv-log', $data);
        }}

         if($track == 'STARTIMES')
       {
       $code = 03;
       $count2 = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.tv-log', $data);
        }}

         if($track == 'dstv')
       {
       $code = 01;
       $count2 = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.tv-log', $data);
        }}

         if($track == 'gotv')
       {
       $code = 02;
       $count2 = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.tv-log', $data);
        }}

         if($track == 'startimes')
       {
       $code = 03;
       $count2 = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(4)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.tv-log', $data);
        }}


        $count1 = Bill::whereTrx($track)->wheretype(3)->whereUser_id($user->id)->count();
        if($count1 > 0){
         $data['log'] = Bill::whereTrx($track)->wheretype(4)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.tv-log', $data);
        }



        $count3 = Bill::wherePhone($track)->wheretype(4)->whereUser_id($user->id)->count();
        if($count3 > 0){
         $data['log'] = Bill::wherePhone($track)->wheretype(4)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.tv-log', $data);
        }

        else
        {
        return back()->with('alert', 'There is no transaction with this entry .');
        }




    }






        public function powersearch(Request $request)
    {
        $request->validate([
            'trx' => 'required',
        ]);
         Session::put('Track', $request->trx);

       return redirect()->route('powersearchget');

    }

        public function powersearchget()
    {
        $user = User::find(Auth::user()->id);
        $data['page_title'] = 'Electricity Bills';
        $track = Session::get('Track');


       if($track == 'EKEDC')
       {
       $code = 01;
       $count2 = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }}



       if($track == 'IKEDC')
       {
       $code = 02;
       $count2 = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }}




       if($track == 'KEDCO')
       {
       $code = 04;
       $count2 = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }}



       if($track == 'PHEDC')
       {
       $code = 05;
       $count2 = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }}




       if($track == 'JED')
       {
       $code = 06;
       $count2 = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }}


       if($track == 'AEDC')
       {
       $code = 03;
       $count2 = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }}


       if($track == 'IBEDC')
       {
       $code = 07;
       $count2 = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }}


       if($track == 'EEDC')
       {
       $code = '08';
       $count2 = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->count();

       if($count2 > 0){

         $data['log'] = Bill::whereNetwork($code)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }}


        $count1 = Bill::wherePhone($track)->wheretype(3)->whereUser_id($user->id)->count();
        if($count1 > 0){
         $data['log'] = Bill::whereTrx($track)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }



        $count3 = Bill::whereTrx($track)->wheretype(3)->whereUser_id($user->id)->count();
        if($count3 > 0){
         $data['log'] = Bill::wherePhone($track)->wheretype(3)->whereUser_id($user->id)->paginate(10);
         return view('user.merchant.power-log', $data);
        }

        else
        {
        return back()->with('alert', 'There is no transaction with this entry .');
        }




    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Currency $currency
     * @return \Illuminate\Http\Response
     */
    public function show(Currency $currency)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Currency $currency
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data['currency'] = Giftcard::find($id);
        $data['page_title'] = "Manage Giftcard";
        return view('admin.giftcard.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \App\Currency $currency
     * @return \Illuminate\Http\Response
     */
    public function post(Request $request )
    {

        $request->validate([
            'buy' => 'required|min:0',
            'symbol' => 'required',
            'name' => 'required',
        ]);

        $data = Giftcard::find($request->id);
        $data['name'] = $request->name ;
        $data['image'] = $request->symbol ;
        $data['buy'] = $request->buy ;
        $data->save();

        return back()->with('success', 'Gift Card Updated Successfully!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Currency $currency
     * @return \Illuminate\Http\Response
     */
    public function destroy(Currency $currency)
    {
        //
    }


     public function developerapi()
    {
      $user = User::find(Auth::user()->id);
      $data['page_title'] = 'Developer Api';

       if($user->developer > 0){

         return view('user.developer.index', $data);
        }
          else
        {
        return back()->with('alert', 'You dont have Developer API permision yet. Please contact admin for permission');
        }
    }



     public function developerapiairtime()
    {
      $user = User::find(Auth::user()->id);
      $data['page_title'] = 'Api Airtime';

       if($user->developer > 0){

         return view('user.developer.airtime', $data);
        }
          else
        {
        return back()->with('alert', 'You dont have Developer API permision yet. Please contact admin for permission');
        }
    }



     public function developerapidata()
    {
      $user = User::find(Auth::user()->id);
      $data['page_title'] = 'Api Internet Data';

       if($user->developer > 0){
         $data['bundle'] = Internetbundle::whereStatus(1)->get();
         return view('user.developer.data', $data );
        }
          else
        {
        return back()->with('alert', 'You dont have Developer API permision yet. Please contact admin for permission');
        }
    }



     public function developerapicabletv()
    {
      $user = User::find(Auth::user()->id);
      $data['page_title'] = 'Api Cable TV';

       if($user->developer > 0){
        $data['bundle'] = Decodersub::whereStatus(1)->get();
         return view('user.developer.cabletv', $data);
        }
          else
        {
        return back()->with('alert', 'You dont have Developer API permision yet. Please contact admin for permission');
        }
    }



     public function developerapipower()
    {
       $user = User::find(Auth::user()->id);
       $data['page_title'] = 'Api Power';

       if($user->developer > 0){

         return view('user.developer.power', $data);
        }
          else
        {
        return back()->with('alert', 'You dont have Developer API permision yet. Please contact admin for permission');
        }
    }





}
