<?php

namespace App\Http\Controllers;

use App\Models\FreeTrail;
use App\Models\PaymentHistory;
use App\Models\PermissionActions;
use App\Models\UserPermissions;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{

    function paymenthistory()
    {

        $data = [

            'paymenthistory' => DB::select(" select  payment_history.*, c.ClientName ,c.Area, c.Location, u.Name as doneby, us.Name as donefor from payment_history 
            left join clients c on payment_history.Client_ID = c.ClientID
            left join user u on payment_history.Done_By = u.id
            left join user us on payment_history.Done_for = us.id
            ")


            // 'paymenthistory' => PaymentHistory::select( "payment_history.*", "c.ClientName" , "c.Area" , "c.Location" ,"u.Name as doneby" , "us.Name as donefor" )
            // ->leftjoin('clients c','payment_history.Client_ID','=','c.ClientID')
            // ->leftjoin('user u','payment_history.Done_By','=','u.id')
            // ->leftjoin('user us','payment_history.Done_for','=','us.id')
            // ->get()
        ];

        // return $data;
        return view('Admin.paymenthistory', $data);
    }



    // ------------------------------------------------
    // copy permission method to pay 

    function readytopaycopy(Request $request)
    {
        $merchant_data = '';
        $working_key = '25E1D96A372D06B069DC53F9D9BD3596'; //Shared by CCAVENUES
        $access_code = 'AVDR04KA55AW35RDWA'; //Shared by CCAVENUES

        $adjustment = $request->adjustment;

        if ($adjustment != '') {

            foreach ($request->except('_token') as $key => $value) {

                if ($key == 'amount') {

                    if ($adjustment > 0) {
                        $merchant_data .= $key . '=' . $value + $adjustment .  '&';
                    }

                    if ($adjustment < 0) {
                        $merchant_data .= $key . '=' . $value + $adjustment .  '&';
                    }

                    if ($adjustment == 0) {
                        $merchant_data .= $key . '=' . $value + $adjustment .  '&';
                    }
                } else {
                    $merchant_data .= $key . '=' . $value . '&';
                }
            }
        } else {
            foreach ($request->except('_token') as $key => $value) {

                $merchant_data .= $key . '=' . $value . '&';
            }
        }

        $encrypted_data = $this->encryptdata($merchant_data, $working_key);

        $data = [
            'merchant_data' => $encrypted_data,
            'access_code' => $access_code
        ];


        if ($request->has('cistrial')) {
            //   allot trial :

            $imploded_One = $request->merchant_param1;
            $imploded_Two = $request->merchant_param2;

            $exploded_One = explode("/", $imploded_One);
            $exploded_Two = explode(",", $imploded_Two);

            $from = $request->merchant_param3;
            $to = $request->merchant_param4;

            $user = $exploded_One[0];
            $client = $exploded_One[1];
            $pack = $exploded_One[2];
            $sessionuser = $exploded_One[3];

            $olduser = $exploded_Two[0];
            $oldclient = $exploded_Two[1];

            $actions = UserPermissions::where('Client_ID', '=', $oldclient)
                ->where('User_ID', '=', $olduser)
                ->get();

            // return $actions;

            for ($count = 0; $count < count($actions); $count++) {

                $data = array(
                    'Client_ID' => $client,
                    'User_ID' => $user,
                    'Package_ID'  => $pack,
                    'per_act'  => $actions[$count]['per_act'],
                    'per_from'  => $from,
                    'per_to'  => $to,
                    'status'  => $actions[$count]['status']
                );

                $insert_data[] = $data;
            }

            UserPermissions::insert($insert_data);

            $uze = Users::find($user);

            $uze->IsLive = 0;

            $save = $uze->save();

            if ($save) {
                $trial = new FreeTrail();

                $trial->User_ID = $user;
                $trial->Client_ID = $client;
                $trial->Package = $pack;
                $trial->Type = 'Trial';
                $trial->From_Date = $from;
                $trial->To_Date = $to;
                $trial->AllottedDate = date("Y-m-d");

                $completed = $trial->save();

                if ($completed) {
                    return back()->with('success', 'Permission allotted Successfully');
                } else {
                    return back()->with('fail', 'Something went wrong');
                }
            } else {
                return back()->with('fail', 'Something went wrong');
            }
        } else if ($request->has('cisActive')) {
            //   allot active  :

            $imploded_One = $request->merchant_param1;
            $imploded_Two = $request->merchant_param2;

            $exploded_One = explode("/", $imploded_One);
            $exploded_Two = explode(",", $imploded_Two);

            $from = $request->merchant_param3;
            $to = $request->merchant_param4;

            $user = $exploded_One[0];
            $client = $exploded_One[1];
            $pack = $exploded_One[2];
            $sessionuser = $exploded_One[3];

            $olduser = $exploded_Two[0];
            $oldclient = $exploded_Two[1];

            $actions = UserPermissions::where('Client_ID', '=', $oldclient)
                ->where('User_ID', '=', $olduser)
                ->get();

            // return $actions;

            for ($count = 0; $count < count($actions); $count++) {

                $data = array(
                    'Client_ID' => $client,
                    'User_ID' => $user,
                    'Package_ID'  => $pack,
                    'per_act'  => $actions[$count]['per_act'],
                    'per_from'  => $from,
                    'per_to'  => $to,
                    'status'  => $actions[$count]['status']
                );

                $insert_data[] = $data;
            }

            UserPermissions::insert($insert_data);

            $uze = Users::find($user);

            $uze->IsLive = 1;

            $save = $uze->save();

            if ($save) {
                $trial = new FreeTrail();

                $trial->User_ID = $user;
                $trial->Client_ID = $client;
                $trial->Package = $pack;
                $trial->Type = 'Active';
                $trial->From_Date = $from;
                $trial->To_Date = $to;
                $trial->AllottedDate = date("Y-m-d");

                $completed = $trial->save();

                if ($completed) {
                    return back()->with('success', 'Permission allotted Successfully');
                } else {
                    return back()->with('fail', 'Something went wrong');
                }
            } else {
                return back()->with('fail', 'Something went wrong');
            }
        } else {
            return view('Admin.paymentPage', $data);
        }
    }


    // -------------------------------------------------

    function readytopay(Request $request)
    {
        $merchant_data = '';
        // $working_key = '25E1D96A372D06B069DC53F9D9BD3596'; //Shared by CCAVENUES
        $working_key = 'BB9AFD5A14911D4B726D05C81B8F7BF8'; //Shared by CCAVENUES
        // $access_code = 'AVDR04KA55AW35RDWA'; //Shared by CCAVENUES
        $access_code = 'AVVE19KB42AW37EVWA'; //Shared by CCAVENUES

        $adjustment = $request->adjustment;

        if ($adjustment != '') {

            foreach ($request->except('_token') as $key => $value) {

                if ($key == 'amount') {

                    if ($adjustment > 0) {
                        $merchant_data .= $key . '=' . $value + $adjustment .  '&';
                    }

                    if ($adjustment < 0) {
                        $merchant_data .= $key . '=' . $value + $adjustment .  '&';
                    }

                    if ($adjustment == 0) {
                        $merchant_data .= $key . '=' . $value + $adjustment .  '&';
                    }
                } else {
                    $merchant_data .= $key . '=' . $value . '&';
                }
            }
        } else {
            foreach ($request->except('_token') as $key => $value) {

                $merchant_data .= $key . '=' . $value . '&';
            }
        }

        $encrypted_data = $this->encryptdata($merchant_data, $working_key);

        $data = [
            'merchant_data' => $encrypted_data,
            'access_code' => $access_code
        ];


        if ($request->has('istrial')) {
            //   allot trial :

            $imploded_One = $request->merchant_param1;
            $imploded_Two = $request->merchant_param2;

            $exploded_One = explode("/", $imploded_One);
            $exploded_Two = explode("/", $imploded_Two);

            $from = $request->merchant_param3;
            $to = $request->merchant_param4;

            $client = $exploded_One[0];
            $user = $exploded_One[1];
            $pack = $exploded_Two[0];

            $actions = PermissionActions::where('act_package', '=', $pack)->get();

            // return $actions;

            for ($count = 0; $count < count($actions); $count++) {

                $data = array(
                    'Client_ID' => $client,
                    'User_ID' => $user,
                    'Package_ID'  => $pack,
                    'per_act'  => $actions[$count]['id'],
                    'per_from'  => $from,
                    'per_to'  => $to,
                    'status'  => $actions[$count]['act_status']
                );

                $insert_data[] = $data;
            }

            UserPermissions::insert($insert_data);

            $uze = Users::find($user);

            $uze->IsLive = 0;

            $save = $uze->save();

            if ($save) {
                $trial = new FreeTrail();

                $trial->User_ID = $user;
                $trial->Client_ID = $client;
                $trial->Package = $pack;
                $trial->Type = 'Trial';
                $trial->From_Date = $from;
                $trial->To_Date = $to;
                $trial->AllottedDate = date("Y-m-d");

                $completed = $trial->save();

                if ($completed) {
                    return back()->with('success', 'Permission allotted Successfully');
                } else {
                    return back()->with('fail', 'Something went wrong');
                }
            } else {
                return back()->with('fail', 'Something went wrong');
            }
        } else if ($request->has('isActive')) {


            $imploded_One = $request->merchant_param1;
            $imploded_Two = $request->merchant_param2;

            $exploded_One = explode("/", $imploded_One);
            $exploded_Two = explode("/", $imploded_Two);

            $from = $request->merchant_param3;
            $to = $request->merchant_param4;

            $client = $exploded_One[0];
            $user = $exploded_One[1];
            $pack = $exploded_Two[0];

            // check if any pack exist 
            $exist = UserPermissions::where('User_ID', '=', $user)
                ->where('Client_ID', '=', $client)->first();

            if (!$exist) {
                $actions = PermissionActions::where('act_package', '=', $pack)->get();


                for ($count = 0; $count < count($actions); $count++) {

                    $data = array(
                        'Client_ID' => $client,
                        'User_ID' => $user,
                        'Package_ID'  => $pack,
                        'per_act'  => $actions[$count]['id'],
                        'per_from'  => $from,
                        'per_to'  => $to,
                        'status'  => $actions[$count]['act_status']
                    );

                    $insert_data[] = $data;
                }

                UserPermissions::insert($insert_data);

                $uze = Users::find($user);

                $uze->IsLive = 1;

                $save = $uze->save();

                if ($save) {
                    $trial = new FreeTrail();

                    $trial->User_ID = $user;
                    $trial->Client_ID = $client;
                    $trial->Package = $pack;
                    $trial->Type = 'Active';
                    $trial->From_Date = $from;
                    $trial->To_Date = $to;
                    $trial->AllottedDate = date("Y-m-d");

                    $completed = $trial->save();

                    if ($completed) {
                        return back()->with('success', 'Permission allotted Successfully');
                    } else {
                        return back()->with('fail', 'Something went wrong');
                    }
                } else {
                    return back()->with('fail', 'Something went wrong');
                }
            } else {
                UserPermissions::where('User_ID', '=', $user)
                    ->where('Client_ID', '=', $client)
                    ->update([
                        'per_from' => $from,
                        'per_to' => $to

                    ]);

                return back()->with('success', 'Permission allotted Successfully');
            }


            // return $actions;


        } else {
            return view('Admin.paymentPage', $data);
        }



        //  make pack active by skipping payment
        // if ($request->has('isActive')) {


        // } 
        // else {
        //     return view('Admin.paymentPage', $data);
        // }
        //  make pack active by skipping payment

    }

    function successpay()
    {
        return view('payment.ccavResponseHandler');
        // return 'you are here....success pay';
    }

    function redirectback()
    {
        return 'you are here....';
    }

    function paymentSuccess($client)
    {
        $data = [
            'client' => $client,
            'from' => PaymentHistory::where('Client_ID', '=', $client)->orderBy('id', 'desc')->pluck('Effect_From')->first(),
            'to' => PaymentHistory::where('Client_ID', '=', $client)->orderBy('id', 'desc')->pluck('Effect_To')->first()
        ];

        return view('Admin.paymentSuccess', $data);
        // return  $data;
    }

    function paymentResponse()
    {
        return view('payment.ccavResponseHandler');
    }

    function encryptdata($plainText, $key)
    {
        $key = $this->hextobin(md5($key));
        $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
        $openMode = openssl_encrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
        $encryptedText = bin2hex($openMode);
        return $encryptedText;
    }

    function hextobin($hexString)
    {
        $length = strlen($hexString);
        $binString = "";
        $count = 0;
        while ($count < $length) {
            $subString = substr($hexString, $count, 2);
            $packedString = pack("H*", $subString);
            if ($count == 0) {
                $binString = $packedString;
            } else {
                $binString .= $packedString;
            }

            $count += 2;
        }
        return $binString;
    }
}
