<?php

namespace App\Http\Controllers;

use App\Models\Clients;
use App\Models\FreeTrail;
use App\Models\Packages;
use App\Models\PaymentHistory;
use App\Models\PaymentSettings;
use App\Models\PermissionActions;
use App\Models\User;
use App\Models\UserPermissions;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class AppPermissionController extends Controller
{

    function viewPrivilageHistory($userid)
    {
        $US = Crypt::decrypt($userid);

        $packID = Users::where('id', '=', $US)->pluck('Package_ID')->first();
        $clientID = Users::where('id', '=', $US)->pluck('userid')->first();
        $userName = Users::where('id', '=', $US)->pluck('Name')->first();
        $cliName = Clients::where('ClientID', '=', $clientID)->pluck('ClientName')->first();
        $Area = Clients::where('ClientID', '=', $clientID)->pluck('Area')->first();
        $Location = Clients::where('ClientID', '=', $clientID)->pluck('Location')->first();
        $Package = Packages::where('id', '=', $packID)->pluck('Pack_Name')->first();


        $data = [
            'packID' => $packID,
            'clientID' => $clientID,
            'userName' => $userName,
            'cliName' => $cliName,
            'Area' => $Area,
            'Location' => $Location,
            'Package' => $Package,
            'userid' => $US,

            'history' => FreeTrail::select(
                "user.Name",
                "clients.ClientName",
                "clients.Area",
                "clients.Location",
                "tbl_packages.Pack_Name",
                "tbl_trials.Type",
                "tbl_trials.From_Date",
                "tbl_trials.To_Date",
                "tbl_trials.AllottedDate",
                "tbl_trials.remarks",
                "tbl_trials.slug"
            )
                ->leftjoin('user', 'tbl_trials.User_ID', '=', 'user.id')
                ->leftjoin('clients', 'tbl_trials.Client_ID', '=', 'clients.ClientID')
                ->leftjoin('tbl_packages', 'tbl_trials.Package', '=', 'tbl_packages.id')
                ->where('User_ID', '=', $US)->get(),

            'payment' => PaymentHistory::where('Done_for', '=', $US)->get()
        ];
        return view('Admin.viewHistory', $data);
        // return  $data;
    }

    function grantprivilegeforuser(Request $request)
    {

        $clientClientUserID   = $request->clientClientUserID;
        $clientPackageSessionID   = $request->clientPackageSessionID;

        $clientAndUser = explode("/", $clientClientUserID);
        $sessionAndPackage = explode("/", $clientPackageSessionID);

        $clientMethod   = $request->clientMethod;
        $clientName   = $request->clientName;
        $clientAddress   = $request->clientAddress;
        $clientCity   = $request->clientCity;
        $clientState   = $request->clientState;
        $clientPinCode   = $request->clientPinCode;
        $clientCountry   = $request->clientCountry;
        $clientMobile   = $request->clientMobile;
        $clientEmail   = $request->clientEmail;
        $clientid = $clientAndUser[0];
        $userid = $clientAndUser[1];
        $packageID = $sessionAndPackage[0];
        $sessionUser = $sessionAndPackage[1];
        $clientUsageMode   = $request->clientUsageMode;
        $clientAmount   = $request->clientAmount;
        $clientAdjustment   = $request->clientAdjustment == '' ? 0 : $request->clientAdjustment;
        $clientPerFrom   = $request->clientPerFrom;
        $clientNoOfDays   = $request->clientNoOfDays;
        $clientPerTo   = $request->clientPerTo;
        $clientPreRemarks   = $request->clientPreRemarks;
        $clientRemarks   = $request->clientRemarks;
        $clientBillingType   = $request->clientBillingType;



        switch ($clientMethod) {

            case 'allotpermission':

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

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

                    $data = array(
                        'Client_ID' => $clientid,
                        'User_ID' => $userid,
                        'Package_ID'  => $packageID,
                        'per_act'  => $actions[$count]['id'],
                        'per_from'  => $clientPerFrom,
                        'per_to'  => $clientPerTo,
                        'status'  => $actions[$count]['act_status'],
                        'userper_slug'  => $actions[$count]['act_slug']
                    );

                    $insert_data[] = $data;
                }

                UserPermissions::insert($insert_data);

                // trial pack
                if ($clientUsageMode == 'T') {
                    $uze = Users::find($userid);

                    $uze->IsLive = 0;

                    $save = $uze->save();

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

                        $trial->User_ID = $userid;
                        $trial->Client_ID = $clientid;
                        $trial->Package = $packageID;
                        $trial->Type = 'Trial';
                        $trial->slug = 'trial';
                        $trial->From_Date = $clientPerFrom;
                        $trial->To_Date = $clientPerTo;
                        $trial->AllottedDate = date("Y-m-d");
                        $trial->remarks = $clientRemarks;

                        $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');
                    }
                }
                // active pack
                else {

                    $paidAmount = $clientAmount + $clientAdjustment;

                    $payHis = new PaymentHistory();

                    $payHis->Client_ID = $clientid;
                    $payHis->Order_Date = date("Y-m-d");
                    $payHis->Order_ID = rand(1000000000, 9999999999);

                    $payHis->actualAmount = $clientAmount;
                    $payHis->adjustmentAmount = $clientAdjustment;

                    $payHis->Order_Amount = $paidAmount;
                    $payHis->Effect_From = $clientPerFrom;
                    $payHis->Effect_To = $clientPerTo;
                    $payHis->Trans_Type = 'Online Log';
                    $payHis->Done_By = $sessionUser;
                    $payHis->Done_for = $userid;
                    $payHis->pay_remark = $clientRemarks;

                    $savez = $payHis->save();

                    if ($savez) {
                        $uze = Users::find($userid);

                        $uze->IsLive = 1;
                        $uze->is_demo = 0;
                        $uze->billing_type = $clientBillingType;

                        $save = $uze->save();

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

                            $trial->User_ID = $userid;
                            $trial->Client_ID = $clientid;
                            $trial->Package = $packageID;
                            $trial->Type = 'Active';
                            $trial->slug = 'active';
                            $trial->From_Date = $clientPerFrom;
                            $trial->To_Date = $clientPerTo;
                            $trial->AllottedDate = date("Y-m-d");
                            $trial->remarks = $clientRemarks;

                            $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 back()->with('fail', 'Something went wrong');
                    }
                }
                break;

            case 'extend':

                UserPermissions::where('User_ID', '=', $userid)
                    ->where('Client_ID', '=', $clientid)
                    ->update([
                        'per_from' => $clientPerFrom,
                        'per_to' => $clientPerTo
                    ]);

                $trial = new FreeTrail();

                $trial->User_ID = $userid;
                $trial->Client_ID = $clientid;
                $trial->Package = $packageID;
                $trial->Type = 'Extend Trial';
                $trial->slug = 'extendtrial';
                $trial->From_Date = $clientPerFrom;
                $trial->To_Date = $clientPerTo;
                $trial->AllottedDate = date("Y-m-d");
                $trial->remarks = $clientRemarks;

                $completed = $trial->save();

                if ($completed) {
                    return back()->with('success', 'Trial Permission extended Successfully');
                } else {
                    return back()->with('fail', 'Something went wrong');
                }

                break;

            case 'makeactive':

                $paidAmount = $clientAmount + $clientAdjustment;

                $payHis = new PaymentHistory();

                $payHis->Client_ID = $clientid;
                $payHis->Order_Date = date("Y-m-d");
                $payHis->Order_ID = rand(1000000000, 9999999999);

                $payHis->actualAmount = $clientAmount;
                $payHis->adjustmentAmount = $clientAdjustment;

                $payHis->Order_Amount = $paidAmount;
                $payHis->Effect_From = $clientPerFrom;
                $payHis->Effect_To = $clientPerTo;
                $payHis->Trans_Type = 'Online Log';
                $payHis->Done_By = $sessionUser;
                $payHis->Done_for = $userid;
                $payHis->pay_remark = $clientRemarks;


                $savez = $payHis->save();

                if ($savez) {

                    $exist = UserPermissions::where('User_ID', '=', $userid)
                        ->where('Client_ID', '=', $clientid)->first();

                    if (!$exist) {

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

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

                            $data = array(
                                'Client_ID' => $clientid,
                                'User_ID' => $userid,
                                'Package_ID'  => $packageID,
                                'per_act'  => $actions[$count]['id'],
                                'per_from'  => $clientPerFrom,
                                'per_to'  => $clientPerTo,
                                'status'  => $actions[$count]['act_status'],
                                'userper_slug'  => $actions[$count]['act_slug']
                            );

                            $insert_data[] = $data;
                        }

                        UserPermissions::insert($insert_data);

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

                        $uze->IsLive = 1;
                        $uze->is_demo = 0;
                        $uze->billing_type = $clientBillingType;

                        $save = $uze->save();

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

                            $trial->User_ID = $userid;
                            $trial->Client_ID = $clientid;
                            $trial->Package = $packageID;
                            $trial->Type = 'Active';
                            $trial->slug = 'active';
                            $trial->From_Date = $clientPerFrom;
                            $trial->To_Date = $clientPerTo;
                            $trial->AllottedDate = date("Y-m-d");
                            $trial->remarks = $clientRemarks;

                            $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', '=', $userid)
                            ->where('Client_ID', '=', $clientid)
                            ->update([
                                'per_from' => $clientPerFrom,
                                'per_to' => $clientPerTo

                            ]);

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

                        $uze->IsLive = 1;
                        $uze->is_demo = 0;
                        $uze->billing_type = $clientBillingType;

                        $save = $uze->save();

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

                            $trial->User_ID = $userid;
                            $trial->Client_ID = $clientid;
                            $trial->Package = $packageID;
                            $trial->Type = 'Active';
                            $trial->slug = 'active';
                            $trial->From_Date = $clientPerFrom;
                            $trial->To_Date = $clientPerTo;
                            $trial->AllottedDate = date("Y-m-d");
                            $trial->remarks = $clientRemarks;

                            $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');
                        }
                    }
                }

                break;

            case 'renewactive':

                $paidAmount = $clientAmount + $clientAdjustment;

                $payHis = new PaymentHistory();

                $payHis->Client_ID = $clientid;
                $payHis->Order_Date = date("Y-m-d");
                $payHis->Order_ID = rand(1000000000, 9999999999);

                $payHis->actualAmount = $clientAmount;
                $payHis->adjustmentAmount = $clientAdjustment;

                $payHis->Order_Amount = $paidAmount;
                $payHis->Effect_From = $clientPerFrom;
                $payHis->Effect_To = $clientPerTo;
                $payHis->Trans_Type = 'Online Log';
                $payHis->Done_By = $sessionUser;
                $payHis->Done_for = $userid;
                $payHis->pay_remark = $clientRemarks;

                $savez = $payHis->save();

                if ($savez) {

                    $exist = UserPermissions::where('User_ID', '=', $userid)
                        ->where('Client_ID', '=', $clientid)->first();

                    if (!$exist) {

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

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

                            $data = array(
                                'Client_ID' => $clientid,
                                'User_ID' => $userid,
                                'Package_ID'  => $packageID,
                                'per_act'  => $actions[$count]['id'],
                                'per_from'  => $clientPerFrom,
                                'per_to'  => $clientPerTo,
                                'status'  => $actions[$count]['act_status'],
                                'userper_slug'  => $actions[$count]['act_slug']
                            );

                            $insert_data[] = $data;
                        }

                        UserPermissions::insert($insert_data);

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

                        $uze->IsLive = 1;
                        $uze->is_demo = 0;
                        $uze->billing_type = $clientBillingType;

                        $save = $uze->save();

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

                            $trial->User_ID = $userid;
                            $trial->Client_ID = $clientid;
                            $trial->Package = $packageID;
                            $trial->Type = 'Renewal';
                            $trial->slug = 'renewal';
                            $trial->From_Date = $clientPerFrom;
                            $trial->To_Date = $clientPerTo;
                            $trial->AllottedDate = date("Y-m-d");
                            $trial->remarks = $clientRemarks;

                            $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', '=', $userid)
                            ->where('Client_ID', '=', $clientid)
                            ->update([
                                'per_from' => $clientPerFrom,
                                'per_to' => $clientPerTo

                            ]);

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

                        $uze->IsLive = 1;
                        $uze->is_demo = 0;
                        $uze->billing_type = $clientBillingType;

                        $save = $uze->save();

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

                            $trial->User_ID = $userid;
                            $trial->Client_ID = $clientid;
                            $trial->Package = $packageID;
                            $trial->Type = 'Active';
                            $trial->slug = 'active';
                            $trial->From_Date = $clientPerFrom;
                            $trial->To_Date = $clientPerTo;
                            $trial->AllottedDate = date("Y-m-d");
                            $trial->remarks = $clientRemarks;

                            $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');
                        }
                    }
                }


                break;
        }

        // 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);
        // }
    }

    function grantPrivilegeForAll(Request $request)
    {
        $from = $request->from;
        $to = $request->to;
        $platinum = 3;
        $status = 1;

        $actions = PermissionActions::where('act_package', '=', $platinum)->get();
        $clients = Clients::all();
        $data = array();

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

                $exist = UserPermissions::where('Client_ID', '=', $clients[$i]['ClientID'])
                    ->where('User_ID', '=', session('LoggedUser')['id'])
                    ->where('Package_ID', '=', $platinum)
                    ->where('per_act', '=', $actions[$count]['id'])
                    ->first();

                if (!$exist) {
                    $data = array(
                        'Client_ID' => $clients[$i]['ClientID'],
                        'User_ID' => session('LoggedUser')['id'],
                        'Package_ID'  => $platinum,
                        'per_act'  => $actions[$count]['id'],
                        'per_from'  => $from,
                        'per_to'  => $to,
                        'status'  => $status
                    );
                } else {
                    UserPermissions::where('Client_ID', '=', $clients[$i]['ClientID'])
                        ->where('User_ID', '=', session('LoggedUser')['id'])
                        ->where('Package_ID', '=', $platinum)
                        ->where('per_act', '=', $actions[$count]['id'])
                        ->update([
                            'per_from' => $from,
                            'per_to' => $to,
                            'status' => $status
                        ]);
                }


                $insert_data[] = $data;
            }
        }

        if (!empty($insert_data)) {
            UserPermissions::insert($insert_data);
        }


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

    function copyUserPermission(Request $request)
    {
        $client = $request->toclient;
        $user = $request->touser;
        $topackage = $request->topackage;

        $fromuser = $request->fromuser;

        $userNclient = explode(",", $fromuser);

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

        $actions = UserPermissions::where('User_ID', '=', $userNclient[0])
            ->where('Client_ID', '=', $userNclient[1])
            ->get();

        for ($count = 0; $count < count($actions); $count++) {
            $data = array(
                'Client_ID' => $client,
                'User_ID' => $user,
                'Package_ID'  => $topackage,
                'per_act'  => $actions[$count]['per_act'],
                'per_from'  => $from,
                'per_to'  => $to,
                'status'  => $actions[$count]['status'],
                'userper_slug'  => $actions[$count]['act_slug'],
            );

            $insert_data[] = $data;
        }

        UserPermissions::insert($insert_data);

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

    function getAllPermissionUsers(Request $request)
    {
        $allUsers = DB::select(" select Name,id,userid from user where id in 
        ( select distinct User_ID from tbl_userpermissions ) and user.Package_ID = " . $request->package . "  ");

        return response()->json($allUsers);
    }


    function assignedAppPermissions($user, $client)
    {
        $US = Crypt::decrypt($user);
        $CN = Crypt::decrypt($client);

        $cliName = Clients::where('ClientID', '=', $CN)->pluck('ClientName')->first();

        $cliArea = Clients::where('ClientID', '=', $CN)->pluck('Area')->first();
        $cliLocation = Clients::where('ClientID', '=', $CN)->pluck('Location')->first();

        $userName = Users::where('id', '=', $US)->pluck('Name')->first();

        $packageID = Users::where('id', '=', $US)->pluck('Package_ID')->first();

        if ($packageID != 0) {
            $packageName = Packages::where('id', '=', $packageID)->pluck('Pack_Name')->first();
        } else {
            return back()->with('fail', 'package not found');
        }


        $data = [
            'clientID' => $CN,
            'userID' => $US,
            'packageID' => $packageID,

            'isLive' => Users::where('id', '=',  $US)->pluck('isLive')->first(),

            // 'fromdate' => UserPermissions::select("tbl_userpermissions.per_from")
            // ->join('tbl_permissionActions','tbl_userpermissions.per_act','=','tbl_permissionActions.id')
            // ->where('tbl_permissionActions.act_slug','=','trial')
            // ->where('tbl_userpermissions.User_ID','=',$US)
            // ->first(),

            'fromdate' => UserPermissions::where('tbl_userpermissions.User_ID', '=', $US)
                ->join('tbl_permissionActions', 'tbl_userpermissions.userper_slug', '=', 'tbl_permissionActions.act_slug')
                ->where('tbl_permissionActions.act_slug', '=', 'trial')
                ->pluck('per_from')->first(),

            'todate' => UserPermissions::where('tbl_userpermissions.User_ID', '=', $US)
                ->join('tbl_permissionActions', 'tbl_userpermissions.userper_slug', '=', 'tbl_permissionActions.act_slug')
                ->where('tbl_permissionActions.act_slug', '=', 'trial')
                ->pluck('per_to')->first(),

            'sessionuser' => session('LoggedUser')['id'],

            'clientname' => $cliName,
            'clientarea' => $cliArea,
            'clientlocation' => $cliLocation,

            'username' => $userName,
            'packagename' => $packageName,

            'merchant' => PaymentSettings::where('id', '=', 1)->pluck('Merchant_ID')->first(),
            'accesskey' => PaymentSettings::where('id', '=', 1)->pluck('Access_Key')->first(),
            'workingkey' => PaymentSettings::where('id', '=', 1)->pluck('Working_Key')->first(),

            'permissions' => UserPermissions::where('Client_ID', '=', $CN)
                ->where('User_ID', '=', $US)
                ->where('Package_ID', '=', $packageID)
                ->count(),

            'userPermissions' => DB::select(" select  tbl_userpermissions.id,tbl_userpermissions.Package_ID,per_from,per_to,status,
            tbl_permissionActions.act_desc,
            tbl_permissionActions.act_payment,
            tbl_permissionActions.act_slug,tbl_packages.Pack_Name from tbl_userpermissions
            
            join tbl_packages on tbl_userpermissions.Package_ID = tbl_packages.id
            join tbl_permissionActions on tbl_userpermissions.userper_slug = tbl_permissionActions.act_slug
            where tbl_userpermissions.User_ID = " . $US . " and tbl_userpermissions.Client_ID = " . $CN . "  ")

            // SELECT tbl_userpermissions.per_from, tbl_userpermissions.per_to,tbl_permissionActions.act_desc,tbl_userpermissions.status FROM `tbl_userpermissions` 
            // join tbl_permissionActions on tbl_userpermissions.per_act = tbl_permissionActions.id
            // where tbl_userpermissions.User_ID = 2

        ];

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

    // function allotPackagePermission(Request $request)
    // {

    //     $client = $request->client;
    //     $user = $request->user;
    //     $pack = $request->package;
    //     $from = $request->from;
    //     $to = $request->to;

    //     $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);

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

    public static function allotPackagePermission($client, $user, $pack, $from, $to)
    {

        // $client = $request->client;
        // $user = $request->user;
        // $pack = $request->package;
        // $from = $request->from;
        // $to = $request->to;

        $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'],
                'userper_slug'  => $actions[$count]['act_slug']
            );

            $insert_data[] = $data;
        }

        UserPermissions::insert($insert_data);

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


    function updatePermissionStatus(Request $request)
    {
        $rowid = $request->rowid;
        $status = $request->status;

        $pers = UserPermissions::find($rowid);

        if ($pers->status == 1) {
            $pers->status = 0;
        } else {
            $pers->status = 1;
        }

        $res = $pers->save();

        if ($res) {
            return response()->json(['success' => true, 'message' => 'Permission updated successfully'], 200);
        } else {
            return response()->json(['fail' => false, 'message' => 'Something went wrong'], 200);
        }
    }

    function updatepermissionstatusbyid($id)
    {


        $pers = UserPermissions::find($id);

        if ($pers->status == 1) {
            $pers->status = 0;
        } else {
            $pers->status = 1;
        }

        $res = $pers->save();

        if ($res) {
            return back()->with('success', 'Permission updated successfully');
        } else {
            return back()->with('success', 'Something went wrong');
        }
    }


    function updatePermissionStatusWithFromTo(Request $request)
    {
        $perRow = $request->perRowID;
        $from = $request->from;
        $to = $request->to;

        $pers = UserPermissions::find($perRow);

        $pers->per_from = $from;
        $pers->per_to = $to;
        $pers->status = 1;

        $res = $pers->save();

        if ($res) {
            return back()->with('success', 'Permission allotted from ' . $from . ' to ' . $to . ' Successfully');
            // return response()->json(['success' => true, 'message' => 'Permission updated successfully' ], 200);
        } else {
            return back()->with('fail', 'something went wrong');

            // return response()->json(['fail' => false, 'message' => 'Something went wrong' ], 200);
        }
    }

    // $newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 365 day"));

}
