<?php

namespace App\Generators;

use App\Models\Group;
use App\Models\SMTPMails;
use Illuminate\Support\Facades\Route;

class TourGuideScriptGenerator
{

    private $steps;

    public function __construct()
    {
        $this->steps = [
            ['id' => 1, 'label' => 'welcome', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 2, 'label' => 'rewatch', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 3, 'label' => 'security-alert', 'roles' => ['owner']],
            ['id' => 4, 'label' => 'set-security-question', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 5, 'label' => 'set-security-question-answer', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 6, 'label' => 'save-security-question', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 7, 'label' => 'change-password-prompt', 'roles' => ['admin', 'user']],
            ['id' => 8, 'label' => 'set-current-password', 'roles' => ['admin', 'user']],
            ['id' => 9, 'label' => 'set-new-password', 'roles' => ['admin', 'user']],
            ['id' => 10, 'label' => 'set-confirm-new-password', 'roles' => ['admin', 'user']],
            ['id' => 11, 'label' => 'save-new-password', 'roles' => ['admin', 'user']],
            ['id' => 12, 'label' => 'set-smtp-server-name', 'roles' => ['owner', 'admin']],
            ['id' => 13, 'label' => 'set-smtp-port', 'roles' => ['owner', 'admin']],
            ['id' => 14, 'label' => 'set-smtp-username', 'roles' => ['owner', 'admin']],
            ['id' => 15, 'label' => 'set-smtp-password', 'roles' => ['owner', 'admin']],
            ['id' => 16, 'label' => 'set-smtp-encryption', 'roles' => ['owner', 'admin']],
            ['id' => 17, 'label' => 'set-smtp-authentication', 'roles' => ['owner', 'admin']],
            ['id' => 18, 'label' => 'test-smtp', 'roles' => ['owner', 'admin']],
            ['id' => 19, 'label' => 'save-smtp', 'roles' => ['owner', 'admin']],
            ['id' => 20, 'label' => 'set-group-name', 'roles' => ['owner', 'admin']],
            ['id' => 21, 'label' => 'save-group', 'roles' => ['owner', 'admin']],
            ['id' => 22, 'label' => 'data-connection', 'roles' => ['owner', 'admin']],
            ['id' => 23, 'label' => 'chart-section', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 24, 'label' => 'reports-section', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 25, 'label' => 'kpis-section', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 26, 'label' => 'home-page', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 27, 'label' => 'dashboards', 'roles' => ['owner', 'admin', 'user']],
            ['id' => 28, 'label' => 'scheduled-reports-section', 'roles' => ['owner', 'admin', 'user']]
        ];
    }

    private function getStepId($label)
    {
        $filteredArray = array_filter($this->steps, function ($step) use ($label) {
            return $step['label'] === $label;
        });

        $ids = array_map(function ($step) {
            return $step['id'];
        }, $filteredArray);

        $id = !empty($ids) ? (int) reset($ids) : null;

        return $id;
    }

    private function onHighlighted()
    {
        $currentTourStep = $this->getCurrentTourStep();
        return <<<END
                onHighlighted: function (element, step, options) {
                    const urlParams = new URLSearchParams(window.location.search);
                    const stepParam = urlParams.get('step');
                    const stepIndex = options.config.steps.findIndex(step => step.id === stepParam);
                    console.log(stepParam,stepIndex);

                    if( stepParam !== null && stepIndex !== null){
                        driverObj.drive(stepIndex);
                    }
                }
        END;
    }

    private function onDestroyed()
    {
        $toProfileStep = session('security_errors') ? 3 : 2;

        $profile = route('profile.index');

        $general = route('general.index');

        $groups = route('quick-add', ['add' => 'groups']);

        return <<<END
                onDestroyed: function (element, step, options) {

                const currentStepIndex = options.config.steps.findIndex(s => s.element === step.element);

                    sendStartTourRequest();
                    sessionStorage.removeItem('currentTourStep');

                }

        END;

    }

// private function enableResume()

// {

//     session()->put('resume', true);

// }

// private function disableResume()

// {

//     session()->put('resume', false);
    // }

    private function buildTour()
    {

        return <<<END

                const driver = window.driver.js.driver;

                const driverObj = driver({
                    popoverClass: "driverjs-theme",
                    showButtons: [
                        'next',
                        'previous',
                    ],
                    {$this->adminTour()},

                    {$this->onHighlighted()},
                    {$this->onDestroyed()}

                });

                driverObj.drive();
        END;

    }

    private function adminTour()
    {

        if (Route::currentRouteName() == 'profile.index') {
            return <<<END
            steps:[
                {$this->profilePageSteps()}
            ]
        END;

        } elseif (Route::currentRouteName() == 'general.index') {
            return <<<END
            steps:[
                {$this->generalPageSteps()}
            ]
        END;

        } elseif (Route::currentRouteName() == 'users.index') {
            return <<<END
            steps:[
                {$this->usersPageSteps()}
            ]
        END;

        } else {
            return <<<END
            steps:[
                {$this->welcomePageSteps()}
            ]
        END;

        }

    }

    private function welcomePageSteps()
    {
        return <<<END
            {$this->welcomeStep()}
            {$this->reWatchStep()}
            {$this->securityErrorStep()}
            {$this->setGroupName()}
            {$this->saveGroup()}
            {$this->showDataConnection()}
            {$this->showChartsSection()}
            {$this->showReportsSection()}
            {$this->showKpisSection()}
            {$this->showHomePageSection()}
            {$this->showDashboardSection()}
            {$this->showScheduledReportsSection()}
        END;
    }

    private function welcomeStep()
    {
        $stepId = $this->getStepId('welcome');
        $logo   = getDefaultLogo();

        return <<<END
        {
            id: $stepId,
            element: 'container-fluid',
            popover: {
                title: 'Welcome to Smart Report Maker!',
                description: "<div class='text-center mb-3'><img src='$logo'></div> With Smart Report Maker, you can effortlessly create reports, charts, scheduled reports, KPIs and metrics, and dashboards. You can also customize your home page with widgets, all derived from connections to any MySQL databases you have. <br><br> This guided tour will help you quickly define the essential settings and get started with Smart Report Maker in no time.",
                nextBtnText: "Oki, start!",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: (element,step,options) => {
                const urlParams = new URLSearchParams(window.location.search);
                const stepParam = urlParams.get('step');
                console.log(stepParam);
                const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);
                console.log(stepParam,stepIndex);

                if( stepParam != null && stepIndex != -1){
                    setTimeout(()=> {
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    },10);
                }

                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;

    }

    private function getRewatchNextStep()
    {
        $profile = route('profile.index');

        $general = route('general.index');

        $groups = route('quick-add', ['add' => 'groups']);

        if (auth()->user()->isAdminOrOwner()) {

            if (isset(session('security_errors')['security_check_error'])) {

                return "driverObj.moveNext();";

            }

            if (!is_null(auth()->user()->Security_question_index) && is_null(auth()->user()->added_by)) {

                if (SMTPMails::defaultSmtpMail()->first()) {

                    if (Group::first()) {
                        return "driverObj.moveNext();";
                    }

                    return "window.location.href = '{$groups}'";

                }

                return "window.location.href = '{$general}'";
            }

            return "window.location.href = '{$profile}'";
        }

        return "window.location.href = '{$profile}'";

    }

    private function reWatchStep()
    {
        $stepId = $this->getStepId('rewatch');

        $nextStep = $this->getRewatchNextStep();

        return <<<END
        {
            id: $stepId,
            element: '#start-tour',
            popover: {
                title: 'Rewatch the Guided Tour Anytime',
                description: "If you would like to rewatch this guided tour at any time, simply click this icon.",
                nextBtnText: "Next",
                onNextClick: () => {
                    $nextStep
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function getSecurityNextStep()
    {
        $profile = route('profile.index');

        $general = route('general.index');

        $groups = route('quick-add', ['add' => 'groups']);

        if (auth()->user()->isOwner()) {

            if (isset(auth()->user()->Security_question_index)) {

                if (SMTPMails::defaultSmtpMail()->first()) {

                    if (Group::first()) {
                        return "driverObj.moveNext();";
                    }

                    return "window.location.href = '{$groups}'";

                }

                return "window.location.href = '{$general}'";
            }

            return "window.location.href = '{$profile}'";
        }

        return "window.location.href = '{$profile}'";

    }

    private function securityErrorStep()
    {

        if (!isset(session('security_errors')['security_check_error']) || !auth()->user()->isAdminOrOwner()) {
            return;
        }

        $profile = route('profile.index');

        $stepId = $this->getStepId('security-alert');

        $nextStep = $this->getSecurityNextStep();

        return <<<END
        {
            id: $stepId,
            element: '#security-error-alert',
            popover: {
                title: 'Urgent Security Alert: Protect Your Configuration Files',
                description: "This security alert is very serious. It indicates that the .htaccess file provided with Smart Report Maker may not be blocking direct access to sensitive configuration files as intended. To secure your server, please configure your web server (Apache, IIS, or Nginx) to prevent direct access to files starting with a dot (e.g., .htaccess, .env) and certain configuration file types (e.g., *.json, *.xml, *.config, *.yml, *.log).",
                nextBtnText: "Next",
                onNextClick: () => {
                    $nextStep
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;

    }

    private function profilePageSteps()
    {

        if (auth()->user()->isAdminOrOwner()) {
            return <<<END
            {$this->securityQuestionStep()}
            {$this->securityQuestionAnswerStep()}
            {$this->securityQuestionSaveStep()}
            {$this->showChangePasswordPromptStep()}
            {$this->setCurrentPasswordStep()}
            {$this->setNewPasswordStep()}
            {$this->setConfirmNewPasswordStep()}
            {$this->saveNewPasswordStep()}
            {$this->setGroupName()}
            {$this->saveGroup()}
            {$this->showDataConnection()}
            {$this->showChartsSection()}
            {$this->showReportsSection()}
            {$this->showKpisSection()}
            {$this->showHomePageSection()}
            {$this->showDashboardSection()}
            {$this->showScheduledReportsSection()}

        END;
        } else {
            return <<<END
            {$this->securityQuestionStep()}
            {$this->securityQuestionAnswerStep()}
            {$this->securityQuestionSaveStep()}
            {$this->showChangePasswordPromptStep()}
            {$this->setCurrentPasswordStep()}
            {$this->setNewPasswordStep()}
            {$this->setConfirmNewPasswordStep()}
            {$this->saveNewPasswordStep()}
            {$this->showChartsSection()}
            {$this->showReportsSection()}
            {$this->showKpisSection()}
            {$this->showHomePageSection()}
            {$this->showDashboardSection()}
        END;

        }

    }

    private function securityQuestionStep()
    {

        if (isset(auth()->user()->Security_question_index) && isset(auth()->user()->Security_answer)) {
            return;
        }

        $stepId = $this->getStepId('set-security-question');

        $home = route('home');

        return <<<END
        {
            id: $stepId,
            element: '#securityQuestion',
            popover: {
                title: "Set Up Your Security Question",
                description: "To enhance the security of your account, please select a security question.",
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                },
                onPrevClick: () => {
                    window.location.href = "{$home}?step=2"
                }
            },
            onHighlighted: (element,step,options) => {
                const urlParams = new URLSearchParams(window.location.search);
                const stepParam = urlParams.get('step');
                const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);
                console.log(stepParam,stepIndex);

                if( stepParam != null && stepIndex != -1){
                    setTimeout(()=> {
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    },10);
                }
                $('.driver-popover-prev-btn').removeClass("driver-popover-btn-disabled");
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);

            },
            {$this->popupPosition()}
        },
        END;
    }

    private function securityQuestionAnswerStep()
    {

        if (isset(auth()->user()->Security_question_index) && isset(auth()->user()->Security_answer)) {
            return;
        }

        $stepId = $this->getStepId('set-security-question-answer');

        return <<<END
        {
            id: $stepId,
            element: '#answer',
            popover: {
                title: "Provide an Answer to Your Security Question",
                description: "Please provide an answer to the security question you selected. This will help us verify your identity if you need to reset your password in the future.",
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function securityQuestionSaveNextStep()
    {

        $general = route('general.index');

        $groups = route('quick-add', ['add' => 'groups']);

        if (auth()->user()->isAdminOrOwner()) {

            if (!auth()->user()->added_by) {

                if (SMTPMails::defaultSmtpMail()->first()) {

                    if (Group::first()) {
                        return "driverObj.moveNext();";
                    }

                    return "window.location.href = '{$groups}'";

                }

                return "window.location.href = '{$general}'";
            }

            return "driverObj.moveNext();";

        }

        if (auth()->user()->added_by) {
            return "driverObj.moveNext();";
        }

        return "driverObj.drive(3);";

    }

    private function securityQuestionSaveStep()
    {

        if (isset(auth()->user()->Security_question_index) && isset(auth()->user()->Security_answer)) {
            return;
        }

        $stepId   = $this->getStepId('save-security-question');
        $nextStep = $this->securityQuestionSaveNextStep();
        return <<<END
        {
            id: $stepId,
            element: '#saveBtn-contact',
            popover: {
                title: "Save Security Question Details",
                description: 'Click "Save" to store your security question and answer. This information will be used to verify your identity if you need to reset your password in the future',
                nextBtnText: "Next",
                onNextClick: () => {
                    $nextStep
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}

        },
        END;
    }

    private function showChangePasswordPromptNextStep()
    {

        $general = route('general.index');

        $groups = route('quick-add', ['add' => 'groups']);

        if (auth()->user()->isAdmin()) {

            if (SMTPMails::defaultSmtpMail()->first()) {

                if (Group::first()) {

                    if (isset(auth()->user()->Security_question_index)) {
                        return "driverObj.drive(5);";
                    }

                    return "driverObj.drive(8);";
                }

                return "window.location.href = '{$groups}'";

            }

            return "window.location.href = '{$general}'";

        }

        if (!auth()->user()->isAdminOrOwner() && !is_null(auth()->user()->Security_question_index)) {
            return "driverObj.drive(5);";
        }

        return "driverObj.drive(8);";

    }

    private function showChangePasswordPromptStep()
    {

// if ((isset(auth()->user()->Security_question_index) && isset(auth()->user()->Security_answer))

//     || auth()->user()->isOwner()

// ) {

//     return;

// }

        if (!isset(auth()->user()->added_by) || auth()->user()->isOwner()) {
            return;
        }

        $stepId = $this->getStepId('change-password-prompt');

        $general = route('general.index');

        $nextStep = $this->showChangePasswordPromptNextStep();
        return <<<END
        {
            id: $stepId,
            element: 'container-fluid',
            popover: {
                title: "Change Your Password",
                description: 'For security reasons, you are required to change your password upon your first login. Have you done this?',
                nextBtnText: "Yes",
                prevBtnText: "No",
                onNextClick: () => {
                    $nextStep
                },
                onPrevClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: (elements, step, options) => {
                setTimeout(()=> {
                    const urlParams = new URLSearchParams(window.location.search);
                    const stepParam = urlParams.get('step');
                    const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);

                    if( stepParam != null && stepIndex != -1){
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    }
                },100);

                $('.driver-popover-prev-btn').removeClass("driver-popover-btn-disabled");
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },

            {$this->popupPosition()}
        },
        END;
    }

    private function setCurrentPasswordStep()
    {

// if ((isset(auth()->user()->Security_question_index) && isset(auth()->user()->Security_answer))

//     || auth()->user()->isOwner()

// ) {

//     return;

// }

        if (!isset(auth()->user()->added_by) || auth()->user()->isOwner()) {
            return;
        }

        $stepId = $this->getStepId('set-current-password');

        return <<<END
        {
            id: $stepId,
            element: '#currentpassword',
            popover: {
                title: "Current password",
                description: 'For security reasons, you are required to change your password upon your first login. Please enter your current password',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function setNewPasswordStep()
    {

// if ((isset(auth()->user()->Security_question_index) && isset(auth()->user()->Security_answer))

//     || auth()->user()->isOwner()

// ) {

//     return;

// }

        if (!isset(auth()->user()->added_by) || auth()->user()->isOwner()) {
            return;
        }

        $stepId = $this->getStepId('set-new-password');

        return <<<END
        {
            id: $stepId,
            element: '#password',
            popover: {
                title: "Current password",
                description: 'For security reasons, you are required to change your password upon your first login. Please enter the new password which should be strong containing at least one upper case letter, one lower case letter, one digit and one special character',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function setConfirmNewPasswordStep()
    {

// if ((isset(auth()->user()->Security_question_index) && isset(auth()->user()->Security_answer))

//     || auth()->user()->isOwner()

// ) {

//     return;

// }

        if (!isset(auth()->user()->added_by) || auth()->user()->isOwner()) {
            return;
        }

        $stepId = $this->getStepId('set-confirm-new-password');

        return <<<END
        {
            id: $stepId,
            element: '#password_confirmation',
            popover: {
                title: "Confirm New Password",
                description: 'Please re-enter your new password in the "Confirm New Password" field to ensure it matches the password you just entered',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function saveNewPasswordNextStep()
    {

        $general = route('general.index');

        $groups = route('quick-add', ['add' => 'groups']);

        if (auth()->user()->isAdmin()) {

            if (SMTPMails::defaultSmtpMail()->first()) {

                if (Group::first()) {
                    return "driverObj.moveNext();";
                }

                return "window.location.href = '{$groups}'";

            }

            return "window.location.href = '{$general}'";

        }

        return "driverObj.moveNext();";

    }

    private function saveNewPasswordStep()
    {

// if ((isset(auth()->user()->Security_question_index) && isset(auth()->user()->Security_answer))

//     || auth()->user()->isOwner()

// ) {

//     return;

// }

        if (!isset(auth()->user()->added_by) || auth()->user()->isOwner()) {
            return;
        }

        $stepId = $this->getStepId('save-new-password');

        $profile = route('profile.index');

        $nextStep = $this->saveNewPasswordNextStep();

        return <<<END
        {
            id: $stepId,
            element: '#saveBtn-changepassword',
            popover: {
                title: "Save New Password",
                description: 'Click "Save New Password" to update your password. This step finalizes the change and secures your account with the new password',
                nextBtnText: "Next",
                onNextClick: () => {
                    $nextStep
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },

            {$this->popupPosition()}
        },
        END;
    }

    private function generalPageSteps()
    {
        return <<<END
            {$this->setSMTPServerName()}
            {$this->setSMTPPort()}
            {$this->setSMTPUserName()}
            {$this->setSMTPPassword()}
            {$this->setSMTPEncryption()}
            {$this->setSMTPAuthenticationMode()}
            {$this->TestSMTPConnection()}
            {$this->saveSMTPConnection()}
            {$this->setGroupName()}
            {$this->saveGroup()}
            {$this->showDataConnection()}
            {$this->showChartsSection()}
            {$this->showReportsSection()}
            {$this->showKpisSection()}
            {$this->showHomePageSection()}
            {$this->showDashboardSection()}
            {$this->showScheduledReportsSection()}
        END;
    }

    private function setSMTPServerNamePrevStep()
    {

        $profile = route('profile.index');
        $home    = route('home');

// if (auth()->user()->isOwner()) {

        if (isset(auth()->user()->Security_question_index) && !isset(auth()->user()->added_by)) {

            return "window.location.href = '{$home}?step=2'";
        }

        return "window.location.href = '{$profile}?step=7'";

// }

        // return "window.location.href = '{$profile}?step=11'";

    }

    private function setSMTPServerName()
    {

        if (SMTPMails::defaultSmtpMail()->first()) {
            return;
        }

        $stepId = $this->getStepId('set-smtp-server-name');

        $prevStep = $this->setSMTPServerNamePrevStep();

        return <<<END
        {
            id: $stepId,
            element: '#smtp-server',
            popover: {
                title: "Enter Your SMTP Server Name",
                description: "Please enter the SMTP server name from which the system will send emails (e.g., smtp.yourprovider.com). Setting this field correctly is crucial, as it affects the system's ability to send emails.",
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                },
                onPrevClick: () => {
                    sessionStorage.setItem('lastStep',true);
                    $prevStep
                }
            },
            onHighlighted: (element,step,options) => {
                const urlParams = new URLSearchParams(window.location.search);
                const stepParam = urlParams.get('step');
                const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);
                console.log(stepParam,stepIndex);

                if( stepParam != null && stepIndex != -1){
                    setTimeout(()=> {
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    },10);
                }
                $('.driver-popover-prev-btn').removeClass("driver-popover-btn-disabled");
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function setSMTPPort()
    {

        if (SMTPMails::defaultSmtpMail()->first()) {
            return;
        }

        $stepId = $this->getStepId('set-smtp-port');

        return <<<END
        {
            id: $stepId,
            element: '#smtp-port',
            popover: {
                title: "Enter Your SMTP Port",
                description: "Please enter the SMTP port number. The default port is 587 if SSL is used, and 25 if SSL is not used. Setting this field correctly is crucial for the system's ability to send emails.",
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: (elements, step, options) => {
                const urlParams = new URLSearchParams(window.location.search);
                const stepParam = urlParams.get('step');
                const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);
                console.log(stepParam,stepIndex);

                if( stepParam != null && stepIndex != -1){
                    setTimeout(()=> {
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    },10);
                }
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function setSMTPUserName()
    {

        if (SMTPMails::defaultSmtpMail()->first()) {
            return;
        }

        $stepId = $this->getStepId('set-smtp-username');

        return <<<END
        {
            id: $stepId,
            element: '#username',
            popover: {
                title: "Enter Your SMTP Username",
                description: 'Please enter the SMTP username. This is the account name the system will use to send emails.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },

            {$this->popupPosition()}
        },
        END;
    }

    private function setSMTPPassword()
    {

        if (SMTPMails::defaultSmtpMail()->first()) {
            return;
        }

        $stepId = $this->getStepId('set-smtp-password');

        return <<<END
        {
            id: $stepId,
            element: '#password',
            popover: {
                title: "Enter Your SMTP Password",
                description: 'Please enter the SMTP password. This is the password associated with your SMTP username and is required for authentication.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function setSMTPEncryption()
    {

        if (SMTPMails::defaultSmtpMail()->first()) {
            return;
        }

        $stepId = $this->getStepId('set-smtp-encryption');

        return <<<END
        {
            id: $stepId,
            element: '#encryption',
            popover: {
                title: "Enter Your SMTP Encryption Mode",
                description: 'Please select the SMTP encryption mode. Choose between SSL, TLS,  none or auto based on your email provider’s requirements. Proper configuration is crucial for secure email transmission.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },

            {$this->popupPosition()}
        },
        END;
    }

    private function setSMTPAuthenticationMode()
    {

        if (SMTPMails::defaultSmtpMail()->first()) {
            return;
        }

        $stepId = $this->getStepId('set-smtp-authentication');

        return <<<END
        {
            id: $stepId,
            element: '#auth-mode',
            popover: {
                title: "Enter Your SMTP Authentication Mode",
                description: 'Please select the SMTP authentication mode. Common options include LOGIN, PLAIN, or CRAM-MD5. Ensure this matches your email provider’s settings to enable successful email sending.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}

        },
        END;
    }

    private function TestSMTPConnection()
    {

        if (SMTPMails::defaultSmtpMail()->first()) {
            return;
        }

        $stepId = $this->getStepId('test-smtp');

        return <<<END
        {
            id: $stepId,
            element: '#test-smtp-server-connection',
            popover: {
                title: "Test SMTP Connection",
                description: 'Click "Test Connection" to verify that the SMTP settings are correct and the system can successfully send emails. This step is crucial to ensure proper email functionality.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }

            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function getSaveSMTPConnectionNextStep()
    {

        $groups = route('quick-add', ['add' => 'groups']);

        if (auth()->user()->isAdminOrOwner()) {

            if (Group::first()) {
                return "driverObj.moveNext();";
            }

            return "window.location.href = '{$groups}'";

        }

        return "driverObj.moveNext();";

    }

    private function saveSMTPConnection()
    {

        if (SMTPMails::defaultSmtpMail()->first()) {
            return;
        }

        $stepId = $this->getStepId('save-smtp');

        $nextStep = $this->getSaveSMTPConnectionNextStep();

        return <<<END
        {
            id: $stepId,
            element: '#saveBtn-smtp-server',
            popover: {
                title: "Save SMTP Connection Settings",
                description: 'Click "Save" to store your SMTP connection settings. This step is essential to ensure that the system can send emails using the configured SMTP server.',
                nextBtnText: "Next",
                onNextClick: () => {
                    $nextStep
                }

            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function usersPageSteps()
    {
        return <<<END
            {$this->setGroupName()}
            {$this->saveGroup()}
            {$this->showDataConnection()}
            {$this->showChartsSection()}
            {$this->showReportsSection()}
            {$this->showKpisSection()}
            {$this->showHomePageSection()}
            {$this->showDashboardSection()}
            {$this->showScheduledReportsSection()}

        END;
    }

    private function setGroupNamePrevStep()
    {
        $home = route('home');

        $profile = route('profile.index');

        $general = route('general.index');

        $users = route('users.index');

        if (auth()->user()->isAdminOrOwner()) {

            if (SMTPMails::defaultSmtpMail()->first()) {

                if (is_null(auth()->user()->Security_question_index)) {

                    return "window.location.href = '{$profile}?step=7'";
                }

                if (!is_null(auth()->user()->added_by) && !auth()->user()->isOwner()) {

                    return "window.location.href = '{$profile}?step=3'";
                }

                if (is_null(Group::first())) {
                    return "window.location.href = '{$home}?step=2'";

                }

                return "window.location.href = '{$profile}'";
            }

            return "window.location.href = '{$general}'";

        }

        return "window.location.href = '{$profile}'";

    }

    private function setGroupName()
    {

        if (Group::first()) {
            return;
        }

        $stepId = $this->getStepId('set-group-name');

        $prevStep = $this->setGroupNamePrevStep();

        return <<<END
        {
            id: $stepId,
            element: '#group-name',
            popover: {
                title: "Enter User Group Name",
                description: 'Please enter the name for the user group. This will help you organize and manage users efficiently.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                },
                onPrevClick: () => {
                    $prevStep
                }
            },
            onHighlightStarted: (elements, step, options) => {
                setTimeout(()=> {
                    const urlParams = new URLSearchParams(window.location.search);
                    const stepParam = urlParams.get('step');
                    const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);

                    if(stepParam != null && stepIndex != -1 && stepIndex != 21 &&  stepIndex !=22){
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    }else{
                        $('#add-group-modal').modal('show');
                        driverObj.refresh();
                        $('#add-group-modal').on('shown.bs.modal', function () {
                            driverObj.drive();
                        });
                    }
                },100);

            },
            onHighlighted: (elements, step, options) => {
                // setTimeout(()=> {
                //     const urlParams = new URLSearchParams(window.location.search);
                //     const stepParam = urlParams.get('step');
                //     const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);

                //     if( stepParam != null && stepIndex != -1){
                //         $('#add-group-modal').modal('hide');
                //         driverObj.moveTo(stepIndex);
                //         let newUrl = window.location.origin + window.location.pathname;
                //         window.history.replaceState(null, '', newUrl);

                //     }
                // },100);

                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
                $('.driver-popover-prev-btn').removeClass("driver-popover-btn-disabled");
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function saveGroup()
    {

        if (Group::first()) {
            return;
        }

        $stepId = $this->getStepId('save-group');

        return <<<END
        {
            id: $stepId,
            element: '#saveBtn-add-group',
            popover: {
                title: "Save Group",
                description: 'Click "Save Group" to store the user group details. This will create the group and apply your settings.',
                nextBtnText: "Next",
                onNextClick: () => {
                    $('#add-group-modal').modal('hide');
                    driverObj.moveNext();
                }
            },
            onHighlighted: (elements,steps,options) => {
                // console.log(($("#add-group-modal").data('bs.modal') || {})._isShown);
                // if(!($("#add-group-modal").data('bs.modal') || {})._isShown){
                //     $('#add-group-modal').modal('show');
                //     driverObj.refresh();

                //     driverObj.refresh();
                //     $('#add-group-modal').on('shown.bs.modal', function () {
                //         driverObj.drive();
                //         driverObj.moveNext()
                //     });

                // }

                const urlParams = new URLSearchParams(window.location.search);
                const stepParam = urlParams.get('step');
                const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);
                console.log(stepParam,stepIndex);

                if( stepParam != null && stepIndex != -1){
                    setTimeout(()=> {
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    },10);
                }else{
                    $('#add-group-modal').modal('show');
                    driverObj.refresh();
                    $('#add-group-modal').on('shown.bs.modal', function () {
                        driverObj.drive();
                    });
                }

                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function showDataConnectionPrevStep()
    {
        $groups       = route('quick-add', ['add' => 'groups']);
        $general      = route('general.index');
        $profile      = route('profile.index');
        $currentRoute = Route::currentRouteName();
        $user         = auth()->user();
        $defaultSmtp  = SMTPMails::defaultSmtpMail()->first();
        $hasGroup     = Group::first();

        if ($user->isAdminOrOwner()) {

            if ($currentRoute == "users.index") {
                return "driverObj.movePrevious();driverObj.movePrevious();";
            }

            if (!is_null($user->Security_question_index)) {

                if ($defaultSmtp) {

                    if ($hasGroup) {
                        return "driverObj.movePrevious();";
                    }

                } else {
                    return "window.location.href = '{$general}'";
                }

            } else {

                if ($currentRoute == "general.index") {
                    return "driverObj.movePrevious();";
                }

                if ((!$defaultSmtp && $currentRoute != "general.index")) {
                    return "window.location.href = '{$general}'";
                }

                return "window.location.href = '{$profile}'";
            }

        }

        return "driverObj.movePrevious();";
    }

    private function showDataConnection()
    {

        $stepId = $this->getStepId('data-connection');

        $prevStep = $this->showDataConnectionPrevStep();
        return <<<END
        {
            id: $stepId,
            element: '.data-connection-page',
            popover: {
                title: "Data Connections",
                description: "On this page, you can add connections to all MySQL data sources you want to use for your reports, charts, KPIs, and dashboards. The default connection is to the database used by SRM to store its own processes, and it also includes test tables with an orders database to help you quickly test the system's functionality. All online tutorials will use this test data available in the default connection.",
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();

                },
                onPrevClick: (element, step, options) => {
                    const prevStepIndex = options.config.steps.findIndex(step => step.id === 7);
                    if(prevStepIndex !== -1){
                        driverObj.drive(prevStepIndex);

                    }else{
                        $prevStep
                    }
                }
            },
            onHighlighted: (element, step, options) => {

                setTimeout(()=> {
                    const urlParams = new URLSearchParams(window.location.search);
                    const stepParam = urlParams.get('step');
                    const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);

                    if( stepParam != null && stepIndex != -1){
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    }
                },100);


                $('.driver-popover-prev-btn').removeClass("driver-popover-btn-disabled");
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function ChartsSectionPrevStep()
    {
        $home    = route('home');
        $profile = route('profile.index');

        if (!auth()->user()->isAdminOrOwner() && !is_null(auth()->user()->added_by)) {
            return "window.location.href = '{$profile}?step=7'";

        }

        if (!auth()->user()->isAdminOrOwner() && !is_null(auth()->user()->Security_question_index)) {
            return "window.location.href = '{$home}?step=2'";
        } else {
            return "driverObj.movePrevious();";

        }

    }

    private function showChartsSection()
    {
        $stepId = $this->getStepId('chart-section');

        $prevStep = $this->ChartsSectionPrevStep();

        return <<<END
        {
            id: $stepId,
            element: '.charts-page',
            popover:
            {
                title: 'Charts Step',
                description: 'In this section, you can create and manage charts that retrieve data from any MySQL connection. Visualize your data using various chart formats to gain valuable insights. Additionally, you can drill down into any chart for more detailed analysis.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                },
                onPrevClick: (element, step, options) => {
                    $prevStep
                }
            },
            onHighlighted: (element, step, options) => {

                setTimeout(()=> {
                    const urlParams = new URLSearchParams(window.location.search);
                    const stepParam = urlParams.get('step');
                    const stepIndex = options.config.steps.findIndex(step => step.id == stepParam);

                    if( stepParam != null && stepIndex != -1){
                        driverObj.moveTo(stepIndex);
                        let newUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState(null, '', newUrl);

                    }
                },100);

                $('.driver-popover-prev-btn').removeClass("driver-popover-btn-disabled");
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function showReportsSection()
    {
        $stepId = $this->getStepId('reports-section');

        return <<<END
        {
            id: $stepId,
            element: '.reports-page',
            popover:
            {
                title: 'Reports Step',
                description: 'In this section, you can create and manage reports that retrieve data from any MySQL connection. Visualize your data through detailed reports to gain valuable insights.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function showKpisSection()
    {
        $stepId = $this->getStepId('kpis-section');

        return <<<END
        {
            id: $stepId,
            element: '.kpis-page',
            popover:
            {
                title: 'Metrics / KPIs Step',
                description: 'Here, you can create and manage KPIs and metrics. Track the measures that matter most to your business, monitor performance over time, and compare current data with historical values or target goals.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function showHomePageSection()
    {
        $stepId = $this->getStepId('home-page');

        return <<<END
        {
            id: $stepId,
            element: '.home-page',
            popover:
            {
                title: 'Home Page Customization Step',
                description: 'From this area, each user can customize their homepage with widgets displaying report lists, charts, or KPIs they care about. Tailor your dashboard to quickly access the information you need.',
                nextBtnText: "Next",
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function showDashboardSection()
    {

        $stepId = $this->getStepId('dashboards');

        $nextButton = auth()->user()->isAdminOrOwner() ? "nextBtnText: 'Next'," : "";

        return <<<END
        {
            id: $stepId,
            element: '.dashboard-page',
            popover:
            {
                title: 'Dashboards Step',
                description: 'In this section, you can create and customize dashboards. Combine multiple reports, charts, and KPIs into a single view for a comprehensive overview of your data.',
                $nextButton
                onNextClick: () => {
                    driverObj.moveNext();
                }
            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function showScheduledReportsSection()
    {

        if (!auth()->user()->isAdminOrOwner()) {
            return;
        }

        $stepId = $this->getStepId('scheduled-reports-section');

        return <<<END
        {
            id: $stepId,
            element: '.scheduled-reports-page',
            popover:
            {
                title: 'Scheduled Reports Step',
                description: 'Finally, in this area, you can create scheduled reports and send them via email to groups of users who need them. Automate your reporting process to ensure everyone stays informed.',
                onNextClick: () => {
                    driverObj.moveNext();
                }

            },
            onHighlighted: () => {
                sendTourStepRequest($stepId);
                sessionStorage.setItem('currentTourStep',$stepId);
            },
            {$this->popupPosition()}
        },
        END;
    }

    private function updateTourStep($step)
    {

        if (is_int($step) && $step <= 28) {
            auth()->user()->guided_tour_last_visited_step = $step;
            auth()->user()->save();
        }

    }

    private function getCurrentTourStep()
    {

        return !is_null(auth()->user()->guided_tour_last_visited_step)
        ? auth()->user()->guided_tour_last_visited_step
        : 1;

    }

    private function popupPosition()
    {
        return <<<END
            side: "bottom",
            align: "center"
        END;
    }

    public function getTourGuide()
    {
        return $this->buildTour();
    }

}
