<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AllTransactions;
use App\Models\Businesshours;
use App\Notifications\InformationSendToUsers;
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\Models\SocialAuthSetting;
use App\Http\Requests\SocialAuthRequest;
use App\Models\Customer;
use Mail;
use App\Models\User;
use Stripe\Stripe;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;
use App\Models\Imap_setting;
use App\Models\Sendmail;
use App\Models\Ticket\Category;
use Swift_Mailer;
use Swift_SmtpTransport;
use \Webklex\IMAP\Facades\Client;
use Illuminate\Support\Facades\Validator;
use File;
use Image;
use App\Models\MessageTemplates;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;
use Illuminate\Support\Facades\Http;
use laravelLara\infoinst\Jobs\MailSend;

class AdminSettingController extends Controller
{

    /**
     * Social Login Settings.
     *
     * @return \Illuminate\Http\Response
     */

    public function sociallogin()
    {
        $this->authorize('Social Logins Access');
        $sociology = SocialAuthSetting::get();
        return $sociology;
    }

    /**
     * Social Login Settings.
     *
     * @return \Illuminate\Http\Response
     */

    public function socialloginupdate(SocialAuthRequest $request)
    {

        $socialAuth = SocialAuthSetting::first();

        $socialAuth->google_client_id = $request->google_client_id;
        $socialAuth->google_secret_id = $request->google_secret_id;
        ($request->google_status)  == 'enable' ? $socialAuth->google_status = 'enable' : $socialAuth->google_status = 'disable';

        $socialAuth->envato_client_id = $request->envato_client_id;
        $socialAuth->envato_secret_id = $request->envato_secret_id;
        ($request->envato_status) == 'enable' ? $socialAuth->envato_status = 'enable' : $socialAuth->envato_status = 'disable';

        $socialAuth->microsoft_app_id = $request->microsoft_app_id;
        $socialAuth->microsoft_secret_id = $request->microsoft_secret_id;
        ($request->microsoft_status) ? $socialAuth->microsoft_status = 'enable' : $socialAuth->microsoft_status = 'disable';

        $socialAuth->save();


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

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


    public function announcementsetting(Request $request)
    {
        $data['ANNOUNCEMENT_USER']  =  $request->ANNOUNCEMENT_USER;

        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Announcement Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'Updated successfully']);
    }

    /**
     * Captcha Settings.
     *
     * @return \Illuminate\Http\Response
     */
    public function captcha()
    {
        $this->authorize('Captcha Setting Access');
        $data['RECAPTCH_ENABLE_CONTACT'] = setting('RECAPTCH_ENABLE_CONTACT');
        $data['RECAPTCH_ENABLE_REGISTER'] = setting('RECAPTCH_ENABLE_REGISTER');
        $data['RECAPTCH_ENABLE_LOGIN'] = setting('RECAPTCH_ENABLE_LOGIN');
        $data['RECAPTCH_ENABLE_GUEST'] = setting('RECAPTCH_ENABLE_GUEST');
        $data['RECAPTCH_ENABLE_ADMIN_LOGIN'] = setting('RECAPTCH_ENABLE_ADMIN_LOGIN');
        $data['CAPTCHATYPE'] = setting('CAPTCHATYPE');
        $data['GOOGLE_RECAPTCHA_KEY'] = setting('GOOGLE_RECAPTCHA_KEY');
        $data['GOOGLE_RECAPTCHA_SECRET'] = setting('GOOGLE_RECAPTCHA_SECRET');

        $data['DosEnabledCaptcha'] = false;
        if (setting('IPBLOCKTYPE') == "captcha" && setting('DOS_Enable') == "on") {
            $data['DosEnabledCaptcha'] = true;
        }
        return $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;


        $this->updateSettings($data);

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

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

    public function captchatypestore(Request $request)
    {

        $data['captchatype'] = $request->captchatype;
        if ($request->captchatype == "off" && setting('DOS_Enable') == "on") {
            $data['IPBLOCKTYPE'] = "block";
        }
        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Captchatype Settings';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'Updated successfully']);
    }
    /**
     * 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;


        $imaps = Imap_setting::all();
        $imap_count = $imaps->count();

        // Fetch all active categories
        $categories = Category::where('status', '1')->pluck('name', 'id');

        // Add category name to each imap setting
        foreach ($imaps as $imap) {
            $imap->category_name = $categories[$imap->category_id] ?? '~~'; // Set category name or fallback
        }
        $data['imaps'] = $imaps;
        $data['imap_count'] = $imap_count;


        return $data;
    }

    public function gettingSendMailData()
    {
        $this->authorize('Email Setting Access');
        $data['mail_driver'] = setting('mail_driver');
        $data['mail_host'] = setting('mail_host');
        $data['mail_port'] = setting('mail_port');
        $data['mail_encryption'] = setting('mail_encryption');
        $data['mail_username'] = setting('mail_username');
        $data['mail_password'] = setting('mail_password');
        $data['mail_from_name'] = setting('mail_from_name');
        $data['mail_from_address'] = setting('mail_from_address');


        $allCategories = Category::whereIn('display', ['ticket', 'all'])->where('status', '1')->get();
        $data['allCategories'] = $allCategories;

        $data['setting'] = response()->json(['IMAP_STATUS' => setting('IMAP_STATUS'), 'email_delete' => setting('email_delete'), 'email_ticket_limit' => setting('email_ticket_limit')]);


        $ticketquery = Imap_setting::with('category')->latest('updated_at');

        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $ticketquery->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('tickets');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
                $query->orWhereHas('category', function ($query) use ($searchTerm) {
                    $query->where('name', 'LIKE', $searchTerm . '%');
                });
            });
        }
        $items = $ticketquery->paginate($perPage);
        $data['queryList'] = $items;
        return $data;
    }

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

    public function ticketsetting()
    {
        $this->authorize('Ticket Setting Access');
        $attributes = [
            'CONTACT_ENABLE',
            'SPRUKOADMIN_P',
            'SPRUKOADMIN_C',
            'DARK_MODE',
            'REGISTER_POPUP',
            'REGISTER_DISABLE',
            'login_disable',
            'GOOGLEFONT_DISABLE',
            'FORCE_SSL',
            'KNOWLEDGE_ENABLE',
            'FAQ_ENABLE',
            'PROFILE_USER_ENABLE',
            'ENVATO_ON',
            'purchasecode_on',
            'defaultlogin_on',
            'article_count',
            'only_social_logins',
            'sidemenu_icon_style',
            'cust_profile_delete_enable',
            'cust_email_update',
            'MAINTENANCE_MODE',
            'customer_inactive_notify',
            'customer_inactive_notify_date',
            'customer_inactive_week_date',
            'guest_inactive_notify',
            'guest_inactive_notify_date',
            'guest_inactive_week_date',
            'AUTO_RESPONSETIME_TICKET_TIME',
            'AUTO_RESPONSETIME_TICKET',
            'AUTO_CLOSE_TICKET',
            'AUTO_CLOSE_TICKET_TIME',
            'USER_REOPEN_ISSUE',
            'USER_REOPEN_TIME',
            'AUTO_OVERDUE_TICKET',
            'AUTO_OVERDUE_CUSTOMER',
            'AUTO_OVERDUE_TICKET_TIME',
            'AUTO_NOTIFICATION_DELETE_ENABLE',
            'AUTO_NOTIFICATION_DELETE_DAYS',
            'GUEST_TICKET',
            'USER_FILE_UPLOAD_ENABLE',
            'GUEST_FILE_UPLOAD_ENABLE',
            'GUEST_TICKET_OTP',
            'CUSTOMER_TICKET',
            'ticket_rating',
            'cc_email',
            'customer_panel_employee_protect',
            'CUSTOMER_TICKETID',
            'TICKET_CHARACTER',
            'MAX_FILE_UPLOAD',
            'FILE_UPLOAD_MAX',
            'FILE_UPLOAD_TYPES',
            'RESTRICT_TO_CREATE_TICKET',
            'MAXIMUM_ALLOW_TICKETS',
            'MAXIMUM_ALLOW_HOURS',
            'trashed_ticket_autodelete',
            'NOTE_CREATE_MAILS',
            'RESTRICT_TO_REPLY_TICKET',
            'MAXIMUM_ALLOW_REPLIES',
            'REPLY_ALLOW_IN_HOURS',
            'employeeprotectname',
            'trashed_ticket_delete_time',
            'ticketrating',
            'contact_form_mail',
            'cust_or_tick_violation',
            'custreplyeditwithintime',
            'CUSTOMER_RESTRICT_EDIT_REPLY',
            'USER_MAX_FILE_UPLOAD',
            'USER_FILE_UPLOAD_MAX_SIZE',
            'USER_FILE_UPLOAD_TYPES',
            'LengthTextFieldStatus',
            'minLengthTextField',
            'maxLengthTextField'
        ];
        $userHeaderSettingValues = groupSetting($attributes);
        $data['setting'] = $userHeaderSettingValues;
        return $data;
    }

    /**
     * Ticket Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    public function ticketsettingstore(Request $request)
    {
        $request->validate([
            'ticketid' => 'required|string|between:1,6',
            'ticketcharacter' => 'required',
        ]);
        if ($request->trashed_ticket_delete_time) {
            $request->validate([
                'trashed_ticket_delete_time' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->custreplyeditwithintime) {
            $request->validate([
                'custreplyeditwithintime' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->MAXIMUM_ALLOW_TICKETS) {
            $request->validate([
                'MAXIMUM_ALLOW_TICKETS' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->MAXIMUM_ALLOW_REPLIES) {
            $request->validate([
                'MAXIMUM_ALLOW_REPLIES' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->REPLY_ALLOW_IN_HOURS) {
            $request->validate([
                'REPLY_ALLOW_IN_HOURS' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->MAXIMUM_ALLOW_HOURS) {
            $request->validate([
                'MAXIMUM_ALLOW_HOURS' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->userreopentime) {
            $request->validate([
                'userreopentime' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->autoclosetickettime) {
            $request->validate([
                'autoclosetickettime' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->autooverduetickettime) {
            $request->validate([
                'autooverduetickettime' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->autoresponsetickettime) {
            $request->validate([
                'autoresponsetickettime' => 'required|numeric|gt:0'
            ]);
        }
        if ($request->autonotificationdeletedays) {
            $request->validate([
                'autonotificationdeletedays' => 'required|numeric|gt:0'
            ]);
        }

        if ($request->ticketcharacter) {
            $request->validate([
                'ticketcharacter' => 'required|integer|between:10,255'
            ]);
        }
        if ($request->employeeprotectname) {
            $request->validate([
                'employeeprotectname' => 'required|max:255'
            ]);
        }
        if ($request->RESTRICT_TO_CREATE_TICKET) {
            $request->validate([
                'MAXIMUM_ALLOW_TICKETS' => 'required|numeric|gt:0',
                'MAXIMUM_ALLOW_HOURS' => 'required|numeric|gt:0',
            ]);
        }
        if ($request->RESTRICT_TO_REPLY_TICKET) {
            $request->validate([
                'MAXIMUM_ALLOW_REPLIES' => 'required|numeric|gt:0',
                'REPLY_ALLOW_IN_HOURS' => 'required|numeric|gt:0',
            ]);
        }
        if ($request->CUSTOMER_RESTRICT_EDIT_REPLY) {
            $request->validate([
                'custreplyeditwithintime' => 'required|numeric|gt:0',
            ]);
        }
        if ($request->trashed_ticket_autodelete) {
            $request->validate([
                'trashed_ticket_delete_time' => 'required|numeric|gt:0',
            ]);
        }
        if ($request->DASHBOARD_TABLE_DATA_AUTO_REFRESH) {
            $request->validate([
                'TABLE_DATA_AUTO_REFRESH_TIME' => 'required|numeric|gt:0',
            ]);
        }
        $data['RESTRICT_TO_CREATE_TICKET']  =  $request->RESTRICT_TO_CREATE_TICKET ? 'on' : 'off';
        $data['MAXIMUM_ALLOW_TICKETS']  =  $request->MAXIMUM_ALLOW_TICKETS;
        $data['MAXIMUM_ALLOW_HOURS']  =  $request->MAXIMUM_ALLOW_HOURS;
        $data['RESTRICT_TO_REPLY_TICKET']  =  $request->RESTRICT_TO_REPLY_TICKET ? 'on' : 'off';
        $data['MAXIMUM_ALLOW_REPLIES']  =  $request->MAXIMUM_ALLOW_REPLIES;
        $data['REPLY_ALLOW_IN_HOURS']  =  $request->REPLY_ALLOW_IN_HOURS;
        $data['USER_REOPEN_ISSUE']  =  $request->USER_REOPEN_ISSUE ? 'yes' : 'no';
        $data['USER_REOPEN_TIME']  =  $request->userreopentime;
        $data['cust_or_tick_violation']  =  $request->cust_or_tick_violation ? 'yes' : 'no';
        $data['AUTO_CLOSE_TICKET']  =  $request->AUTO_CLOSE_TICKET ? 'yes' : 'no';
        $data['AUTO_CLOSE_TICKET_TIME']  =  $request->autoclosetickettime;
        $data['AUTO_OVERDUE_CUSTOMER']  =  $request->AUTO_OVERDUE_CUSTOMER ? 'yes' : 'no';
        $data['AUTO_OVERDUE_TICKET']  =  $request->AUTO_OVERDUE_TICKET ? 'yes' : 'no';
        $data['AUTO_OVERDUE_TICKET_TIME']  =  $request->autooverduetickettime;
        $data['trashed_ticket_autodelete']  =  $request->trashed_ticket_autodelete ? 'on' : 'off';
        $data['trashed_ticket_delete_time']  =  $request->trashed_ticket_delete_time;
        $data['AUTO_RESPONSETIME_TICKET']  =  $request->AUTO_RESPONSETIME_TICKET ? 'yes' : 'no';
        $data['AUTO_RESPONSETIME_TICKET_TIME']  =  $request->autoresponsetickettime;
        $data['AUTO_NOTIFICATION_DELETE_ENABLE']  =  $request->AUTO_NOTIFICATION_DELETE_ENABLE ? 'on' : 'off';
        $data['AUTO_NOTIFICATION_DELETE_DAYS']  =  $request->autonotificationdeletedays;
        $data['CUSTOMER_TICKETID']  =  $request->ticketid;
        $data['DASHBOARD_TABLE_DATA_AUTO_REFRESH']  =  $request->has('DASHBOARD_TABLE_DATA_AUTO_REFRESH') ? 'yes' : 'no';
        $data['TABLE_DATA_AUTO_REFRESH_TIME']  =  $request->input('TABLE_DATA_AUTO_REFRESH_TIME');
        $data['GUEST_TICKET']  =  $request->GUEST_TICKET ? 'yes' : 'no';
        $data['NOTE_CREATE_MAILS']  =  $request->NOTE_CREATE_MAILS ? 'on' : 'off';
        $data['PRIORITY_ENABLE']  =  $request->PRIORITY_ENABLE ? 'yes' : 'no';
        $data['USER_FILE_UPLOAD_ENABLE']  =  $request->USER_FILE_UPLOAD_ENABLE ? 'yes' : 'no';
        $data['GUEST_FILE_UPLOAD_ENABLE']  =  $request->GUEST_FILE_UPLOAD_ENABLE ? 'yes' : 'no';
        $data['GUEST_TICKET_OTP']  =  $request->GUEST_TICKET_OTP ? 'yes' : 'no';
        $data['CUSTOMER_TICKET']  =  $request->CUSTOMER_TICKET ? 'yes' : 'no';
        $data['TICKET_CHARACTER']  =  $request->ticketcharacter;
        $data['customer_panel_employee_protect']  =  $request->customer_panel_employee_protect ? 'on' : 'off';
        $data['employeeprotectname']  =  $request->employeeprotectname;
        $data['CUSTOMER_RESTRICT_EDIT_REPLY']  =  $request->CUSTOMER_RESTRICT_EDIT_REPLY ? 'yes' : 'no';
        $data['custreplyeditwithintime']  =  $request->input('custreplyeditwithintime');
        $data['admin_reply_mail']  =  $request->admin_reply_mail ? 'yes' : 'no';
        $data['ticketrating']  =  $request->ticket_rating ? 'on' : 'off';
        $data['cc_email']  =  $request->cc_email ? 'on' : 'off';
        $data['LengthTextFieldStatus']  =  $request->LengthTextFieldStatus ? 'on' : 'off';
        $data['maxLengthTextField']  =  $request->maxLengthTextField;
        $data['minLengthTextField']  =  $request->minLengthTextField;

        $this->updateSettings($data);


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

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


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

    public function emailStore(Request $request)
    {
        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(['imapconnectionError' => 'notconnected', 'error' => 'Your smtp credentials are invalid, please verify your entered details.']);
            }
        }

        $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 = 'Updated Email Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 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');
                });

                return response()->json(['success' => 'A test email was sent successfully.']);
            } catch (\Exception $e) {
                return response()->json(['error' => 'The test email couldn’t be sent.']);
            }
        } else {
            return  response()->json(['error' => 'Please enter the email to send test mail.']);
        }
    }


    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(['success' => 'Connected']);
        } catch (\Swift_TransportException $e) {
            return response()->json(['imapconnectionError' => 'notconnected', 'error' => 'Your smtp credentials are invalid, please setup correctly to add imap settings.']);
        }
    }
    public function imapstore(Request $request)
    {
        $this->authorize('Email Setting Access');


        $imap_id = $request->imap_id;



        if ($imap_id) {
            $request->validate([
                'imap_host' => 'required',
                'imap_port' => 'required',
                'imap_protocol' => 'required',
                'imap_encryption' => 'required',
                'imap_username' => 'required',
                'imap_password' => 'required',

            ]);
        } else {

            $request->validate([
                'imap_host' => 'required',
                'imap_port' => 'required',
                'imap_protocol' => 'required',
                'imap_encryption' => 'required',
                'imap_username' => 'required|unique:imap_settings',
                'imap_password' => 'required',

            ]);

            if ($request->category) {
                $imaps = Imap_setting::where('category_id', $request->category)->first();
                if ($imaps)
                    return response()->json(['code' => 500, 'category' => 'notunique', 'error' => 'The imap category has already been taken.'], 500);
            }
        }


        $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 response()->json(['imapconnectionError' => 'notconnected', 'error' => 'Your imap credentials are invalid, please verify your entered details.']);
        }
        $category = null;
        if ($request->category) {
            $imaps = Imap_setting::where('category_id', $request->category)->where('id', '!=', $imap_id)->first();
            if ($imaps) {
                return response()->json([
                    'code' => 500,
                    'category' => 'notunique',
                    'error' => 'The imap category has already been taken.'
                ], 500);
            }
            $category = Category::where('status', '1')->find($request->category);
            if ($category) {
                $ipdtaa['category_name'] = $category->name;
            }
        }


        $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,
            'category_id' => $request->category,
            'status' => $request->status ?? 0,

        ];



        $ipdtaa = Imap_setting::updateOrCreate(['id' => $imap_id], $imapdata);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated IMAP List.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        if ($request->category) {
            $category = Category::where('status', '1')->find($request->category);
            if ($category) {
                $ipdtaa['category_name'] = $category->name;
            }
        }


        return response()->json(['success' =>  'Updated successfully'], 200);
    }
    public function statuschange(Request $request, $id)
    {
        $this->authorize('Email Setting Access');

        $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 status.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['code' => 200, 'success' => 'Status Updated successfully'], 200);
    }
    public function delete($id)
    {
        $this->authorize('Email Setting Access');

        $data = Imap_setting::find($id);
        $data->delete();
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted IMAP List.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['code' => 200, 'success' => 'Deleted successfully'], 200);
    }
    public function massdelete(Request $request)
    {
        $this->authorize('Email Setting Access');

        $holiday_array = $request->input('id');


        $holidays = Imap_setting::whereIn('id', $holiday_array)->get();

        foreach ($holidays as $holiday) {
            $holiday->delete();
        }
        return response()->json(['success' => 'The imap settings was deleted successfully.']);
    }

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

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

        $emailtemplates = EmailTemplate::query();

        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $emailtemplates->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('email_templates');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }
        $items = $emailtemplates->paginate($perPage);
        $data['queryList'] = $items;

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

        $data['templateSettings'] = [
            'templateFooterColor' => setting('templateFooterColor'),
            'templateHeaderColor' => setting('templateHeaderColor'),
        ];

        return $data;
    }

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

        $template = EmailTemplate::find($id);
        $data['template'] = $template;
        return $data;
        return $data;
    }
    public function templateSettings(Request $request)
    {
        $request->validate([
            'templateHeaderColor' => 'required',
            'templateFooterColor' => 'required',
        ]);
        $data['templateHeaderColor'] = $request->templateHeaderColor;
        $data['templateFooterColor'] = $request->templateFooterColor;

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

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

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

        $request->validate([
            'subject' => 'required|max:255',
            'body' => 'required'
        ]);

        $templateData = $request->only(['subject', 'body']);

        // Check and trim <p><br></p> or <div><br></div> from the body
        if (!empty($templateData['body'])) {
            $templateData['body'] = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $templateData['body']);
        }

        $template = EmailTemplate::find($id)->update($templateData);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Email Templates.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'Updated successfully']);
    }
    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 = 'Enabled Email to Ticket';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'Updated successfully']);
    }


    public function registerpopup(Request $request)
    {
        $socialAuth = SocialAuthSetting::first();
        if ($request->defaultsocialloginon == 'on') {
            if ($socialAuth->twitter_status == 'enable' || $socialAuth->facebook_status == 'enable' || $socialAuth->google_status == 'enable' || $socialAuth->envato_status == 'enable') {
                $data['REGISTER_DISABLE'] = 'off';
                $data['REGISTER_POPUP'] = 'no';
            } else {
                return response()->json(['error' => 'Social logins are not enabled please enable it first']);
            }
        }
        if ($request->custmobileupdate == 'on' && setting('twilioenable') != 'on') {
            return response()->json(['code' => 500, 'error' => lang('If you want enable switch for cusotmer mobile number update, first you need to setup twilio settings.', 'alerts')], 200);
        }

        if ($request->status == 'yes' && $request->defaultloginon == 'on') {
            return response()->json(['code' => 500, 'error' => lang('If default login is already enabled, at this moment you are not allowed to enable this switch.', 'alerts')], 200);
        }

        if ($request->defaultloginon == 'on' && $request->status == 'yes') {
            return response()->json(['code' => 500, 'error' => lang('If Register or login popup is already enabled, at this moment you are not allowed to enable this switch.', 'alerts')], 200);
        }
        $data['REGISTER_POPUP'] = $request->status == true ? 'yes' : 'no';
        $data['REGISTER_DISABLE'] = $request->registerdisable == true ? 'off' : 'on';
        $data['GOOGLEFONT_DISABLE'] = $request->googledisable == true ? 'on' : 'off';
        $data['FORCE_SSL'] = $request->forcessl == true ? 'on' : 'off';
        $data['DARK_MODE'] = $request->darkmode == true ? '1' : '0';

        $data['cust_mobile_update'] = $request->cust_mobile_update == true ? 'on' : 'off';

        if ($request->darkmode == true) {
            User::query()->update(['darkmode' => '1']);
            Customer::query()->each(function ($user) {
                $user->custsetting()->update(['darkmode' => '1']);
            });
        } else {
            User::query()->update(['darkmode' => '0']);
            Customer::query()->each(function ($user) {
                $user->custsetting()->update(['darkmode' => '0']);
            });
        }


        $data['SPRUKOADMIN_P'] = $request->sprukoadminp ? 'on' : 'off';
        $data['SPRUKOADMIN_C'] = $request->sprukocustp ? 'on' : 'off';
        $data['ENVATO_ON'] = $request->envatoon ? 'on' : 'off';
        $data['purchasecode_on'] = $request->purchasecodeon ? 'on' : 'off';
        $data['defaultlogin_on'] = $request->defaultloginon ? 'on' : 'off';
        $data['article_count'] = $request->article_count ? 'on' : 'off';
        $data['sidemenu_icon_style'] = $request->sidemenustyle ? 'on' : 'off';
        $data['login_disable'] = $request->logindisable ? 'on' : 'off';
        $data['cust_email_update'] = $request->cust_email_update ? 'on' : 'off';
        $data['cust_profile_delete_enable'] = $request->custdeleteprofile ? 'on' : 'off';
        // $data['MAINTENANCE_MODE'] = $request->maintanancemode ? 'on' : 'off';
        $data['only_social_logins'] = $request->defaultsocialloginon ? 'on' : 'off';
        $data['emp_google_translate'] = $request->empGoogleTranslate;
        $data['emp_google_translate'] = $request->emp_google_translate ? 'on' : 'off';
        $data['cust_google_translate'] = $request->cust_google_translate ? 'on' : 'off';
        $data['cust_email_verification'] = $request->cust_email_verification ? '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 = 'Updated Global Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }
    public function emailToTicket(Request $request)
    {
        $data['IMAP_STATUS'] = $request->IMAP_STATUS == true ? 'on' : 'off';
        $this->updateSettings($data);
        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }
    public function emailToTicketDeleteCloneTicket(Request $request)
    {
        $data['IMAP_STATUS'] = $request->IMAP_STATUS == true ? 'on' : 'off';
        $data['email_delete'] = $request->email_delete == true ? 1 : 0;
        $data['email_ticket_limit'] = $request->email_ticket_limit;
        $this->updateSettings($data);
        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }


    public function contactemail(Request $request)
    {

        if ($request->CONTACT_ENABLE == true) {
            $request->validate([
                'contact_form_mail' => 'required|email',
            ]);
        }

        $data['CONTACT_ENABLE']  =  $request->CONTACT_ENABLE == true ? 'yes' : 'no';
        $data['contact_form_mail'] = $request->contact_form_mail;
        $this->updateSettings($data);

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

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

    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 response()->json(['error' => 'You are enter wrong file formats please enter correct format.'], 200);
        //     }
        // }
        // foreach ($fileuploadtypes as $fileuploadtype) {
        //     if (!in_array($fileuploadtype, $allowedFormats)) {
        //         return response()->json(['error' => 'You are enter wrong file formats please enter correct format.'], 200);
        //     }
        // }
        $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 = 'Updated File Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'Updated Successfully']);
    }


    public function knowledge(Request $request)
    {
        $data['KNOWLEDGE_ENABLE']  =  $request->KNOWLEDGE_ENABLE == true ? 'yes' : 'no';
        $data['FAQ_ENABLE']  =  $request->FAQ_ENABLE == true ? 'yes' : 'no';

        $this->updateSettings($data);

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

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


    public function profileuser(Request $request)
    {

        $data['PROFILE_USER_ENABLE']  =  $request->PROFILE_USER_ENABLE == true ? 'yes' : 'no';

        $this->updateSettings($data);

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

        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }
    public function profileagent(Request $request)
    {

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

        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated PROFILE_AGENT_ENABLE Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }

    public function captchacontact(Request $request)
    {

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

        $this->updateSettings($data);

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

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

    public function captcharegister(Request $request)
    {

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

        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Captcha Setting In Forms.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();


        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }
    public function captchalogin(Request $request)
    {

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

        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Captcha Setting In Forms.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();


        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }
    public function captchaadminlogin(Request $request)
    {

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

        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Captcha Setting In Forms.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();


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

    public function captchaguest(Request $request)
    {

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

        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Captcha Setting In Forms.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();


        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 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 = 'Updated Color Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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

    public function getcolorsetting()
    {
        $data['setting'] = response()->json([
            'theme_color' => setting('theme_color'),
            'theme_color_dark' => setting('theme_color_dark'),
        ]);
        return $data;
    }


    public function googleanalytics()
    {
        $this->authorize('Google Analytics Access');
        $data['GOOGLE_ANALYTICS_ENABLE'] = setting('GOOGLE_ANALYTICS_ENABLE');
        $data['GOOGLE_ANALYTICS'] = setting('GOOGLE_ANALYTICS');


        return $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 = 'Updated Google Analytics.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'Updated Successfully']);
    }

    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 = 'Updated Global language Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response(['success' => 'Updated successfully']);
    }
    public function envatosetting()
    {
        if (setting('ENVATO_ON') != 'on') {
            abort(403);
        }
        $data['setting'] = response()->json(['purchasecode_on' => setting('purchasecode_on'), 'ENVATO_EXPIRED_BLOCK' => setting('ENVATO_EXPIRED_BLOCK'),  'SUPPORT_POLICY_URL' => setting('SUPPORT_POLICY_URL')]);

        return $data;
    }
    public function termsurl()
    {
        $data['terms_url'] = setting('terms_url');
        return $data;
    }
    public function expiredsupport(Request $request)
    {

        if ($request->ENVATO_EXPIRED_BLOCK == true) {
            $request->validate([
                'SUPPORT_POLICY_URL' => 'required|url',
            ]);
        }

        $data['purchasecode_on']  =   $request->purchasecode_on == true ? 'on' : 'off';
        $data['ENVATO_EXPIRED_BLOCK']  = $request->ENVATO_EXPIRED_BLOCK == true ? '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 = 'Updated Envato settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response(['success' =>  'Updated successfully']);
    }

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

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

        $this->updateSettings($data);

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

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

    public function datetimeformatstore(Request $request)
    {

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

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

        return response()->json(['success' => 'The Global Date & Time Format was successfully restore.']);
    }

    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 = 'Updated Global Date & Time Format.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'The First Day of the Week was successfully restore.']);
    }


    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 = 'Updated TimeZone';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'The Global Timezones was successfully restore.']);
    }

    public function businesshourtitle(Request $request)
    {
        $request->validate([
            'businesshourstitle' => 'required|max:255',
        ]);
        if ($request->businesshourssubtitle) {
            $request->validate([
                'businesshourssubtitle' => 'max:255',
            ]);
        }
        $data['businesshourstitle'] = $request->businesshourstitle;
        $data['businesshourssubtitle'] = $request->businesshourssubtitle;
        $data['businesshoursswitch'] = $request->businesshoursswitch ? 'on' : 'off';

        if ($request->file('supporticon')) {
            $supportimage = $request->file('supporticon');
            $request->validate([
                'supporticon' => 'required|mimes:jpg,jpeg,png,svg|max:512',
            ]);
            //delete old file
            $supporticon = setting('supporticonimage');
            $imagepath = public_path() . "" . '/uploads/support/' . $supporticon;
            if (\File::exists($imagepath)) {
                \File::delete($imagepath);
            }
            //insert new file
            $destinationPath = public_path() . "" . '/uploads/support/'; // upload path
            $profileImage = date('YmdHis') . "." . $supportimage->getClientOriginalExtension();
            $supportimage->move($destinationPath, $profileImage);
            $data['supporticonimage'] = "$profileImage";
        }
        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Business Hours Setting.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();


        return response()->json(['success' => 'Updated successfully']);
    }
    public function businessofflinemsg(Request $request)
    {
        $request->validate([
            'offlineTextTitle' => $request->businesshourofflinemsg ? 'required' : '',
            'offlineTextMessage' => $request->businesshourofflinemsg ? 'required|string|max:255' : '',
        ]);
        $data['businesshourofflinemsg'] = $request->businesshourofflinemsg ? 'on' : 'off';
        $data['offlineTextTitle'] = $request->offlineTextTitle;
        $data['offlineTextMessage'] = $request->offlineTextMessage;

        $this->updateSettings($data);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Business Hours offline message Setting.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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

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

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

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

    public function disablestatement()
    {
        $data['setting'] = response()->json([
            'login_disable_statement' => setting('login_disable_statement'),
            'login_disable' => setting('login_disable'),
        ]);
        return $data;
    }

    public function customerprofiledelete(Request $request)
    {
        $request->validate([
            'customer_inactive_notify_month' => 'required|numeric|gt:0',
            'customer_inactive_days' => 'required|numeric|gt:0',
            'guest_inactive_notify_month' => 'required|numeric|gt:0',
            'guest_inactive_days' => 'required|numeric|gt:0',
        ]);

        $data['customer_inactive_notify']  =  $request->has('customer_inactive_notify') && $request->customer_inactive_notify !== false ? 'on' : 'off';
        $data['customer_inactive_notify_date']  =  $request->input('customer_inactive_notify_month');
        $data['customer_inactive_week_date']  =  $request->input('customer_inactive_days');
        $data['guest_inactive_notify']  =  $request->has('guest_inactive_notify') && $request->guest_inactive_notify !== false ? 'on' : 'off';
        $data['guest_inactive_notify_date']  =  $request->input('guest_inactive_notify_month');
        $data['guest_inactive_week_date']  =  $request->input('guest_inactive_days');

        $this->updateSettings($data);

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

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


    public function customerautologout(Request $request)
    {
        // $request->validate([
        //     'customer_inactive_auto_logout_time' => 'required||numeric|gt:0',
        //     'admin_users_inactive_auto_logout_time' => 'required||numeric|gt:0',
        // ]);
        if ($request->has('customer_inactive_auto_logout')) {
            $request->validate([
                'customer_inactive_auto_logout_time' => 'required|numeric|gt:0',
            ]);
        }

        if ($request->has('admin_users_inactive_auto_logout')) {
            $request->validate([
                'admin_users_inactive_auto_logout_time' => 'required|numeric|gt:0',
            ]);
        }
        $data['customer_inactive_auto_logout']  =  $request->input('customer_inactive_auto_logout') == true ?  'on' : 'off';
        $data['customer_inactive_auto_logout_time']  =  $request->input('customer_inactive_auto_logout_time');
        $data['admin_users_inactive_auto_logout']  =  $request->input('admin_users_inactive_auto_logout') == true ?  'on' : 'off';
        $data['admin_users_inactive_auto_logout_time']  =  $request->input('admin_users_inactive_auto_logout_time');

        $this->updateSettings($data);

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

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

    public function twofactauthsetting(Request $request)
    {
        $data['Employe_google_two_fact']  =  $request->Employe_google_two_fact ? 'on' : 'off';
        if ($request->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));

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

                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->Employe_email_two_fact ? 'on' : 'off';
        $data['Customer_google_two_fact']  =  $request->Customer_google_two_fact ? 'on' : 'off';
        if ($request->Customer_google_two_fact == false) {
            $customers = Customer::with('custsetting')->where('google2fa_secret', '!=', 'null')->get();
            foreach ($customers as $user) {
                $user['google2fa_secret'] = null;
                $user->save();
                $user->custsetting->twofactorauth = null;
                $user->custsetting->save();

                $user->notify(new InformationSendToUsers($user));

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

                dispatch((new MailSend($user->email, 'send_mail_to_users_when_two_factor_authentication_disabled', $ticketData)));
            }
        }
        $data['Customer_email_two_fact']  =  $request->Customer_email_two_fact ? '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 = 'Updated Two Factor Authentication Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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


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

        $this->updateSettings($data);
        return response()->json(['success' =>  'Deleted successfully'], 200);
    }



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


    public function botresponsettingcreate(Request $request)
    {
        $data['settings'] = [
            "botresponseenable" => setting('botresponseenable'),
            "bot_image" => setting('bot_image'),
            "bot_name" => setting('bot_name'),
            "botsresponse_time" => setting('botsresponse_time'),
            "time_detection" => setting('time_detection'),
            "response_description" => setting('response_description'),
            "response_description_exclude_business_hours" => setting('response_description_exclude_business_hours'),
        ];
        if (setting('bot_image')) {
            $data['bot_imagePreview'] =  asset('public/uploads/profile/botprofile/' . setting('bot_image'));
        }

        return $data;
    }

    public function botsettingstore(Request $request)
    {
        $businesshours = Businesshours::get();
        if ($businesshours->isempty()) {
            return response()->json(['error' => 'You need to setup business hours first to enable bot response']);
        }
        if ($request->has('botresponseenable')) {
            $request->validate([
                'bot_name' => 'required',
                'botsresponse_time' => 'required|numeric|gt:0',
                'response_description' => 'required',
                'response_description_exclude_business_hours' => 'required',
            ]);
        }
        $data['botresponseenable']  =  $request->botresponseenable == "true" ? '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 response()->json(['error' => 'Please check the format and size of the file.']);
            } 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 = 'Updated Bot Settings.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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

    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 = 'Deleted Bot Image';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

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

    public function twiliosetting()
    {
        $this->authorize('Twilio Setting Access');

        $data['settings'] = [
            "twilioenable" => setting('twilioenable'),
            "twilio_auth_id" => setting('twilio_auth_id'),
            "twilio_auth_token" => setting('twilio_auth_token'),
            "twilio_auth_phone_number" => setting('twilio_auth_phone_number')
        ];

        $emailtemplates = MessageTemplates::query();

        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $emailtemplates->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('email_templates');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }
        $items = $emailtemplates->paginate($perPage);
        $data['queryList'] = $items;
        $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 twiliosettingstore(Request $request)
    {
        $this->authorize('Twilio Setting Access');

        if ($request->has('twilioenable')) {
            $this->validate($request, [
                'twilio_auth_id' => 'required',
                'twilio_auth_token' => 'required',
                'twilio_auth_phone_number' => 'required',
            ]);

            try {
                $client = new \Twilio\Rest\Client($request->twilio_auth_id, $request->twilio_auth_token);
                $client->api->v2010->accounts->read();
            } catch (\Twilio\Exceptions\ConfigurationException $e) {
                return response()->json(['error' => 'Twilio credentials are invalid']);
            } catch (\Twilio\Exceptions\TwilioException $e) {
                return response()->json(['error' => 'Twilio credentials are invalid']);
            } catch (\Exception $e) {
                return response()->json(['error' => 'Twilio credentials are invalid']);
            }
        }

        $data['twilioenable'] = $request->has('twilioenable') ? 'on' : 'off';;
        $data['twilio_auth_id'] = $request->twilio_auth_id;
        $data['twilio_auth_token'] = $request->twilio_auth_token;
        $data['twilio_auth_phone_number'] = $request->twilio_auth_phone_number;

        $this->updateSettings($data);

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

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

    public function smstemplateedit($id)
    {
        $this->authorize('Twilio 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;

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

        return $data;
    }

    public function smstemplateUpdate(Request $request, $id)
    {
        $this->authorize('Twilio Setting Access');

        $request->validate([
            'body' => 'required'
        ]);
        if (strip_tags($request->body) == "") {
            return response()->json(['bodyNull' => 'Message Body field is required.']);
        }

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

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

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


    public function payments()
    {
        $this->authorize('Payment Gateways Access');

        $data['settings'] = [
            'enableStripe' => setting('enableStripe'),
            'stripeKey' => setting('stripeKey'),
            'stripeSecret' => setting('stripeSecret'),
            'stripeDefault' => setting('stripeDefault'),
            'enablePaypal' => setting('enablePaypal'),
            'paypalKey' => setting('paypalKey'),
            'paypalSecret' => setting('paypalSecret'),
            'paypalDefault' => setting('paypalDefault'),
            'enableRefund' => setting('enableRefund'),
            'refundDays' => setting('refundDays'),
            'autoInvoiceCancelEnable' => setting('autoInvoiceCancelEnable'),
            'invoiceCancelDays' => setting('invoiceCancelDays'),
            'autoinvoicedelete' => setting('autoinvoicedelete'),
            'autodeleteinvoiceDays' => setting('autodeleteinvoiceDays'),
        ];

        return $data;
    }

    public function stripePaymentsStore(Request $request)
    {
        $this->authorize('Payment Gateways Access');
        if ($request->enableStripe) {
            $this->validate($request, [
                'stripeKey' => 'required',
                'stripeSecret' => 'required',
            ]);
        }

        try {
            Stripe::setApiKey($request->stripeSecret);
            $account = \Stripe\Account::retrieve();
        } catch (Exception $e) {
            return response()->json(['error' => $e->getMessage()]);
        }

        $data['enableStripe'] = $request->enableStripe ? 'on' : 'off';
        $data['stripeKey'] = $request->stripeKey;
        $data['stripeSecret'] = $request->stripeSecret;
        $data['stripeDefault'] = $request->stripeDefault ? '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 = 'Updated Stripe credentials.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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

    public function paypalPaymentsStore(Request $request)
    {
        $this->authorize('Payment Gateways Access');
        if ($request->enablePaypal) {
            $this->validate($request, [
                'paypalKey' => 'required',
                'paypalSecret' => 'required',
            ]);
        }

        $data['enablePaypal'] = $request->enablePaypal ? 'on' : 'off';
        $data['paypalKey'] = $request->paypalKey;
        $data['paypalSecret'] = $request->paypalSecret;
        $data['paypalDefault'] = $request->paypalDefault ? '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 = 'Updated Paypal credentials.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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

    public function updateDefaultSettings(Request $request)
    {

        $validatedData = $request->validate([
            'setting' => 'required|string',
            'value' => 'required|string',
        ]);

        if ($request->setting == 'stripeDefault') {
            $data['stripeDefault'] = $request->value;
            $data['paypalDefault'] = 'off';
        } elseif ($request->setting == 'paypalDefault') {
            $data['stripeDefault'] = 'off';
            $data['paypalDefault'] = $request->value;
        }
        $this->updateSettings($data);

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

        return response()->json(['success' => lang('Changed default payment gateway settings')]);
    }

    public function invoiceAddress(Request $request)
    {
        $request->validate([
            'companyName' => 'required',
            'addressLine1' => 'required',
            'cityName' => 'required',
            'stateName' => 'required',
            'zipPostalCode' => 'required',
            'countryName' => 'required',
            // 'taxName' => 'required',
            // 'taxId' => 'required',
        ]);
        $data['companyName'] = $request->input('companyName');
        $data['addressLine1'] = $request->input('addressLine1');
        $data['addressLine2'] = $request->input('addressLine2');
        $data['cityName'] = $request->input('cityName');
        $data['stateName'] = $request->input('stateName');
        $data['zipPostalCode'] = $request->input('zipPostalCode');
        $data['countryName'] = $request->input('countryName');
        $data['taxName'] = strtoupper($request->input('taxName'));
        $data['taxId'] = $request->input('taxId');
        $data['taxPercent'] = $request->input('taxPercent');

        if ($request->has('customInvoiceId') && $request->input('customInvoiceId') != null) {
            $customId = (int)$request->input('customInvoiceId');

            $existingTransaction = AllTransactions::latest()->value('invoiceId');

            if ($existingTransaction >= $customId) {
                return response()->json(['error' => 'Custom ID must be greater than the current custom ID ' . $existingTransaction]);
            }
            $data['customInvoiceId'] = $request->input('customInvoiceId');
        }

        $this->updateSettings($data);

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

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

    public function aisetup()
    {
        $this->authorize('AI Setup Access');


        $data['settings'] = [
            'enableGeminiApi' => setting('enableGeminiApi'),
            'geminiApiKey' => setting('geminiApiKey')
        ];


        return $data;
    }

    public function geminiApiStore(Request $request)
    {
        $this->authorize('AI Setup Access');
        if ($request->enableGemini) {
            $this->validate($request, [
                'geminiKey' => 'required',
            ]);

            $isValidApiKey = $this->validateGeminiApiKey($request->geminiKey);
            if (!$isValidApiKey) {
                return response()->json(['geminiKey' => 'Invalid Gemini API key. Please check your key and try again.']);
            }
        }

        $data['enableGeminiApi'] = $request->enableGemini ? 'on' : 'off';
        $data['geminiApiKey'] = $request->geminiKey;

        $this->updateSettings($data);

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

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

    private function validateGeminiApiKey($apiKey)
    {
        $endpoint = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key={$apiKey}";
        $headers = [
            'Content-Type' => 'application/json',
        ];
        $body = [
            'contents' => [
                [
                    'parts' => [
                        [
                            'text' => "Test Prompt",
                        ]
                    ]
                ]
            ]
        ];
        try {
            $response = Http::withHeaders($headers)->post($endpoint, $body);

            if ($response->successful()) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }
}
