<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Auth;
use App\Models\User;
use App\Models\usersettings;
use App\Models\Employeerating;
use App\Models\Customer;
use App\Models\Countries;
use App\Models\Apptitle;
use App\Models\Footertext;
use Illuminate\Support\Facades\Validator;
use Hash;
use Illuminate\Support\Str;
use App\Imports\CustomerImport;
use App\Models\Announcement;
use App\Models\Customfield;
use App\Models\TicketCustomfield;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\VerifyUser;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;
use App\Models\VerifyOtp;
use PragmaRX\Google2FA\Google2FA;
use App\Models\Setting;
use App\Models\tickethistory;
use App\Models\Holiday;
use App\Models\Ticket\Ticket;
use App\Models\Ticketviolation;
use App\Models\senduserlist;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use laravelLara\infoinst\Jobs\MailSend;
use ZipArchive;
use Ifsnop\Mysqldump\Mysqldump;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

use Jenssegers\Agent\Agent;
use App\Models\CustomerSetting;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;

class AdminprofileController extends Controller
{
    use ThrottlesLogins, AuthenticatesUsers {
        logout as performLogout;
    }
    public function adminLayout()
    {
        $title = Apptitle::first();
        $data['title'] = $title;

        $user = User::with('roles', 'usetting')->findOrFail(Auth::user()->id);
        $data['users'] = $user;
        $data['authcheck'] = Auth::check();

        if (Auth::check() && Auth::user()->id) {
            $avgrating1 = Employeerating::where('user_id', Auth::id())->where('rating', '1')->count();
            $avgrating2 = Employeerating::where('user_id', Auth::id())->where('rating', '2')->count();
            $avgrating3 = Employeerating::where('user_id', Auth::id())->where('rating', '3')->count();
            $avgrating4 = Employeerating::where('user_id', Auth::id())->where('rating', '4')->count();
            $avgrating5 = Employeerating::where('user_id', Auth::id())->where('rating', '5')->count();
            $avgr = ((5 * $avgrating5) + (4 * $avgrating4) + (3 * $avgrating3) + (2 * $avgrating2) + (1 * $avgrating1));
            $avggr = ($avgrating1 + $avgrating2 + $avgrating3 + $avgrating4 + $avgrating5);

            if ($avggr == 0) {
                $avggr = 1;
                $avg = $avgr / $avggr;
                $data['avg'] = $avg;
            } else {
                $avg = $avgr / $avggr;
                $data['avg'] = $avg;
            }
        }
        $data['date_format'] = setting('date_format');

        $setting = response()->json([
            'MAINTENANCE_MODE' => setting('MAINTENANCE_MODE'),
            'date_format' => setting('date_format'),
            'FAQ_ENABLE' => setting('FAQ_ENABLE'),
            'CONTACT_ENABLE' => setting('CONTACT_ENABLE'),
            'time_format' => setting('time_format'),
            'start_week' => setting('start_week'),
            'default_timezone' => setting('default_timezone'),
            'SPRUKOADMIN_P' => setting('SPRUKOADMIN_P'),
            'DARK_MODE' => setting('DARK_MODE'),
            'FILE_UPLOAD_MAX' => setting('FILE_UPLOAD_MAX'),
            'FILE_UPLOAD_TYPES' => setting('FILE_UPLOAD_TYPES'),
            'sidemenu_icon_style' => setting('sidemenu_icon_style'),
            'ENVATO_ON' => setting('ENVATO_ON'),
            'cronjob_set' => setting('cronjob_set'),
            'mail_host' => setting('mail_host'),
            'admin_users_inactive_auto_logout_time' => setting('admin_users_inactive_auto_logout_time'),
            'admin_users_inactive_auto_logout' => setting('admin_users_inactive_auto_logout'),
            'isToken' => setting('isToken'),
            'operatorsAgentToAgentSound' => setting('operatorsAgentToAgentSound'),
            'operatorsAgentToAgentWebNot' => setting('operatorsAgentToAgentWebNot'),
            'operatorsNotificationsSounds' => setting('operatorsNotificationsSounds'),
            'operatorsGroupChatWebNot' => setting('operatorsGroupChatWebNot'),
            'operatorsGroupChatSound' => setting('operatorsGroupChatSound'),
        ]);
        $data['setting'] = $setting;

        $country = Countries::all();
        $data['countries'] = $country;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }
        $cronset = \App\Models\Setting::where('key', 'cronjob_set')->first();
        $cronworking = $cronset->updated_at->addMinutes(1) >= \Carbon\Carbon::now();
        $data['cronworking'] = $cronworking;
        return $data;
    }
    public function index()
    {
        $title = Apptitle::first();
        $data['title'] = $title;

        $user = User::with('roles', 'usetting')->findOrFail(Auth::user()->id);
        $data['users'] = $user;
        if (Auth::check() && Auth::user()->id) {
            $avgrating1 = Employeerating::where('user_id', Auth::id())->where('rating', '1')->count();
            $avgrating2 = Employeerating::where('user_id', Auth::id())->where('rating', '2')->count();
            $avgrating3 = Employeerating::where('user_id', Auth::id())->where('rating', '3')->count();
            $avgrating4 = Employeerating::where('user_id', Auth::id())->where('rating', '4')->count();
            $avgrating5 = Employeerating::where('user_id', Auth::id())->where('rating', '5')->count();

            $avgr = ((5 * $avgrating5) + (4 * $avgrating4) + (3 * $avgrating3) + (2 * $avgrating2) + (1 * $avgrating1));
            $avggr = ($avgrating1 + $avgrating2 + $avgrating3 + $avgrating4 + $avgrating5);

            if ($avggr == 0) {
                $avggr = 1;
                $avg = $avgr / $avggr;
                $data['avg'] = $avg;
            } else {
                $avg = $avgr / $avggr;
                $data['avg'] = $avg;
            }
        }
        $data['date_format'] = setting('date_format');

        $setting = response()->json(['MAINTENANCE_MODE' => setting('MAINTENANCE_MODE'), 'date_format' => setting('date_format'), 'FAQ_ENABLE' => setting('FAQ_ENABLE'), 'CONTACT_ENABLE' => setting('CONTACT_ENABLE'), 'time_format' => setting('time_format'), 'start_week' => setting('start_week'), 'default_timezone' => setting('default_timezone'), 'SPRUKOADMIN_P' => setting('SPRUKOADMIN_P'), 'DARK_MODE' => setting('DARK_MODE'), 'FILE_UPLOAD_MAX' => setting('FILE_UPLOAD_MAX'), 'FILE_UPLOAD_TYPES' => setting('FILE_UPLOAD_TYPES'), 'sidemenu_icon_style' => setting('sidemenu_icon_style'), 'ENVATO_ON' => setting('ENVATO_ON'), 'cronjob_set' => setting('cronjob_set'), 'mail_host' => setting('mail_host'), 'twofactorauth' => Auth::user()->twofactorauth, 'Employe_email_two_fact' => setting('Employe_email_two_fact'), 'Employe_google_two_fact' => setting('Employe_google_two_fact'), 'cust_email_update' => setting('cust_email_update')]);
        $data['setting'] = $setting;

        $country = Countries::all();
        $data['countries'] = $country;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }

        return $data;
    }

    public function adminemailchange(Request $request)
    {
        $user = User::where('email', $request->email)->first();
        if (Hash::check($request->password, $user->password)) {
            $emaildata = [
                'username' => $user->name,
                'useremail' => $user->email,
                'ticket_admin_url' => url('/admin/adminemailupdate/' . $user->email),
            ];
            try {
                dispatch((new MailSend($user->email, 'Send_email_to_admin_users_when_change_email', $emaildata)));
            } catch (\Exception $e) {
            }
            return response()->json(['success' => 'Please check your email to change email id, we send a mail to your email.', 'message' => 'linksend']);
        } else {
            return response()->json(['error' => 'You entered an invalid password.', 'message' => 'wrongpassword']);
        }
    }
    public function userpasswordverify(Request $request)
    {
        $user = User::where('email', $request->email)->first();
        if (Hash::check($request->password, $user->password)) {
            return response()->json(['success' => lang('Correct password.', 'alerts'), 'message' => $request->twofactorname == 'emailtwofact' ? 'email2famatched' : 'google2famatched']);
        } else {
            return response()->json(['error' => lang('You are entered invalid password.', 'alerts'), 'message' => 'wrongpassword']);
        }
    }

    public function adminemailupdate(Request $request, $id)
    {

        $now = now();
        $announcement = announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;

        $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->whereDate('enddate', '>=', $now->toDateString())->where('status', '1')->get();
        $data['holidays'] =  $holidays;

        $data['oldemail'] = $id;

        return $data;
    }

    public function adminnewemailstore(Request $request)
    {
        $user = User::where('email', $request->oldemail)->first();
        if ($user->email == $request->email) {
            return response()->json(['error' => lang('This email is already linked to your account.', 'alerts'), 'email' => 'already']);
        }

        $request->validate([
            'email' => 'required|email|max:255|indisposable|unique:users',
        ]);

        $otpdata = VerifyOtp::where('type', 'emailupdate')->where('cust_id', $request->email)->first();
        $user = User::where('email', $request->oldemail)->first();

        if ($otpdata) {
            $otpdata->otp = rand(100000, 999999);
            $otpdata->update();
            if ($request->session()->has('emailupdate')) {
                $request->session()->forget('emailupdate');
            }
            $request->session()->put('emailupdate', $otpdata->cust_id);
            $custemailchange = [
                'otp' => $otpdata->otp,
                'useremail' => $otpdata->cust_id,
                'username' => $user->name,
            ];
            try {
                dispatch((new MailSend($otpdata->cust_id, 'Send_email_to_customer_when_change_email_otp_verification', $custemailchange)));
            } catch (\Exception $e) {
            }
            return response()->json(['success' => 'Please check your email to verify otp.', 'otp' => 'exists']);
        }
        if (!$otpdata) {
            $verifyOtp = VerifyOtp::create([
                'cust_id' => $request->email,
                'otp' => rand(100000, 999999),
                'type' => 'emailupdate',
            ]);

            if ($request->session()->has('emailupdate')) {
                $request->session()->forget('emailupdate');
            }
            $request->session()->put('emailupdate', $verifyOtp->cust_id);

            $custemailchange = [
                'otp' => $verifyOtp->otp,
                'useremail' => $verifyOtp->cust_id,
                'username' => $user->name,
            ];

            try {
                dispatch((new MailSend($verifyOtp->cust_id, 'Send_email_to_customer_when_change_email_otp_verification', $custemailchange)));
            } catch (\Exception $e) {
            }

            return response()->json(['success' => 'Please check your email to verify otp.', 'otp' => 'exists']);
        }
    }

    public function adminemailupdateotpverify(Request $request, $oldemail)
    {

        if ($request->session()->has('emailupdate')) {
            $emailvalidate = $request->session()->get('emailupdate');
        }
        $verify = VerifyOtp::where('type', 'emailupdate')->where('otp', $request->otp)->first();
        if ($verify) {
            if ($emailvalidate == $verify->cust_id) {
                $userfind = User::where('email', $oldemail)->first();
                $userfind->email = $verify->cust_id;
                $userfind->save();

                $geolocation = GeoIP::getLocation(request()->getClientIp());
                $agent = new Agent();
                $activity = new EmployeeActivity();
                $activity->user_id = Auth::user()->id;
                $activity->activity_type = 'Updated their email';
                $activity->ip_address = $geolocation->ip;
                $activity->browser = $agent->browser();
                $activity->device = $agent->device();
                $activity->save();

                $this->performLogout($request);
                return response()->json(['success' => 'Your email id updated successfully.']);
            } else {
                return response()->json(['error' => 'Invalid OTP']);
            }
        } else {
            return response()->json(['error' => 'Invalid OTP']);
        }

        if (!$verify) {
            return response()->json(['error' => 'Invalid OTP']);
        }
    }

    public function profilesetup(Request $request)
    {
        $this->authorize('Profile Edit');

        $this->validate($request, [
            'firstname' => 'max:255|required',
            'lastname' => 'max:255|required',
        ]);



        $user_id = Auth::user()->id;
        $user = User::findOrFail($user_id);
        $user->firstname = ucfirst($request->input('firstname'));
        $user->lastname = ucfirst($request->input('lastname'));
        $user->name = ucfirst($request->input('firstname')) . ' ' . ucfirst($request->input('lastname'));
        $user->gender = $request->input('gender');
        $user->languagues =  $request->input('languages');
        $user->skills =  $request->input('skills');
        $user->phone = $request->input('phone');
        $user->country = $request->input('country');
        $user->timezone = $request->input('timezone');
        if ($request->input('profileRemoved') != 'null' && $request->input('profileRemoved') != 'undefined') {
            $user = User::findOrFail($user_id);
            $user->image = null;
            $user->update();
        }

        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $fileArray = array('image' => $file);
            $rules = array(
                'image' => 'mimes:jpeg,jpg,png|required|max:5120' // max 10000kb
            );

            // Now pass the input and rules into the validator
            $validator = Validator::make($fileArray, $rules);

            if ($validator->fails()) {
                return response()->json(['error' => 'Please check the format and size of the file.']);
            } else {
                $image_name = time() . '.' . $file->getClientOriginalExtension();
                $provider = storage()->provider;
                $existprovider = existprovider($user->storage_disk);
                if ($existprovider)
                    $existprovider->provider::delete('/uploads/profile' . "/" . $user->image);
                $upload =  $provider::uploadprofile($file, $image_name);
                if ($upload) {
                    $user->update(['image' => $image_name, 'storage_disk' => storage()->storage_disk]);
                } else
                    return response()->json(['error' => 'Image upload failed please try again.']);
            }
        }

        $user->update();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated their profile';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'Your profile has been successfully updated.']);
    }

    public function imageremove(Request $request, $id)
    {


        $user = User::findOrFail($id);
        $user->image = null;
        $user->update();
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Removed their profile image';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'The profile image was successfully removed.']);
    }


    // Customer function

    public function customers(Request $request)
    {
        $this->authorize('Customers Access');

        $customer = Customer::withCount('tickets');
        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;
        if ($searchTerm) {
            $customer->where(function ($query) use ($searchTerm) {
                $query->where(function ($query) use ($searchTerm) {
                    $columns = Schema::getColumnListing('customers');
                    foreach ($columns as $column) {
                        $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                    }
                });
            });
        }
        $items = $customer->paginate($perPage);


        $data['queryList'] = $items;

        $data['setting'] = response()->json(['date_format', setting('date_format')]);


        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }

        return $data;
    }


    public function resendverification($email)
    {
        $user = Customer::where('email', '=', $email)->first();

        $existVerifyUser = VerifyUser::where('cust_id', $user->id)->get();
        if ($existVerifyUser != null) {
            foreach ($existVerifyUser as $existVerifyUsers) {
                $existVerifyUsers->delete();
            }
        }

        $verifyUser = VerifyUser::create([
            'cust_id' => $user->id,
            'token' => sha1(time())
        ]);

        $verifyData = [
            'username' => $user->username,
            'email' => $user->email,
            'email_verify_url' => url('/customer/user/verify/' . $verifyUser->token),
        ];

        try {
            dispatch((new MailSend($user->email, 'customer_sendmail_verification', $verifyData)));
            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Re-sent Customer email verification mail to .' . ' ' . $user->username;
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
        } catch (\Exception $e) {
            return response()->json(['success' => 'The email verification link was successfully sent. Please check and verify your email.']);
        }

        return response()->json(['success' => 'The email verification link was successfully sent. Please check and verify your email.']);
    }
    public function exportDatabase()
    {
        // Set the file path where the database dump will be stored
        $filePath = storage_path('app/database_backup.sql');

        // Set your database credentials
        $host = env('DB_HOST');
        $database = env('DB_DATABASE');
        $username = env('DB_USERNAME');
        $password = env('DB_PASSWORD');

        try {
            // Create a new instance of Mysqldump
            $dump = new Mysqldump("mysql:host=$host;dbname=$database", $username, $password);

            // Dump the database to the specified file path
            $dump->start($filePath);

            return response()->download($filePath)->deleteFileAfterSend(true);
            // Return the file path
            // return response()->json(['file_path' => $filePath]);
        } catch (\Exception $e) {
            // Handle any exceptions
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
    public function downloadProject()
    {
        // Create a temporary file for the zip
        $zipFile = tempnam(sys_get_temp_dir(), env('APP_NAME') . '_');
        $zip = new ZipArchive();
        // Open the zip file for writing
        if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
            // Get the base path of your Laravel project
            $basePath = base_path();
            // Get all files and directories in your Laravel project
            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($basePath),
                RecursiveIteratorIterator::LEAVES_ONLY
            );

            // Loop through each file and directory
            foreach ($files as $name => $file) {
                // Skip directories (they will be added automatically when adding files)
                if (!$file->isDir()) {
                    // Add file to the zip archive
                    $filePath = $file->getRealPath();
                    $relativePath = substr($filePath, strlen($basePath) + 1);
                    if (strpos($relativePath, 'storage') !== false && basename($relativePath) === 'installed') {
                        continue; // Skip this file
                    }
                    $zip->addFile($filePath, $relativePath);
                } else {
                    // Add empty directory to the zip archive
                    $relativePath = substr($file->getRealPath(), strlen($basePath) + 1);
                    $zip->addEmptyDir($relativePath);
                }
            }
            // Close the zip archive
            $zip->close();

            // Download the zip file
            return response()->download($zipFile)->deleteFileAfterSend(true);
        } else {
            // If failed to open the zip file, return an error response
            return response()->json(['message' => 'Failed to create zip file']);
        }
    }



    public function customerscreate()
    {
        $this->authorize('Customers Create');
        $user = Customer::get();
        $data['users'] = $user;

        $country = Countries::all();
        $data['countries'] = $country;


        $customfields = Customfield::whereIn('displaytypes', ['both', 'registerform'])->whereIn('status', [1])->get();
        $data['customfields'] = $customfields;
        return $data;
    }

    public function customersstore(Request $request)
    {
        $this->authorize('Customers Create');
        $request->validate([
            'firstname' => 'required|string|max:255',
            'lastname' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:customers',
            'password' => 'required|string|min:8',
        ]);

        if ($request->phone) {
            $request->validate([
                'phone' => 'numeric',
            ]);
        }
        $customer = Customer::create([
            'firstname' => Str::ucfirst($request->input('firstname')),
            'lastname' => Str::ucfirst($request->input('lastname')),
            'email' => $request->email,
            'status' => '1',
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'image' => null,
            'verified' => '1',
            'userType' => 'Customer',

        ]);

        $customers = Customer::find($customer->id);
        $customers->username = $customer->firstname . ' ' . $customer->lastname;
        $customers->update();
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Created a customer' . ' ' . $customers->username;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        $customersetting = new CustomerSetting();
        $customersetting->custs_id = $customers->id;
        $customersetting->darkmode = null;
        $customersetting->save();

        $customfields = Customfield::whereIn('displaytypes', ['both', 'registerform'])->whereIn('status', [1])->get();

        if ($customfields != false) {
            foreach ($customfields as $customfield) {
                $ticketcustomfield = new TicketCustomfield();
                $ticketcustomfield->cust_id = $customer->id;
                $ticketcustomfield->fieldnames = $customfield->fieldnames;
                $ticketcustomfield->fieldtypes = $customfield->fieldtypes;
                $ticketcustomfield->fieldoptions = $customfield->fieldoptions;
                if ($customfield->fieldtypes == 'checkbox') {
                    if ($request->input('custom_' . $customfield->id) != null) {

                        $string = implode(',', $request->input('custom_' . $customfield->id));
                        $ticketcustomfield->values = $string;
                    }
                }
                if ($customfield->fieldtypes != 'checkbox') {
                    if ($customfield->fieldprivacy == '1') {
                        $ticketcustomfield->privacymode  = $customfield->fieldprivacy;
                        $ticketcustomfield->values = encrypt($request->input('custom_' . $customfield->id));
                    } else {

                        $ticketcustomfield->values = $request->input('custom_' . $customfield->id);
                    }
                }
                $ticketcustomfield->save();
            }
        }

        $customerData = [
            'userpassword' => $request->password,
            'username' => $customer->firstname . ' ' . $customer->lastname,
            'useremail' => $customer->email,
            'url' => url('/'),
        ];

        try {
            dispatch((new MailSend($customer->email, 'customer_send_registration_details', $customerData)));
        } catch (\Exception $e) {
            return response()->json(['success' => 'A new customer was successfully added.']);
        }
        return response()->json(['success' => 'A new customer was successfully added.']);
    }

    public function customersshow($id)
    {
        $this->authorize('Customers Edit');

        $id = decrypt($id);
        $user = Customer::where('id', $id)->first();
        $data['user'] = $user;
        $country = Countries::all();
        $data['countries'] = $country;
        $customfield = TicketCustomfield::where('cust_id', $id)->get();
        $data['customfield'] = $customfield;
        return $data;
    }

    public function voilating(Request $request)
    {

        $request->validate([
            'ticketviolation' => 'required',
        ]);

        $ticket = Ticket::find($request->ticket_id);

        $ticketviolation = $request->input('ticketviolation');

        // Trim unwanted tags from the start and end
        $ticketviolation = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $ticketviolation);

        if ($request->ticket_violation_id != null) {
            $ticketnote = Ticketviolation::find($request->ticket_violation_id);
            $ticketnote->ticketviolation = $request->ticketviolation;
            $ticketnote->save();

            $tickethistory = new tickethistory();
            $tickethistory->ticket_id = $ticket->id;
            $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
            $tickethistory->ticketviolation = $ticketviolation;
            $tickethistory->overduestatus = $ticket->overduestatus;
            $tickethistory->status = $ticket->status;
            $tickethistory->replystatus = $ticket->replystatus;
            $tickethistory->currentAction = 'Ticket Violation Modified';
            $tickethistory->username = Auth::user()->name;
            $tickethistory->type = Auth::user()->getRoleNames()[0];
            $tickethistory->assignUser = null;


            $tickethistory->save();
            $ticketData = [
                'ticket_id' => $ticket->id,
                'violatedId' => $ticketnote->id,
                'ticketviolation' => $ticket->ticketviolation,
                'violationnote' => $request->input('ticketviolation'),
                'rolename' => Auth::user()->getRoleNames()[0],
                'username' => Auth::user()->name,
                'role_id' => Auth::user()->id,

            ];
            return response()->json(['success' => lang('The violatied note is modified successfully.', 'alerts')]);
        } else {

            $custdetails = Customer::find($ticket->cust_id);

            $ticketnote = Ticketviolation::create([
                'ticket_id' => $request->input('ticket_id'),
                'user_id' => Auth::user()->id,
                'ticketviolation' => $request->input('ticketviolation')
            ]);

            $ticket = Ticket::where('id', $request->input('ticket_id'))->firstOrFail();
            $custdetails->voilated = 'on';
            $custdetails->update();

            $ticket->ticketviolation = 'on';
            $ticket->update();

            $tickethistory = new tickethistory();
            $tickethistory->ticket_id = $ticket->id;
            $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
            $tickethistory->ticketviolation = $ticket->ticketviolation;
            $tickethistory->overduestatus = $ticket->overduestatus;
            $tickethistory->status = $ticket->status;
            $tickethistory->replystatus = $ticket->replystatus;
            $tickethistory->currentAction = 'Added Ticket Violation';
            $tickethistory->username = Auth::user()->name;
            $tickethistory->type = Auth::user()->getRoleNames()[0];
            $tickethistory->assignUser = null;


            $tickethistory->save();

            $ticketData = [
                'ticket_id' => $ticket->id,
                'violatedId' => $ticketnote->id,
                'ticketviolation' => $ticket->ticketviolation,
                'violationnote' => $request->input('ticketviolation'),
                'rolename' => Auth::user()->getRoleNames()[0],
                'username' => Auth::user()->name,
                'role_id' => Auth::user()->id,

            ];

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Marked customer as violated' . ' ' . $custdetails->username;
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            return response()->json(['success' => lang('The ticket is added as a violated ticket.', 'alerts')]);
        }
    }
    public function voilationnotedelete(Request $request, $id)
    {
        $this->authorize('Customers Edit');

        $ticketviolation = Ticketviolation::find($id);
        $ticketviolation->delete();

        $ticket = Ticket::where('id', $ticketviolation->ticket_id)->firstOrFail();
        $ticket->ticketviolation = null;
        $ticket->update();

        $tickethistory = new tickethistory();
        $tickethistory->ticket_id = $ticket->id;

        $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
        $tickethistory->overduestatus = $ticket->overduestatus;
        $tickethistory->status = $ticket->status;
        $tickethistory->ticketviolation = $ticket->ticketviolation;
        $tickethistory->currentAction = 'Violation Deleted';
        $tickethistory->username = Auth::user()->name;
        $tickethistory->type = Auth::user()->getRoleNames()[0];
        $tickethistory->assignUser = null;

        $tickethistory->save();
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted a violated note for ticket';
        $activity->ticket_id = $tickethistory->ticket_id;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();


        return response()->json(['success' => lang('Customer violation note deleted successfully..', 'alerts')]);
    }

    public function voilationedit(Request $request, $id)
    {
        $this->authorize('Customers Edit');

        $ticketviolation = Ticketviolation::find($id);

        return response()->json(['violation' => $ticketviolation, 'success' => lang('Customer violation note details fetched successfully..', 'alerts')]);
    }

    public function unvoilating(Request $request, $id)
    {
        $cust = Customer::find($id);
        $cust->voilated = null;
        $cust->update();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Unviolated a customer' . ' ' . $cust->username;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'Customer removed from voilated customer.']);
    }
    public function customersupdate(Request $request, $id)
    {
        $this->authorize('Customers Edit');
        $request->validate([
            'firstname' => 'required|string|max:255',
            'lastname' => 'required|string|max:255',
            'email' => 'required|string|email|max:255',
        ]);

        if ($request->phone) {
            $request->validate([
                'phone' => 'numeric',
            ]);
        }
        $id = decrypt($id);

        $user = Customer::where('id', $id)->findOrFail($id);
        $userexist = Customer::get();
        $userarray = [];
        foreach ($userexist as $userexists) {
            array_push($userarray, $userexists->email);
        }

        if ($user->email != $request->email && in_array($request->email, $userarray)) {
            return response()->json(['error' => 'You are given email is already existing please provide correct email.']);
        }

        $user->firstname = $request->input('firstname');
        $user->lastname = $request->input('lastname');
        $user->username = $request->input('firstname') . ' ' . $request->input('lastname');
        $user->country = $request->input('country');
        $user->email = $request->input('email');
        $user->country = $request->input('country');
        $user->timezone = $request->input('timezone');
        $user->status = $request->input('status');
        $user->voilated = $request->input('voilated');
        $user->phone = $request->input('phone');

        $user->update();

        $ticketcustomfield = TicketCustomfield::where('cust_id', $id)->get();
        foreach ($ticketcustomfield as $customfield) {
            if ($customfield->privacymode == '1') {
                $customfield->values = encrypt($request->input('custom_' . $customfield->id));
            } else {
                $customfield->values = $request->input('custom_' . $customfield->id);
            }
            $customfield->save();
        }


        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated customer profile of' . ' ' . $user->username;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        $request->session()->forget('email', $user->email);

        return response()->json(['success' => 'The customer profile was successfully updated.']);
    }


    /**
     * @return \Illuminate\Support\Collection
     */
    public function customercsv(Request $req)
    {

        $validator = Validator::make(
            $req->all(),
            [

                'file' => 'required|file|mimes:xlsx,csv,txt',
            ],
            [
                'file.mimes' => 'The file must be a file of type: xlsx, csv.',

            ]
        );
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        $file = $req->file('file')->store('import');
        $import = new CustomerImport;
        Excel::import($import, $file);

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Imported Customers.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        if ($import->hasData) {
            return response()->json(['success' => 'The Customer list was imported successfully.']);
        } else {
            return response()->json(['error' => 'The imported file does not contain any data.']);
        }

        $import = Excel::import(new CustomerImport, $file);

        return response()->json(['success' => 'The Customer list was imported successfully.']);
    }


    public function adminLogin(Request $request, $id)
    {
        // if ($request->session()->get('customerlogin')) {
        //     request()->session()->forget('password_hash_customer');
        //     request()->session()->forget('customerlogin');
        //     Auth::guard('customer')->logout();
        // }

        // $customerExist = Customer::where(['id' => $id, 'status' => 0])->exists();
        // if ($customerExist) {
        //     return response()->json(['error' => 'The account has been deactivated.']);
        // }
        // Auth::guard('customer')->loginUsingId($id, true);
        // $request->session()->put('customerlogin', $id);
        // return response()->json(['success' => 'Customer Logged In SuccessFully', 'redirect' => true]);


        if ($request->session()->get('customerlogin')) {
            request()->session()->forget('password_hash_customer');
            request()->session()->forget('customerlogin');

            if ($request->session()->get('twofactoremail')) {
                request()->session()->forget('twofactoremail');
            }

            if ($request->session()->get('googleauthid')) {
                request()->session()->forget('googleauthid');
            }

            Auth::guard('customer')->logout();
        }
        $id = decrypt($id);
        $customerExist = Customer::where(['id' => $id, 'status' => 0])->exists();

        if ($customerExist) {
            return response()->json(['error' => 'The account has been deactivated.']);
            // return redirect()->back()->with('success', lang('The account has been deactivated.', 'alerts'));
        }
        Auth::guard('customer')->loginUsingId($id, true);
        $request->session()->put('customerlogin', $id);
        $cust = Customer::find($id);
        if ($cust) {
            if ($cust->custsetting->twofactorauth == 'emailtwofact') {
                $request->session()->put('twofactoremail', $cust->email);
            }
            if ($cust->custsetting->twofactorauth == 'googletwofact') {
                $request->session()->put('googleauthid', $cust->email);
            }
            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Initiated Login as Customer.';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            return response()->json(['success' => 'Customer Logged In SuccessFully', 'redirect' => true]);
            return redirect()->intended('customer/');
        } else {
            return back()->with('error', 'This customer account is not available/deleted to login');
        }
    }

    public function customersdelete($id)
    {
        $this->authorize('Customers Delete');
        $id = decrypt($id);
        $user = Customer::findOrFail($id);
        $ticket = $user->tickets()->get();

        foreach ($ticket as $tickets) {
            foreach ($tickets->getMedia('ticket') as $media) {
                $media->delete();
            }
            foreach ($tickets->comments as $comment) {
                foreach ($comment->getMedia('comments') as $media) {
                    $media->delete();
                }
                $comment->delete();
            }
            $tickets->delete();
        }
        $user->custsetting()->delete();
        // $user->customercustomsetting()->delete();
        $customfields = TicketCustomfield::where('cust_id', $id)->get();
        foreach ($customfields as $customfield) {
            $customfield->delete();
        }

        $custnotifications = senduserlist::where('tocust_id', $user->id)->get();
        foreach ($custnotifications as $custnotification) {
            $custnotifycount = senduserlist::where('mail_id', $custnotification->mail_id)->count();
            if ($custnotifycount == 1) {
                $custnotification->sendmaildata->delete();
            }
            $custnotification->delete();
        }
        $user->delete();
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted a Customer.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'The customer was deleted successfully.']);
    }


    public function customermassdestroy(Request $request)
    {
        $student_id_arrays = $request->input('id');
        $student_id_array = array_map(function ($encryptedValue) {
            return decrypt($encryptedValue);
        }, $student_id_arrays);

        $customers = Customer::whereIn('id', $student_id_array)->get();

        foreach ($customers as $customer) {

            foreach ($customer->tickets()->get() as $tickets) {
                foreach ($tickets->getMedia('ticket') as $media) {
                    $media->delete();
                }
                foreach ($tickets->comments as $comment) {
                    foreach ($comment->getMedia('comments') as $media) {
                        $media->delete();
                    }
                    $comment->delete();
                }
                $tickets->delete();
            }
            $customer->custsetting()->delete();
            $custnotifications = senduserlist::where('tocust_id', $customer->id)->get();
            foreach ($custnotifications as $custnotification) {
                $custnotifycount = senduserlist::where('mail_id', $custnotification->mail_id)->count();
                if ($custnotifycount == 1) {
                    $custnotification->sendmaildata->delete();
                }
                $custnotification->delete();
            }
            // $customer->customercustomsetting()->delete();
            $customer->delete();


            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Deleted multiple Customer.';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
        }
        return response()->json(['success' => 'The customer was deleted successfully.']);
    }

    public function usersetting(Request $request)
    {
        $users = User::find($request->user_id);
        $users->darkmode = $request->dark;
        $users->update();
        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }

    public function emailonoff(Request $request)
    {
        $useting = usersettings::where('users_id', $request->userid)->first();

        if ($useting == null) {
            $usettingcreate = new usersettings();
            $usettingcreate->users_id  = $request->userid;
            $usettingcreate->emailnotifyon = $request->emailvalue;
            $usettingcreate->save();
        } else {
            $useting->emailnotifyon = $request->emailvalue;
            $useting->update();
        }
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Changed email settings';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'Updated successfully']);
    }

    public function emptwofactqr(Request $request)
    {
        // $user = User::find($request->cust_id);
        $user = User::find($request->user_id);
        if (!Hash::check($request->password, $user->password)) {
            return response()->json(['error' => 'You are entered an invalid password.', 'message' => 'wrongpassword']);
        } else {
            if ($user) {
                if ($request->emptwofact) {

                    $google2fa = app('pragmarx.google2fa');
                    $google2fa_secret = $google2fa->generateSecretKey();
                    $email = $user->email;
                    $domainname = parse_url(url('/'));
                    $request->session()->put('google2faemail', $email);
                    $QR_Image = $google2fa->getQRCodeInline(
                        $domainname['host'],
                        config('app.name'),
                        $google2fa_secret
                    );
                    $geolocation = GeoIP::getLocation(request()->getClientIp());
                    $agent = new Agent();
                    $activity = new EmployeeActivity();
                    $activity->user_id = Auth::user()->id;
                    $activity->activity_type = 'Reconfigured Google TwoFactor Authentication.';
                    $activity->ip_address = $geolocation->ip;
                    $activity->browser = $agent->browser();
                    $activity->device = $agent->device();
                    $activity->save();
                    return response()->json(['success' => "Scan To activate two factor authentication", 'QR_Image' => $QR_Image, 'secret' => $google2fa_secret, 'workprogress' => 'workingmode']);
                } else {
                    $geolocation = GeoIP::getLocation(request()->getClientIp());
                    $agent = new Agent();
                    $activity = new EmployeeActivity();
                    $activity->user_id = Auth::user()->id;
                    $activity->activity_type = 'Disabled Google TwoFactor Authentication.';
                    $activity->ip_address = $geolocation->ip;
                    $activity->browser = $agent->browser();
                    $activity->device = $agent->device();
                    $activity->save();

                    $user->update(['google2fa_secret' => null,]);

                    $user->update(['twofactorauth' => null,]);

                    return response()->json(['success' => lang('successfully disabled your two factor authentication.', 'alerts'), 'workprogress' =>
                    'notworkingmode']);
                }
            }
        }
    }

    public function empgoogle2faotp(Request $request)
    {

        $otp = $request->otp;

        $user = User::find($request->id);

        $google2fa = new Google2FA();
        $isValidOTP = $google2fa->verifyKey($request->secret_key_value, $otp, 0);
        if ($isValidOTP) {
            $user->update(['twofactorauth' => 'googletwofact', 'google2fa_secret' => encrypt($request->secret_key_value)]);
            $request->session()->put('admingoogleauthid', $user->email);

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Enabled Google TwoFacor Authentication.';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
            return response()->json(['success' => 'Verified']);
        } else {
            return response()->json(['error' => 'failed']);
        }
    }

    public function empemail2fa(Request $request)
    {
        $user = User::find($request->cust_id);
        if (!Hash::check($request->password, $user->password)) {
            return response()->json(['error' => 'You entered an invalid password.', 'message' => 'wrongpassword']);
        } else {
            if ($request->emailtwofact) {
                $user->update(['twofactorauth' => 'emailtwofact',]);
                $request->session()->forget('admintwofactoremail');
                $verifyuser = VerifyOtp::where('cust_id', $user->email);
                if ($verifyuser->exists()) {
                    $verifyuser->delete();
                }
                $request->session()->put('admintwofactoremail', $user->email);
                $geolocation = GeoIP::getLocation(request()->getClientIp());
                $agent = new Agent();
                $activity = new EmployeeActivity();
                $activity->user_id = Auth::user()->id;
                $activity->activity_type = 'Enabled Email TwoFactor Authentication.';
                $activity->ip_address = $geolocation->ip;
                $activity->browser = $agent->browser();
                $activity->device = $agent->device();
                $activity->save();
            } else {
                $user->update(['twofactorauth' => null,]);
                $geolocation = GeoIP::getLocation(request()->getClientIp());
                $agent = new Agent();
                $activity = new EmployeeActivity();
                $activity->user_id = Auth::user()->id;
                $activity->activity_type = 'Disabled Email TwoFactor Authentication.';
                $activity->ip_address = $geolocation->ip;
                $activity->browser = $agent->browser();
                $activity->device = $agent->device();
                $activity->save();
                return response()->json(['success' => 'successfully disabled your two factor authentication.', 'disabled' => true]);
            }
            return response()->json(['success' => 'Email two factor authentication is enabled.']);
        }
    }


    public function google2faadminlogin($email)
    {
        $now = now();
        $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;

        // $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->whereDate('enddate', '>=', $now->toDateString())->where('status', '1')->get();
        // $data['holidays'] =  $holidays;
        $now = now();
        $currentYear = $now->year;
        $activeHolidays = Holiday::where('status', 1)->get();


        $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
            $holidayStart = Carbon::parse($holiday->startdate);
            $holidayEnd = Carbon::parse($holiday->enddate);
            if ($holiday->is_fixed) {
                return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
            }
            return $holidayStart->isSameDay($now);
        });

        if (session()->has('admingoogleauthid')) {
            return response()->json(['success' => 'Success']);
        }

        if (!session()->has('google2faemail')) {
            session()->put('google2faemail', $email);
        }

        $data['email'] = session()->get('google2faemail');

        return $data;
    }

    public function admingoogle2faotpverify(Request $request)
    {
        $otp = (string) $request->one_time_password;

        $user = User::where('email', $request->email)->first();

        $google = decrypt($user->google2fa_secret);

        $google2fa = new Google2FA();
        $isValidOTP = $google2fa->verifyKey($google, $otp, 0);


        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        if ($isValidOTP) {
            $request->session()->put('admingoogleauthid', $user->email);
            $activity = new EmployeeActivity();
            $activity->user_id = $user->id;
            $activity->activity_type = 'Logged in to the application';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
            return response()->json(['success' => 'Success']);
        } else {
            $activity = new EmployeeActivity();
            $activity->user_id = $user->id;
            $activity->activity_type = 'Failed login attempt';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
            return response()->json(['error' => 'Invalid otp.']);
        }
    }

    public function emailtwofactorlogin($email)
    {
        $now = now();
        $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;

        // $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->whereDate('enddate', '>=', $now->toDateString())->where('status', '1')->get();
        // $data['holidays'] =  $holidays;

        $now = now();
        $currentYear = $now->year;
        $activeHolidays = Holiday::where('status', 1)->get();


        $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
            $holidayStart = Carbon::parse($holiday->startdate);
            $holidayEnd = Carbon::parse($holiday->enddate);
            if ($holiday->is_fixed) {
                return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
            }
            return $holidayStart->isSameDay($now);
        });

        $data['email'] = $email;

        if (session()->has('admintwofactoremail')) {
            return response()->json(['success' => 'Success']);
        }
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();

        $verifyotp = VerifyOtp::where('cust_id', $email)->first();
        if (!$verifyotp) {
            $verifyOtp = VerifyOtp::create([
                'cust_id' => $email,
                'otp' => rand(100000, 999999),
                'type' => 'twofactorotp',
            ]);

            $guestticket = [

                'otp' => $verifyOtp->otp,
                'guestemail' => $verifyOtp->cust_id,
                'guestname' => 'adminuser',
            ];
            try {
                dispatch((new MailSend($verifyOtp->cust_id, 'two_factor_authentication_otp_send', $guestticket)));
            } catch (\Exception $e) {
            }
        }

        return $data;
    }

    public function resendotp(Request $request)
    {
        if ($request->session()->has('admintwofactoremail')) {
            return redirect()->route('admin.dashboard');
        }
        $verifyUser = VerifyOtp::where('cust_id', $request->email)->first();
        if ($verifyUser) {
            $verifyUser->otp = rand(100000, 999999);
            $verifyUser->update();
        }

        $guestticket = [
            'otp' => $verifyUser->otp,
            'guestemail' => $verifyUser->cust_id,
            'guestname' => 'adminuser',
        ];
        try {
            dispatch((new MailSend($verifyUser->cust_id, 'two_factor_authentication_otp_send', $guestticket)));
        } catch (\Exception $e) {

            return response()->json(['success' => lang('Please check your Email', 'alerts'), 'email' => 'exists']);
        }
        return response()->json(['success' => lang('Please check your Email', 'alerts'), 'email' => 'exists']);
        // return redirect()->route('admin.emailtwofactorlogin', ['email' => $verifyUser->cust_id]);
    }


    public function sessionLogout(Request $request)
    {
        $user = Auth::user();
        if ($request->stayin) {
            $user->last_activity = now();
            $user->save();
            return true;
        } else {

            $user->last_activity = null;
            $user->save();
            $userType = $request->route()->action['prefix'];
            $exploded = explode('/', $userType)[1];
            $response = response()->json(['message' => 'User logged out successfully']);
            if ($exploded === 'admin') {
                $response->header('X-User-Type', 'admin');
            }
            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Logged out of the application';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
            return $response;
        }
    }
}
