<?php

namespace App\Http\Controllers\Admin;

use App\Events\LiveNotification;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Pages;
use App\Models\EmailTemplate;
use App\Jobs\MailSend;
use Mail;
use App\Models\Imap_setting;
use App\Models\User;
use App\Notifications\InformationSendToUsers;
use Swift_Mailer;
use Swift_SmtpTransport;
use \Webklex\IMAP\Facades\Client;
use Illuminate\Support\Facades\Validator;
use File;
use Image;
use Torann\GeoIP\Facades\GeoIP;
use Jenssegers\Agent\Agent;
use App\Models\EmployeeActivity;
use Illuminate\Support\Facades\Auth;

class AdminSettingController extends Controller
{
    /**
     * Captcha Settings.
     *
     * @return \Illuminate\Http\Response
     */
    public function captcha()
    {
        $this->authorize('Captcha Setting Access');
        $title = Apptitle::first();
        $data['title'] = $title;

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

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        return view('admin.generalsetting.captchasetting')->with($data);
    }

    /**
     * Captcha Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    public function captchastore(Request $request)
    {
        $this->validate($request, [
            'googlerecaptchakey' => 'required|max:10000',
            'googlerecaptchasecret' => 'required|max:10000',
        ]);
        $data['GOOGLE_RECAPTCHA_KEY'] = $request->googlerecaptchakey;
        $data['GOOGLE_RECAPTCHA_SECRET'] = $request->googlerecaptchasecret;
        if($request->input('g-recaptcha-response') != null){
            $this->updateSettings($data);

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Google Re-Captcha Site And Secret Key Stored';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            return back()->with('success', lang('Updated successfully', 'alerts'));
        }else{
            return back()->with('error', lang('Invalid reCAPTCHA credentials.', 'alerts'));
        }

    }

    public function captchatypestore(Request $request)
    {
        $data['captchatype'] = $request->captchatype;
        $this->updateSettings($data);

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Google Re-Captcha Type Changed';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => lang('Updated successfully', 'alerts')]);
    }
    /**
     * Email Settings.
     *
     * @return \Illuminate\Http\Response
     */

    public function email()
    {

        $this->authorize('Email Setting Access');
        $title = Apptitle::first();
        $data['title'] = $title;

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

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        return view('admin.email.email')->with($data);
    }
    /**
     * Ticket Settings.
     *
     * @return \Illuminate\Http\Response
     */

    public function ticketsetting()
    {
        $this->authorize('Ticket Setting Access');

        $title = Apptitle::first();
        $data['title'] = $title;

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

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;


        return view('admin.generalsetting.ticketsetting')->with($data);
    }

    /**
     * Ticket Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    public function ticketsettingstore(Request $request)
    {
        $request->validate([
            'ticketid' => 'required|max:5',
            'ticketcharacter' => 'required|integer|min:10|max:255',
        ]);

        if ($request->AUTO_CLOSE_TICKET) {
            $request->validate([
                'autoclosetickettime' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->AUTO_OVERDUE_TICKET) {
            $request->validate([
                'autooverduetickettime' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->AUTO_RESPONSETIME_TICKET != null) {
            $request->validate([
                'autoresponsetickettime' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->AUTO_NOTIFICATION_DELETE_ENABLE) {
            $request->validate([
                'autonotificationdeletedays' => 'required|numeric|gt:0'
            ]);
        }

        if ($request->customer_panel_employee_protect) {
            $request->validate([
                'employeeprotectname' => 'required|max:255'
            ]);
        }
        if ($request->trashed_ticket_autodelete != null) {
            $request->validate([
                'trashed_ticket_delete_time' => 'required|numeric|gt:0',
            ]);
        }

        $data['AUTO_CLOSE_TICKET']  =  $request->has('AUTO_CLOSE_TICKET') ? 'yes' : 'no';
        $data['AUTO_CLOSE_TICKET_TIME']  =  $request->input('autoclosetickettime');
        $data['AUTO_OVERDUE_TICKET']  =  $request->has('AUTO_OVERDUE_TICKET') ? 'yes' : 'no';
        $data['AUTO_OVERDUE_CUSTOMER']  =  $request->has('AUTO_OVERDUE_CUSTOMER') ? 'yes' : 'no';
        $data['AUTO_OVERDUE_TICKET_TIME']  =  $request->input('autooverduetickettime');
        $data['trashed_ticket_autodelete']  =  $request->has('trashed_ticket_autodelete') ? 'on' : 'off';
        $data['trashed_ticket_delete_time']  =  $request->input('trashed_ticket_delete_time');
        $data['AUTO_RESPONSETIME_TICKET']  =  $request->has('AUTO_RESPONSETIME_TICKET') ? 'yes' : 'no';
        $data['AUTO_RESPONSETIME_TICKET_TIME']  =  $request->input('autoresponsetickettime');
        $data['AUTO_NOTIFICATION_DELETE_ENABLE']  =  $request->has('AUTO_NOTIFICATION_DELETE_ENABLE') ? 'on' : 'off';
        $data['AUTO_NOTIFICATION_DELETE_DAYS']  =  $request->input('autonotificationdeletedays');
        $data['CUSTOMER_TICKETID']  =  $request->input('ticketid');
        $data['NOTE_CREATE_MAILS']  =  $request->has('NOTE_CREATE_MAILS') ? 'on' : 'off';
        $data['PRIORITY_ENABLE']  =  $request->has('PRIORITY_ENABLE') ? 'yes' : 'no';
        $data['TICKET_CHARACTER']  =  $request->input('ticketcharacter');
        $data['customer_panel_employee_protect']  =  $request->has('customer_panel_employee_protect') ? 'on' : 'off';
        $data['employeeprotectname']  =  $request->input('employeeprotectname');
        $data['admin_reply_mail']  =  $request->has('admin_reply_mail') ? 'yes' : 'no';
        $data['ticketrating']  =  $request->has('ticket_rating') ? 'on' : 'off';

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }
    /**
     * Email Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */

    public function emailStore(Request $request)
    {
        if ($request->ajax()) {
            if ($request->mail_driver == 'sendmail') {
                $request->validate([
                    'mail_from_name' => 'required|max:10000',
                    'mail_from_address' => 'required|max:10000'
                ]);
            }
            if ($request->mail_driver == 'smtp') {
                $request->validate([
                    'mail_host' => 'required|max:10000',
                    'mail_port' => 'required|numeric',
                    'mail_encryption' => 'required|max:10000',
                    'mail_username' => 'required|max:10000',
                    'mail_password' => 'required|max:10000',
                    'mail_from_name' => 'required|max:10000',
                    'mail_from_address' => 'required|max:10000'
                ]);

                //validating smtp connection
                $transport = new Swift_SmtpTransport($request->mail_host, $request->mail_port);
                $transport->setUsername($request->mail_username);
                $transport->setPassword($request->mail_password);
                $transport->setEncryption($request->mail_encryption);

                try {
                    $mailer = new Swift_Mailer($transport);
                    $mailer->getTransport()->start();
                } catch (\Swift_TransportException $e) {
                    return response()->json(['code' => 500, 'imapconnectionError' => 'notconnected', 'error' => lang('Your smtp credentials are invalid, please verify your entered details.', 'alerts')], 500);
                }
            }


            $data = $request->only(['mail_driver', 'mail_host', 'mail_port', 'mail_from_address', 'mail_from_name', 'mail_encryption', 'mail_username', 'mail_password']);

            $this->updateSettings($data);

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

            return response()->json(['code' => 200, 'success' => lang('Updated successfully', 'alerts')], 200);
        }
    }



    /**
     * Email Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendTestMail(Request $request)
    {

        $email = $request->get('email');
        if($email != null){
            try {
                Mail::send('admin.email.template', ['emailBody' => "This is a test email sent by system"], function ($message) use ($email) {
                    $message->to($email)->subject('Test Email');
                });

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

                return back()->with('success', lang('A test email was sent successfully.', 'alerts'));
            } catch (\Exception $e) {
                return back()->with('error',  lang('The test email couldn’t be sent.', 'alerts'));
            }
        }else{
            return back()->with('error',  lang('Please enter the email to send test mail.', 'alerts'));
        }
    }


    /**
     * Email Settings.
     *
     * @return \Illuminate\Http\Response
     */

    public function emailtemplates()
    {
        $this->authorize('Email Template Access');

        $title = Apptitle::first();
        $data['title'] = $title;

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

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        $emailtemplates = EmailTemplate::all();
        $data['emailtemplates'] = $emailtemplates;

        return view('admin.email.index')->with($data);
    }

    /**
     * Email Settings.
     *
     * @return \Illuminate\Http\Response
     */
    public function emailtemplatesEdit($id)
    {
        $this->authorize('Email Template Edit');

        $title = Apptitle::first();
        $data['title'] = $title;

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

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        $template = EmailTemplate::find($id);
        $data['template'] = $template;

        return view('admin.email.edit')->with($data);
    }

    public function emailtemplatesUpdate(Request $request, $id)
    {
        $this->authorize('Email Template Edit');

        $request->validate([
            'subject' => 'required|max:255',
            'body' => 'required'
        ]);
        if (strip_tags($request->body) == "") {
            return back()->with('bodyNull', lang('Email Body field is required.', 'alerts'));
        }

        $template = EmailTemplate::find($id)->update($request->only(['subject', 'body']));

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

        return redirect('/admin/emailtemplates')->with('success', lang('Updated successfully', 'alerts'));
    }

    public function enableemailtoticket(Request $request)
    {
        if ($request->has('IMAP_EMAIL_PROCESS_LIMIT_SWITCH')) {
            $request->validate([
                'IMAP_EMAIL_TEMPLATE_LIMIT' => 'required|numeric|gt:0',
            ]);
        }

        $data['IMAP_STATUS']  =  $request->has('IMAP_STATUS') ? 'on' : 'off';
        $data['IMAP_EMAIL_AUTO_DELETE']  =  $request->has('IMAP_EMAIL_AUTO_DELETE') ? 'on' : 'off';
        $data['IMAP_EMAIL_PROCESS_LIMIT_SWITCH']  =  $request->has('IMAP_EMAIL_PROCESS_LIMIT_SWITCH') ? 'on' : 'off';
        $data['IMAP_EMAIL_TEMPLATE_LIMIT']  =  $request->IMAP_EMAIL_TEMPLATE_LIMIT;

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function registerpopup(Request $request)
    {

        $data['GOOGLEFONT_DISABLE'] = $request->googledisable;
        $data['FORCE_SSL'] = $request->forcessl;
        $data['DARK_MODE'] = $request->darkmode;
        $data['SPRUKOADMIN_P'] = $request->sprukoadminp;
        $data['ENVATO_ON'] = $request->envatoon;
        $data['purchasecode_on'] = $request->purchasecodeon;
        $data['article_count'] = $request->articlecount;
        $data['sidemenu_icon_style'] = $request->sidemenustyle;

        $this->updateSettings($data);

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

        return response()->json(['code' => 200, 'success' => lang('Updated successfully', 'alerts')], 200);
    }


    public function filesettingstore(Request $request)
    {
        $request->validate([
            'usermaxfileupload' => 'required|numeric|gt:0',
            'userfileuploadmaxsize' => 'required|numeric|gt:0',
            'userfileuploadtypes' => 'required',
            'maxfileupload' => 'required|numeric|gt:0',
            'fileuploadmax' => 'required|numeric|gt:0',
            'fileuploadtypes' => 'required',
        ]);

        $userfileuploadtypes = explode(',',$request->userfileuploadtypes);
        $fileuploadtypes = explode(',',$request->fileuploadtypes);
        $allowedFormats = ['.xlsx', '.csv', '.docx', '.pdf', '.jpg', '.jpeg', '.png', '.mp3', '.wav', '.mp4', '.zip', '.webp'];
        foreach($userfileuploadtypes as $userfileuploadtype){
            if(!in_array($userfileuploadtype, $allowedFormats)){
                return back()->with('error', lang('You are enter wrong file formats please enter correct format.', 'alerts'));
            }
        }
        foreach($fileuploadtypes as $fileuploadtype){
            if(!in_array($fileuploadtype, $allowedFormats)){
                return back()->with('error', lang('You are enter wrong file formats please enter correct format.', 'alerts'));
            }
        }

        $data['USER_MAX_FILE_UPLOAD']  =  $request->input('usermaxfileupload');
        $data['USER_FILE_UPLOAD_MAX_SIZE']  =  $request->input('userfileuploadmaxsize');
        $data['USER_FILE_UPLOAD_TYPES']  =  $request->input('userfileuploadtypes');
        $data['MAX_FILE_UPLOAD']  =  $request->input('maxfileupload');
        $data['FILE_UPLOAD_MAX']  =  $request->input('fileuploadmax');
        $data['FILE_UPLOAD_TYPES']  =  $request->input('fileuploadtypes');

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function botresponsettingcreate(Request $request)
    {
        $title = Apptitle::first();
        $data['title'] = $title;

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

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        return view('admin.generalsetting.botresponsesetting')->with($data);
    }

    public function botsettingstore(Request $request)
    {
        $request->validate([
            'bot_name' => 'required',
            'botsresponse_time' => 'required|numeric|gt:0',
            'response_description' => 'required',
            'response_description_exclude_business_hours' => 'required',
        ]);

        $data['botresponseenable']  =  $request->has('botresponseenable') ? 'on' : 'off';
        $data['bot_name']  =  $request->input('bot_name');
        $data['botsresponse_time']  =  $request->input('botsresponse_time');
        $data['time_detection']  =  $request->input('time_detection');
        $data['response_description']  =  $request->input('response_description');
        $data['response_description_exclude_business_hours']  =  $request->input('response_description_exclude_business_hours');

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

              $validator = Validator::make($fileArray, $rules);

              if ($validator->fails())
                {
                    return redirect()->back()->with('error', lang('Please check the format and size of the file.', 'alerts'));
                }else
                {

                    $destination = public_path() . "" . '/uploads/profile/botprofile';
                    $image_name = time() . '.' . $file->getClientOriginalExtension();
                    $resize_image = Image::make($file->getRealPath());

                    $resize_image->resize(80, 80, function($constraint){
                    $constraint->aspectRatio();
                    })->save($destination . '/' . $image_name);

                    $destinations = public_path() . "" . '/uploads/profile/botprofile'.setting('bot_image');
                    if(File::exists($destinations)){
                        File::delete($destinations);
                    }
                    $file = $request->file('image');
                    $data['bot_image']  =  $image_name;
                }


        }

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function botimagedelete(Request $request)
    {
        $destinations = public_path() . "" . '/uploads/profile/botprofile/'.setting('bot_image');

        if(File::exists($destinations)){
            File::delete($destinations);

            $data['bot_image']  =  null;

            $this->updateSettings($data);

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


            return response()->json(['code' => 200, 'success' => lang('Image is deleted successfully.', 'alerts')], 200);
        }else{
            return response()->json(['code' => 500, 'error' => lang('The image path is not exists.', 'alerts')], 500);
        }

    }

    public function chatbotsettingstore(Request $request)
    {
        $request->validate([
            'chat_bot_name' => 'required',
        ]);

        $data['chat_bot_name']  =  $request->input('chat_bot_name');

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

            $validator = Validator::make($fileArray, $rules);

            if ($validator->fails()){
                return redirect()->back()->with('error', lang('Please check the format and size of the file.', 'alerts'));
            }else{
                $existprovider = existprovider(setting('chat_bot_storage_disk'));
                if($existprovider)
                $existprovider->provider::delete('/uploads/profile/chatbotprofile' . "/" . setting('chat_bot_image'));

                $image_name = time() . '.' . $file->getClientOriginalExtension();
                $provider = storage()->provider;
                $upload =  $provider::uploadprofile($file,$image_name);
                if($upload){
                    $data['chat_bot_image'] = $image_name;
                    $data['chat_bot_storage_disk'] = storage()->storage_disk;
                }else{
                    return redirect()->back()->with('error', lang('Image upload failed please try again.', 'alerts'));
                }
            }
        }

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function chatbotimagedelete(Request $request)
    {
        $existprovider = existprovider(setting('chat_bot_storage_disk'));

        if($existprovider){
            $existprovider->provider::delete('/uploads/profile/chatbotprofile' . "/" . setting('chat_bot_image'));

            $data['chat_bot_image']  =  null;
            $data['chat_bot_storage_disk']  =  null;

            $this->updateSettings($data);

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

            return response()->json(['code' => 200, 'success' => lang('The chatbot image has been deleted successully.', 'alerts')], 200);
        }else{
            return response()->json(['code' => 500, 'error' => lang('The image path is not exists.', 'alerts')], 500);
        }

    }

    public function knowledge(Request $request)
    {

        $data['KNOWLEDGE_ENABLE']  =  $request->KNOWLEDGE_ENABLE;
        $data['FAQ_ENABLE']  =  $request->FAQ_ENABLE;

        $this->updateSettings($data);


        return response()->json(['code' => 200, 'success' => lang('Updated successfully', 'alerts')], 200);
    }

    public function profileagent(Request $request)
    {

        $data['PROFILE_AGENT_ENABLE']  =  $request->PROFILE_AGENT_ENABLE;

        $this->updateSettings($data);


        return response()->json(['code' => 200, 'success' => lang('Updated successfully', 'alerts')], 200);
    }


    /**
     * Frontend Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    public function frontendStore(Request $request)
    {
        $request->validate([
            'theme_color' => 'required',
            'theme_color_dark' => 'required',
        ]);

        $data = $request->only(['theme_color', 'theme_color_dark']);

        $this->updateSettings($data);

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

        return back()->with('success',  lang('Updated successfully', 'alerts'));
    }


    public function googleanalytics()
    {
        $this->authorize('Google Analytics Access');
        $title = Apptitle::first();
        $data['title'] = $title;

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

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;


        return view('admin.generalsetting.googleanalytics')->with($data);
    }

    /**
     * Googleanalytics Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    public function googleanalyticsStore(Request $request)
    {

        $request->validate([
            'GOOGLE_ANALYTICS' => 'required',
        ]);
        $data['GOOGLE_ANALYTICS_ENABLE']  =  $request->has('GOOGLE_ANALYTICS_ENABLE') ? 'yes' : 'no';
        $data['GOOGLE_ANALYTICS'] = $request->input(['GOOGLE_ANALYTICS']);

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function languagesettingstore(Request $request)
    {

        $data = $request->only(['default_lang']);

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function envatosetting()
    {
        if(setting('ENVATO_ON') != 'on'){
            abort(403);
        }

        $this->authorize('Envato Access');
        $title = Apptitle::first();
        $data['title'] = $title;

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

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        return view('admin.envato.envatosetting')->with($data);
    }

    public function expiredsupport(Request $request)
    {
        $request->validate([
            'SUPPORT_POLICY_URL' => 'required|url',
        ]);

        $data['purchasecode_on']  =  $request->has('purchasecode_on') ? 'on' : 'off';
        $data['ENVATO_EXPIRED_BLOCK']  =  $request->has('ENVATO_EXPIRED_BLOCK') ? 'on' : 'off';
        $data['SUPPORT_POLICY_URL']  =  $request->input(['SUPPORT_POLICY_URL']);
        $this->updateSettings($data);

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

        return back()->with('success',  lang('Updated successfully', 'alerts'));
    }

    public function datetimeformatstore(Request $request)
    {

        $data['date_format'] = $request->date_format;
        $data['time_format'] = $request->time_format;

        $this->updateSettings($data);

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function startweekstore(Request $request)
    {

        $data['start_week'] = $request->start_week;

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }


    public function timezoneupdate(Request $request)
    {
        $data['default_timezone'] = $request->timezones;

        $this->updateSettings($data);

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

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function logindisable(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
        ]);

        $data['login_disable_statement'] = $request->name;
        $this->updateSettings($data);

        return response()->json(['success' =>  lang('Updated successfully', 'alerts')], 200);
    }

    public function customerautologout(Request $request)
    {

        if($request->has('admin_users_inactive_auto_logout')){
            $request->validate([
                'admin_users_inactive_auto_logout_time' => 'required|numeric|gt:0',
            ]);
        }

        $data['admin_users_inactive_auto_logout']  =  $request->has('admin_users_inactive_auto_logout') ? 'on' : 'off';
        $data['admin_users_inactive_auto_logout_time']  =  $request->input('admin_users_inactive_auto_logout_time');

        $this->updateSettings($data);

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function twofactauthsetting(Request $request)
    {
        $data['Employe_google_two_fact']  =  $request->has('Employe_google_two_fact') ? 'on' : 'off';
        if ($request->has('Employe_google_two_fact') == false) {
            $Users = User::where('twofactorauth', 'googletwofact')->get();
            foreach ($Users as $user) {
                $user->google2fa_secret = null;
                $user->twofactorauth = null;
                $user->update();

                $user->notify(new InformationSendToUsers($user));
                event(new LiveNotification('Ticket has been assigned to you',$user,null,null));

                $ticketData = [
                    'username' => $user->name,
                ];

                if($user->usetting->emailnotifyon == 1){
                    dispatch((new MailSend($user->email, 'send_mail_to_users_when_two_factor_authentication_disabled', $ticketData)));
                }

            }
        }
        $data['Employe_email_two_fact']  =  $request->has('Employe_email_two_fact') ? 'on' : 'off';

        $this->updateSettings($data);

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function geminiSave(Request $request)
    {
        if($request->has('spellCheck') || $request->has('wordSuggestion')){
            $request->validate([
                'geminiApiKey' => 'required|string',
            ]);
        }

        $data['geminiApiKey']  =  $request->input('geminiApiKey');
        $data['spellCheck']  =  $request->has('spellCheck') ? 'on' : 'off';
        $data['wordSuggestion']  =  $request->has('wordSuggestion') ? 'on' : 'off';

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

        $this->updateSettings($data);

        return back()->with('success', lang('Updated successfully', 'alerts'));
    }

    public function bussinesslogodelete(Request $request)
    {
        $data['supporticonimage']  =  null;

        $this->updateSettings($data);

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

        return response()->json(['success' =>  lang('Updated successfully', 'alerts')], 200);
    }



    public function imapstore(Request $request)
    {
        $request->validate([
            'imap_host' => 'required',
            'imap_port' => 'required',
            'imap_protocol' => 'required',
            'imap_encryption' => 'required',
            'imap_username' => 'required',
            'imap_password' => 'required',

        ]);

        if(isset($request->IMAP_STATUS)){
            $client = Client::make([
                'host'          => $request->imap_host,
                'port'          => $request->imap_port,
                'encryption'    => $request->imap_encryption,
                'validate_cert' => true,
                'username'      => $request->imap_username,
                'password'      => $request->imap_password,
                'protocol'      => $request->imap_protocol
            ]);
            try {
                $client->connect();
            } catch (\Exception $e) {
                return redirect()->back()->with('error', lang('Your imap credentials are invalid, please verify your entered details.', 'alerts'));
            }
        }

        $imapdata =  [
            'imap_host' => $request->imap_host,
            'imap_port' => $request->imap_port,
            'imap_protocol' => $request->imap_protocol,
            'imap_encryption' => $request->imap_encryption,
            'imap_username' => $request->imap_username,
            'imap_password' => $request->imap_password,
            'IMAP_STATUS' => $request->IMAP_STATUS ?? 0,
        ];

        $this->updateSettings($imapdata);

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

        return redirect()->back()->with('success', lang('Updated successfully', 'alerts'));
    }

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

        $imap = Imap_setting::find($id);
        $imap->status = $request->status;
        $imap->save();

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

        return response()->json(['code' => 200, 'success' => lang('Status Updated successfully', 'alerts')], 200);
    }

    public function edit($id)
    {
        $data = Imap_setting::find($id);

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

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

    public function smtpcheck()
    {
        $transport = new Swift_SmtpTransport(setting('mail_host'), setting('mail_port'));
        $transport->setUsername(setting('MAIL_USERNAME'));
        $transport->setPassword(setting('MAIL_PASSWORD'));
        $transport->setEncryption(setting('mail_encryption'));

        try {
            $mailer = new Swift_Mailer($transport);
            $mailer->getTransport()->start();
            return response()->json(1);

        } catch (\Swift_TransportException $e) {
            return response()->json(['code' => 500, 'imapconnectionError' => 'notconnected', 'error' => lang('Your smtp credentials are invalid, please setup correctly to add imap settings.', 'alerts')], 500);
        }
    }

    /**
     *  Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    private function updateSettings($data)
    {

        foreach ($data as $key => $val) {
            $setting = Setting::where('key', $key);
            if ($setting->exists())
                $setting->first()->update(['value' => $val]);
        }
    }
}
