<?php

/*
 * ******************************************
   RS Studio Template Hook
   1. Namespaces
   2. Layout Helpers
   3. Template Classes
   4. Order Redirection
   5. Page Header Type
   6. Market Connect Banners
   7. Client Area Home Panels
   8. Module Classes Helper
   9. Site Helper
   10. Light/Dark Mode switcher
   11. Product Details - Get Product group ID
   12. Remove addon from cart + select product period
   13. Check if bundle
   14. Invoice - Show 0% Taxes
   15. Hide Inactive Services
   16. Dashboard Alerts Cookies
   17. Product Configure - Password Strenght - Show Errors
   18. SEO - Server HTTP Host
   19. ProductGroups in renewals
   20. Domain Configuration - TLD Cycle Switcher
   21. Open Ticket - show product group in related services
   22. Product - show clear description
   23. Services List - show end of trial period
   24. Required Company name - client register & checkout 
   25. Configure Product Domain & Configure Domains - Product Free Domain
   26. WordPress Managment icon on the cPanel page
   27. Assets Cache Key
   28. Show amount of hidden services/domains
   29. Custom Language List
   30. Domain Revewals - Renewals In Cart Counter
 * ******************************************
 */

/*
 * ******************************************
   1. Namespaces
 * ******************************************
 */

use RSThemes\Helpers\AddonHelper;
use RSThemes\Models\Domain;
use RSThemes\Models\Icons;
use RSThemes\Models\Page;
use RSThemes\Processors\MenuProcessor;
use RSThemes\Processors\SidebarProcessor;
use WHMCS\Product\Group as ProductGroup;
use WHMCS\Database\Capsule;
use WHMCS\MarketConnect\Service;
use WHMCS\View\Menu\Item as MenuItem;

use WHMCS\CustomField;
use WHMCS\CustomField\CustomFieldValue;
use WHMCS\User\Client;

use RSThemes\Template\Template;
use RSThemes\Template\Page as TemplatePage;

/*
 * ******************************************
   2. Layout Helpers
 * ******************************************
 */
if(basename($_SERVER['SCRIPT_NAME']) == 'cart.php' && isset($_GET['a']) && $_GET['a'] == 'add' && isset($_GET['billingcycle'])) {
    \WHMCS\Session::set("storeBillingCycle", $_GET['billingcycle']);
}

add_hook('ClientAreaPage', 2, function($vars) {
    $actionFile = $vars['templatefile'];
    $configFilePath = realpath(dirname(__FILE__)) . DS .'..'.DS. 'config' . DS . 'layouthelpers.php';

    /* DEFAULT */
    if (file_exists($configFilePath)) {
        $config = require_once $configFilePath;
        if (isset($config[$actionFile])) {
            if (count($config[$actionFile]) == 1) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => false,
                    'forceSidebar' => false,
                    'ignoreMainBody' => false,
                    'sidebarOnRight' => false,
                ];
            } else if (count($config[$actionFile]) == 2) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => $config[$actionFile][1],
                    'forceSidebar' => false,
                    'ignoreMainBody' => false,
                    'sidebarOnRight' => false,
                ];
            }
            else if (count($config[$actionFile]) == 3) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => $config[$actionFile][1],
                    'forceSidebar' => $config[$actionFile][2],
                    'ignoreMainBody' => false,
                    'sidebarOnRight' => false,
                ];
            }
            else if (count($config[$actionFile]) == 4) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => $config[$actionFile][1],
                    'forceSidebar' => $config[$actionFile][2],
                    'ignoreMainBody' => $config[$actionFile][3],
                    'sidebarOnRight' => false,
                ];
            }
            else if (count($config[$actionFile]) == 5) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => $config[$actionFile][1],
                    'forceSidebar' => $config[$actionFile][2],
                    'ignoreMainBody' => $config[$actionFile][3],
                    'sidebarOnRight' => $config[$actionFile][4],
                ];
            }
            else{
                return [
                    'ignoreSidebars' => false,
                    'ignoreHeader' => false,
                    'forceSidebar' => false,
                    'ignoreMainBody' => false,
                    'sidebarOnRight' => false,
                ];
            }
        } else {
            return [
                'ignoreSidebars' => false,
                'ignoreHeader' => false,
                'forceSidebar' => false,
                'ignoreMainBody' => false,
                'sidebarOnRight' => false,
            ];
        }
    }
});

add_hook('ClientAreaPage', 3, function($vars) {
    $actionFile = $vars['templatefile'];
    $configFilePathCustom = realpath(dirname(__FILE__)) . DS .'..'.DS. 'config' . DS . 'layouthelpers-custom.php';
    
     /* CUSTOM */
     if (file_exists($configFilePathCustom)) {
        $config = require_once $configFilePathCustom;
        if (isset($config[$actionFile])) {
            if (count($config[$actionFile]) == 1) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => false,
                    'forceSidebar' => false,
                    'ignoreMainBody' => false,
                    'sidebarOnRight' => false,
                ];
            } else if (count($config[$actionFile]) == 2) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => $config[$actionFile][1],
                    'forceSidebar' => false,
                    'ignoreMainBody' => false,
                    'sidebarOnRight' => false,
                ];
            }
            else if (count($config[$actionFile]) == 3) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => $config[$actionFile][1],
                    'forceSidebar' => $config[$actionFile][2],
                    'ignoreMainBody' => false,
                    'sidebarOnRight' => false,
                ];
            }
            else if (count($config[$actionFile]) == 4) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => $config[$actionFile][1],
                    'forceSidebar' => $config[$actionFile][2],
                    'ignoreMainBody' => $config[$actionFile][3],
                    'sidebarOnRight' => false,
                ];
            }
            else if (count($config[$actionFile]) == 5) {
                return [
                    'ignoreSidebars' => $config[$actionFile][0],
                    'ignoreHeader' => $config[$actionFile][1],
                    'forceSidebar' => $config[$actionFile][2],
                    'ignoreMainBody' => $config[$actionFile][3],
                    'sidebarOnRight' => $config[$actionFile][4],
                ];
            }
        }
    }
});

/*
 * ******************************************
   3. Template Classes
 * ******************************************
 */

add_hook('ClientAreaPage', 2, function($vars) {
    $actionFile = $vars['templatefile'];
    $configFilePath = realpath(dirname(__FILE__)) . DS .'..'.DS. 'config' . DS . 'templateclasses.php';

    /* DEFAULT */
    if (file_exists($configFilePath)) {
        $config = require_once $configFilePath;
        if (isset($config[$actionFile])) {
            if (count($config[$actionFile]) == 1) {
                return [
                    'appMainBodyClasses' => $config[$actionFile][0],
                    'bodyClasses' => false,
                    'mainContentClasses' => false,
                ];
            } else if (count($config[$actionFile]) == 2) {
                return [
                    'appMainBodyClasses' => $config[$actionFile][0],
                    'bodyClasses' => $config[$actionFile][1],
                    'mainContentClasses' => false,
                ];
            }
            else if (count($config[$actionFile]) == 3) {
                return [
                    'appMainBodyClasses' => $config[$actionFile][0],
                    'bodyClasses' => $config[$actionFile][1],
                    'mainContentClasses' => $config[$actionFile][2],
                ];
            }            
        }
    }
});

add_hook('ClientAreaPage', 3, function($vars) {
    $actionFile = $vars['templatefile'];
    $configFilePathCustom = realpath(dirname(__FILE__)) . DS .'..'.DS. 'config' . DS . 'templateclasses-custom.php';
    
    /* CUSTOM */
    if (file_exists($configFilePathCustom)) {
        $config = require_once $configFilePathCustom;
        if (isset($config[$actionFile])) {
            if (count($config[$actionFile]) == 1) {
                return [
                    'appMainBodyClasses' => $config[$actionFile][0],
                    'bodyClasses' => false,
                    'mainContentClasses' => false,
                ];
            } else if (count($config[$actionFile]) == 2) {
                return [
                    'appMainBodyClasses' => $config[$actionFile][0],
                    'bodyClasses' => $config[$actionFile][1],
                    'mainContentClasses' => false,
                ];
            }
            else if (count($config[$actionFile]) == 3) {
                return [
                    'appMainBodyClasses' => $config[$actionFile][0],
                    'bodyClasses' => $config[$actionFile][1],
                    'mainContentClasses' => $config[$actionFile][2],
                ];
            }
        }
    }
});


/*
 * ****************************************************************
   4. Order Redirection - Don't show view cart page as separate
 * ****************************************************************
 */

add_hook('ClientAreaPage', -100000000, function($vars) {
    if (isset($vars['inShoppingCart'])) {
        if (isset($_GET['a']) && $_GET['a'] == 'view') {
            $url = 'cart.php?a=checkout';
            header("Location: $url");
            die();
        }
    }
});

/*
 * ******************************************
   5. Page Header Type
 * ******************************************
 */

add_hook('ClientAreaPage', 2, function($vars) {
    $actionFile = $vars['templatefile'];
    $configFilePath = realpath(dirname(__FILE__)) . DS .'..'.DS. 'config' . DS . 'pageheader.php';

    /* DEFAULT */
    if (file_exists($configFilePath)) {
        $config = require_once $configFilePath;
        if (isset($config[$actionFile])) {
            if (count($config[$actionFile]) == 1) {
                return [
                    'RSheadersearch' => $config[$actionFile][0],
                    'RSheadercenter' => false,
                ];
            } else if (count($config[$actionFile]) == 2) {
                return [
                    'RSheadersearch' => $config[$actionFile][0],
                    'RSheadercenter' => $config[$actionFile][1],
                ];
            }
            else{
                return [
                    'RSheadersearch' => false,
                    'RSheadercenter' => false,
                ];
            }
        } else {
            return [
                'RSheadersearch' => false,
                'RSheadercenter' => false,
            ];
        }
    }
});

add_hook('ClientAreaPage', 3, function($vars) {
    $actionFile = $vars['templatefile'];
    $configFilePathCustom = realpath(dirname(__FILE__)) . DS .'..'.DS. 'config' . DS . 'pageheader-custom.php';

    /* CUSTOM */
    if (file_exists($configFilePathCustom)) {
        $config = require_once $configFilePathCustom;
        if (isset($config[$actionFile])) {
            if (count($config[$actionFile]) == 1) {
                return [
                    'RSheadersearch' => $config[$actionFile][0],
                    'RSheadercenter' => false,
                ];
            } else if (count($config[$actionFile]) == 2) {
                return [
                    'RSheadersearch' => $config[$actionFile][0],
                    'RSheadercenter' => $config[$actionFile][1],
                ];
            } 
        }
    }
});

/*
 * ******************************************
   6. Market Connect Banners
 * ******************************************
 */

if(isset($_SESSION['uid']) && basename($_SERVER['SCRIPT_NAME']) !== 'logout.php' && strpos($_SERVER['QUERY_STRING'], 'verificationId') === false){
    $rsServicesHooks = [
        'ClientAreaPage',
        'ClientAreaPageProductsServices',
        'ClientAreaHomepage',
        'ClientAreaPageProductDetails'
    ];
}
else{
    $rsServicesHooks = [
        'ClientAreaPageProductsServices',
        'ClientAreaHomepage',
        'ClientAreaPageProductDetails'
    ];
}

foreach ($rsServicesHooks as $rsServicesHook) {
    add_hook($rsServicesHook, -2, function($var = NULL) {
        return [
            'RSMarketConnectServices' => Service::active()->get()->toArray()
        ];
    });
}

/*
 * ******************************************
   7. Client Area Home Panels
 * ******************************************
 */

use WHMCS\View\Menu\Item;
add_hook('ClientAreaHomepagePanels', 1, function (Item $homePagePanels) {

    $recentTicketsPanel = $homePagePanels->getChild('Recent Support Tickets');
    $activeServicesPanel = $homePagePanels->getChild('Active Products/Services');
    $affiliatePanel = $homePagePanels->getChild('Affiliate Program');
    $recentNewsPanel = $homePagePanels->getChild('Recent News');

    if (!is_null($recentTicketsPanel)) {
        $recentTicketsPanel->setExtras(
            []
        );
    }
    if (!is_null($activeServicesPanel)) {
        $activeServicesPanel->setExtras(
            []
        )->setOrder(0);
        $activeServicesPanel->setFooterHtml('');
    }
    if (!is_null($affiliatePanel)) {
        $affiliatePanel->setExtras(
            []
        );
    }
    if (!is_null($recentNewsPanel)) {
        $recentNewsPanel->setExtras(
            []
        );
    }
});

/*
 * ******************************************
   8. Module Classes Helper
 * ******************************************
 */

add_hook('ClientAreaPage', 2, function($vars) {
    if (isset($_GET['m'])){
        if ($_GET['m'] == "DomainOrdersExtended"){
            return [
                'pageModuleName' => 'searchdomains'
            ];
        }
        else if ($_GET['m'] == "DNSManager2"){
            return [
                'pageModuleName' => 'dnsmanager'
            ];
        }
        else{
            $moduleName = strtolower($_GET['m']);
            $moduleName = str_replace(' ', '', $moduleName);
            return [
                'pageModuleName' => $moduleName
            ];
        }
    }
});

/*
 * ******************************************
   9. Site Helper
 * ******************************************
 */

add_hook('ClientAreaPage', 2, function($vars) {
    $actionFile = $vars['templatefile'];
    $configFilePath = realpath(dirname(__FILE__)) . DS .'..'.DS. 'config' . DS . 'site.php';

    /* DEFAULT */
    if (file_exists($configFilePath)) {
        $config = require_once $configFilePath;
        if (isset($config[$actionFile])) {
            if (count($config[$actionFile]) == 1) {
                return [
                    'isSite' => $config[$actionFile][0],
                    'siteSeoDesc' => false
                ];
            }
            else if (count($config[$actionFile]) == 2) {
                return [
                    'isSite' => $config[$actionFile][0],
                    'siteSeoDesc' => $config[$actionFile][1]
                ];
            }
            else{
                return [
                    'isSite' => false,
                    'siteSeoDesc' => false
                ];
            }
        } else {
            return [
                'isSite' => false,
                'siteSeoDesc' => false
            ];
        }
    }
});

add_hook('ClientAreaPage', 3, function($vars) {
    $actionFile = $vars['templatefile'];
    $configFilePathCustom = realpath(dirname(__FILE__)) . DS .'..'.DS. 'config' . DS . 'site-custom.php';

    /* CUSTOM */
    if (file_exists($configFilePathCustom)) {
        $config = require_once $configFilePathCustom;
        if (isset($config[$actionFile])) {
            if (count($config[$actionFile]) == 1) {
                return [
                    'isSite' => $config[$actionFile][0],
                    'siteSeoDesc' => false
                ];
            }
            else if (count($config[$actionFile]) == 2) {
                return [
                    'isSite' => $config[$actionFile][0],
                    'siteSeoDesc' => $config[$actionFile][1]
                ];
            }
        } 
    }
});

/*
 * ******************************************
   10. Light/Dark Mode switcher
 * ******************************************
 */

add_hook('ClientAreaPage', 1, function($vars) {
    $displayModeSwitcher = \RSThemes\Models\Settings::where('setting', 'display_mode_switcher')->first();
    $displayModeSwitcherEnabled = (bool) $displayModeSwitcher->value;
    $darkModeEnabledValue = false; //default value
    if ($displayModeSwitcherEnabled) {
        if (isset($_COOKIE['lagom_client_theme_dark_mode'])) { //get cookie value
            $darkModeEnabledValue = $_COOKIE['lagom_client_theme_dark_mode'];
        } 
    }
    return [
        'display_mode_switcher' => [
            'enabled' => $displayModeSwitcherEnabled,
            'dark' => $darkModeEnabledValue
        ]
    ];
});

/*
 * ******************************************
   11. Product Details - Get Product group ID
 * ******************************************
 */

add_hook('ClientAreaPageProductDetails', 2, function($vars) {
    $groupId = ProductGroup::where('name', $vars['groupname'])->value('id');
    return [
        'groupId' => $groupId
    ];
});

add_hook('ClientAreaPage', 1, function($vars) {
    $uri = str_replace("&amp;", "&", $_SERVER['REQUEST_URI']);
    $uri = strstr($uri, '?rs', true) ?: $uri;
    $uri = strstr($uri, '&rs', true) ?: $uri;

    if($vars['templatefile'] == "knowledgebasearticle"){
        $uri = routePath('knowledgebase-article-view' ,$vars['kbarticle']['id'],$vars['kbarticle']['urlfriendlytitle']);
    }elseif($vars['templatefile'] == "knowledgebase"){
        $uri = routePath('knowledgebase-index');
    }elseif($vars['templatefile'] == "knowledgebasecat"){
        $uri = routePath('knowledgebase-category-view', $vars['kbcurrentcat']['id'],$vars['kbcurrentcat']['urlfriendlyname']);
    }elseif($vars['templatefile'] == "announcements"){
        $uri = routePath('announcement-index');
    }elseif($vars['templatefile'] == "viewannouncement"){
        $uri = routePath('announcement-view',$vars['id'],$vars['urlfriendlytitle']);
    }elseif($vars['templatefile'] == "downloads"){
        $uri = routePath('download-index');
    }


    return [
        'currentUrl' => $uri,
        'hideServerAlert' => $_SESSION['hide_server_alert'] ?? ""
    ];
});

/*
 * ******************************************
   12. Remove addon from cart + select product period
 * ******************************************
*/

add_hook('ClientAreaPage', 1, function($vars) {
    
    if ($vars['templatefile'] == "viewcart"){

        $currency = getCurrency(WHMCS\Session::get("uid"), WHMCS\Session::get("currency"));
        
        if(App::getFromRequest("removeAddon"))
        {   
            if (App::getFromRequest("pt") == "products" && $_SESSION['cart']['products'][App::getFromRequest("pi")]){
                unset($_SESSION['cart']['products'][App::getFromRequest("pi")]['addons'][App::getFromRequest("ai")]);
            }
            if (App::getFromRequest("pt") == "domains" && $_SESSION['cart']['domains'][App::getFromRequest("pi")]){
                $_SESSION['cart']['domains'][App::getFromRequest("pi")][App::getFromRequest("ai")] = NULL;
            }
            if (App::getFromRequest("pt") == "renewals" && $_SESSION['cart']['rewals'][App::getFromRequest("pi")]){
                $_SESSION['cart']['rewals'][App::getFromRequest("pi")][App::getFromRequest("ai")] = NULL;
            }

            $response = new WHMCS\Http\JsonResponse();
            $response->setData(calcCartTotals(null, false, $currency));
            $response->send();
            WHMCS\Terminus::getInstance()->doExit();
        }

        elseif(App::getFromRequest("selectProductPeriod") && App::getFromRequest("pi") >= 0 && App::getFromRequest("pc") )
        {
            if($_SESSION['cart']['products'][App::getFromRequest("pi")])
            {
                $_SESSION['cart']['products'][App::getFromRequest("pi")]['billingcycle'] = App::getFromRequest("pc");
            }
            
            $response = new WHMCS\Http\JsonResponse();
            $response->setData(calcCartTotals(null, false, $currency));
            $response->send();
            WHMCS\Terminus::getInstance()->doExit();
        }
        $cycles = [];
        $billingcycles = [];
        foreach($vars['products'] as $i => $p)
        {
            $product = \WHMCS\Product\Product::find($vars['products'][$i]['pid']);
            $cycles[$i] = $product->pricing()->allAvailableCycles();
            $billingcycles[$i] = [];
            $proratabilling = in_array($product->paytype, [WHMCS\Product\Product::PAYMENT_ONETIME, WHMCS\Product\Product::PAYMENT_FREE]) ? "" : $product->proratabilling;

            try {
                foreach($cycles[$i] as $key => $cycle)
                { 
                    if ($proratabilling) {
                        $proratavalues = getProrataValues($cycle->cycle(), $cycle->price()->toNumeric(), $product->proratadate, $product->proratachargenextmonth, date("d"), date("m"), date("Y"), $_SESSION['uid']);
                        $product_onetime = $proratavalues["amount"];
                        $exploded = explode('/', $cycle->toFullString());
                        $billingcycles[$i][] = [
                            'price' => $product_onetime, // add currency
                            'cycle' => $cycle->cycle(),
                            'toFullString' => $currency['prefix'] . $product_onetime . $currency['suffix'] . '/' . $exploded[1],
                            'toFullStringCalculated' => $currency['prefix'] . $product_onetime . $currency['suffix'] . '/' . $exploded[1],
                        ];
                    }else
                    {
                        $currency = $cycle->price()->getCurrency();
                        //$currency['format'] = 1;
                        $exploded = explode('/', $cycle->toFullString());
                        $price = new \WHMCS\View\Formatter\Price($cycle->price()->toNumeric()*$p['qty'],$cycle->price()->getCurrency());
                        $billingcycles[$i][] = [
                            'price' => $cycle->price(),
                            'cycle' => $cycle->cycle(),
                            'toFullString' => $cycle->toFullString(),
                            //'toFullStringFormatted' => $cycle->price()->format(NULL, $currency) . '/' . $exploded[1],
                            'toFullStringCalculated' => $price->format() . '/' . $exploded[1],
                        ];
                    }
                
                }

               
            } catch (\Throwable $th) {}
        }
        return [ 'allAvailableCycles' => $billingcycles];
    }
});

/*
 * ******************************************
   13. Check if bundle
 * ******************************************
*/

add_hook('ClientAreaPage', 1, function($vars) {
    if (isset($_SESSION['cart']['bundle']) && !empty($_SESSION['cart']['bundle']) && $vars['templatefile'] == 'configureproductdomain'){
        return [
            'isBundle' => true                  
        ];
    }
});

/*
 * ******************************************
   14. Invoice - Show 0% Taxes
 * ******************************************
*/

add_hook('ClientAreaPageViewInvoice', 1, function($vars) {
    if(function_exists('invoiceVars')){
        $vars = invoiceVars($vars);
        foreach($vars as $var => $value){
            $vars[$var] = $value;
        }
    }
    return $vars;
});

/*
 * ******************************************
    15. Hide Inactive Services
 * ******************************************
*/

add_hook('ClientAreaPage', 1, function($vars) {
    if ($vars['templatefile'] == "clientareaproducts" || $vars['templatefile'] == "clientareadomains"){
        if (isset($_COOKIE['hideInactiveSercices']) && $_COOKIE['hideInactiveSercices'] == "true"){
            $inactiveServices = true;
        }
        else{
            $inactiveServices = false;
        }
    
        if (isset($_COOKIE['hideInactiveDomains']) && $_COOKIE['hideInactiveDomains'] == "true"){
            $inactiveDomains = true;
        }
        else{
            $inactiveDomains = false;
        }
    
        $hideInacviveServices = [
            "inactiveServices" => $inactiveServices,
            "inactiveDomains" => $inactiveDomains
        ];
    
        return [
            'hideInactiveServices' => $hideInacviveServices
        ];
    }
    
});

add_hook('ClientAreaPageSubmitTicket', 1, function($vars) {
    $user = $vars['client'];
    $client = Client::find($user->id);
    if ($client){
        $clientServices = $client->services()->get();
        $clientDomains = $client->domains()->get();

        $services = [];
        $domains = [];
        foreach ($clientServices as $key => $service) {
            $services[$key]['id'] = $service->id;
            $services[$key]['status'] = $service->status;
        }
        foreach($clientDomains as $key => $domain) {
            $domains[$key]['id'] = $domain->id;
            $domains[$key]['status'] = $domain->status;
        }

        return[
            'services' => $services,
            'domains' => $domains
        ];
    }
});

/*
 * ******************************************
    16. Dashboard Alerts Cookies
 * ******************************************
*/

add_hook('ClientAreaPage', 2, function($vars) {
    if ($vars['templatefile'] == "clientareahome"){
        return[
            'clienthomealertscookies' => $_COOKIE
        ];
    }
});

/*
 * **************************************************************
    17. Product Configure - Password Strenght - Show Errors
 * **************************************************************
*/

add_hook('ShoppingCartValidateProductUpdate', 1, function($vars) {
    $validate = new WHMCS\Validate();
    if (isset($vars['rootpwstrength']) && $vars['rootpwstrength'] == "true"){
        if (!$validate->validate("pwstrength", 'rootpw', "pwstrengthfail")){
            return [    
                Lang::trans("pwstrengthfail")
            ];
        }
    }
});


/*
 * **************************************************************
    18. SEO - Server HTTP Host
 * **************************************************************
*/

add_hook('ClientAreaPage', 2, function($vars) {
    // if ($vars['templatefile'] == "knowledgebasearticle" || $vars['templatefile'] == "viewannouncement" || $vars['templatefile'] == "products" || str_contains($vars['templatefile'], "store/")){
        $seoHost = 'https://'.$_SERVER['HTTP_HOST'].'/';
        $defaultLanguage = (new \RSThemes\Models\Configuration())->getConfig('Language');
        return[
            'seoHost' => $seoHost,
            'defaultLanguage' => $defaultLanguage
        ];
    // }
});

/*
 * **************************************************************
    19. ProductGroups
 * **************************************************************
*/

add_hook('ClientAreaPage', 2, function($vars) {
    if(isset($vars['gid']) && isset($vars['services']) && $vars['gid'] == "service-renewals" && $vars['services'] == "renew"){
        $renewableServicesGroups = [];
        if(isset($vars['renewableServices']))
            foreach($vars['renewableServices'] as $item){
                if(!isset($renewableServicesGroups[$item['product']->gid]))
                    $renewableServicesGroups[$item['product']->gid] = ProductGroup::where('id', $item['product']->gid)->first();
            }
        if(isset($vars['nonRenewableServices']))
            foreach($vars['nonRenewableServices'] as $item){
                if(!isset($renewableServicesGroups[$item['product']->gid]))
                    $renewableServicesGroups[$item['product']->gid] = ProductGroup::where('id', $item['product']->gid)->first();
            }
        return ['renewableServicesGroups' => $renewableServicesGroups];
    }
});

/*
 * **************************************************************
    20. Domain Configuration - TLD Cycle Switcher
 * **************************************************************
*/

add_hook('ClientAreaPage', 2, function($vars) {
    if ($vars['templatefile'] == "configuredomains"){
        $tldCycleSwitcher = \RSThemes\Models\Settings::where('setting', 'tld_cycle_switcher')->first();
        $tldCycleSwitcherEnabled = (bool) $tldCycleSwitcher->value;
        if ($tldCycleSwitcherEnabled){
            $tldPricing = [];
            foreach ($vars['domains'] as $domain){
                $domainName = explode('.', $domain['domain'], 2);
                $tld = $domainName[1];
                $tldPricing[$tld] = getTLDPriceList("." . $tld);
                foreach($_SESSION['cart']['domains'] as $sessionDomain){
                    if ($sessionDomain['domain'] == $domain['domain']){
                        $tldPricing[$domain['domain']] = $sessionDomain['type'];
                    }
                }
            }
            $orderForm = new WHMCS\OrderForm();
            $cartDomains = $orderForm->getCartDataByKey("domains");
            if (is_array($cartDomains)) {
                foreach ($cartDomains as $key => $domain) {
                    if ($domain['isPremium'] && $domain['domainpriceoverride']){
                        $domainName = explode('.', $domain['domain'], 2);
                        $tld = $domainName[1];
                        unset($tldPricing[$tld]);
                        $tldPricing[$tld]['1']['register'] = $domain['domainpriceoverride'];
                    }
                }
            }

            return [
                'tldPricing' => $tldPricing
            ];
        }
    }
});

/*
 * **************************************************************
    21. Open Ticket - show product group in related services
 * **************************************************************
*/

add_hook('ClientAreaPageSubmitTicket', 1, function($vars) {
    if (isset($vars['relatedservices']) && is_array($vars['relatedservices']) && $vars['templatefile'] == "supportticketsubmit-steptwo"){
        $template = new Template($vars['template']);
        $page = new TemplatePage($template, 'supportticketsubmit-steptwo');
        if (isset($page) && $page){
            if ($page->getConfiguredOption()){
                $settings = $page->getConfiguredOption()->getSettings(true);
            }
        }
        if (isset($settings) && is_array($settings)){
            if (isset($settings['showProductGroupInRelatedSectives']) && $settings['showProductGroupInRelatedSectives'] == 1){
                $show_product_group = true;
            }
        }
        if (isset($show_product_group) && $show_product_group){
            foreach ($vars['relatedservices'] as $key => $relatedService){
                if(str_contains($relatedService['id'], "S")){
                    $currentId = str_replace('S', '', $relatedService['id']);
                    $product = WHMCS\Product\Product::where('id', $currentId)->first();
                    $group = ProductGroup::where('id', $product->gid)->first();
                    $vars['relatedservices'][$key]['groupName'] = $group->name;
                }
            }
            return $vars;
        }
    }
});

/*
 * **************************************************************
    22. Product - show clear description
 * **************************************************************
*/

add_hook('ClientAreaPage', 99999999999, function($vars) {
    if ($vars['templatefile'] == "products" || $vars['templatefile'] == "configureproduct"){
        $descriptionStyle = \RSThemes\Models\Settings::where('setting', 'product_description_style')->first();
        $descriptionStyleEnabledOption = "clear";
        if (isset($descriptionStyle) && $descriptionStyle){
            $descriptionStyleEnabledOption = $descriptionStyle->value;
        }
        if ($descriptionStyleEnabledOption == "clear"){
            $language = $vars['language'];
            
            if ($vars['templatefile'] == "products"){
                $products = $vars['products'];
               
                foreach ($products as $key => $product){
                    $translatedDescription = "";
                    if (\WHMCS\Config\Setting::getValue("EnableTranslations")) {
                        $translatedDescription = \Lang::trans("product." . $product['pid'] . ".description", [], "dynamicMessages", $language);
                    }
                    $description = \WHMCS\Product\Product::getProductDescription($product['pid']);
                   
                    $vars['products'][$key]['clearDescription'] = strlen($translatedDescription) && $translatedDescription != "product." . $product['pid'] . ".description" ? $translatedDescription : $description;  
                }
            }
            if ($vars['templatefile'] == "configureproduct"){
                $translatedDescription = "";
                if (\WHMCS\Config\Setting::getValue("EnableTranslations")) {
                    $translatedDescription = \Lang::trans("product." . $vars['productinfo']['pid'] . ".description", [], "dynamicMessages", $language);
                }
                $description = \WHMCS\Product\Product::getProductDescription($vars['productinfo']['pid']);
                
                $vars['productinfo']['clearDescription'] = strlen($translatedDescription) && $translatedDescription != "product." . $vars['productinfo']['pid'] . ".description" ? $translatedDescription : $description;    
            }
            return $vars;
        } 
    }
});

/*
 * **************************************************************
    23. Services List - show end of trial period
 * **************************************************************
*/

add_hook('ClientAreaPage', 1, function($vars) {
    if ($vars['templatefile'] == "clientareaproducts" ){
        $template = new Template($vars['template']);
        $page = new TemplatePage($template, 'clientareaproducts');
        if (isset($page) && $page){
            if ($page->getConfiguredOption()){
                $settings = $page->getConfiguredOption()->getSettings(true);
            }
        }
        if (isset($settings) && is_array($settings)){
            if (isset($settings['showEndOfTrialPeriod']) && $settings['showEndOfTrialPeriod'] == 1){
                $show_end_of_trial_period = true;
            }
        }
        if (isset($show_end_of_trial_period) && $show_end_of_trial_period){
            $autoterminatedays = [];
            foreach($vars['services'] as $key => $service){
                $package = Capsule::table('tblhosting')->where('id', $service['id'])->get('packageid')->first();
                $product = Capsule::table('tblproducts')->where('id', $package->packageid)->get('autoterminatedays')->first();
                if ($product->autoterminatedays > 0){
                    $autoterminateddate = new DateTime($service['normalisedRegDate']);
                    $autoterminateddate->modify('+'.$product->autoterminatedays.' days');
                    $autoterminatedays[$service['id']] = $autoterminateddate->format('d.m.Y');
                }  
            }
            return [
                'autoterminatedays' => $autoterminatedays
            ];
        }
    }
});


/*
 * **************************************************************
    24. Required Company name - client register & checkout 
 * **************************************************************
*/

add_hook('ClientDetailsValidation', 2, function($vars) {
   
    if ((basename($_SERVER["SCRIPT_FILENAME"], '.php') == "register" || (basename($_SERVER["SCRIPT_FILENAME"], '.php') == "cart") && isset($_GET['a']) && $_GET['a'] == "checkout") && $GLOBALS['CONFIG']['Template'] == "lagom2"){
        $template = new Template($GLOBALS['CONFIG']['Template']);
       
        if (basename($_SERVER["SCRIPT_FILENAME"], '.php') == 'register'){
            $templatefile = "clientregister";
        }
        else if (basename($_SERVER["SCRIPT_FILENAME"], '.php') == 'cart'){
            $templatefile = "viewcart";
        }
        if (isset($templatefile)){
            $page = new TemplatePage($template, $templatefile);
            if (isset($page) && $page){
                if ($page->getConfiguredOption()){
                    $settings = $page->getConfiguredOption()->getSettings(true);
                }
            }
            if (isset($settings) && is_array($settings)){
                if (isset($settings['companyNameRequired']) && $settings['companyNameRequired'] == 1){
                    $companyNameRequired = true;
                }
            }
            if (isset($companyNameRequired) && $companyNameRequired) {
                if (isset($vars['companyname']) && $vars['companyname'] == ""){
                    $errors[] = Lang::trans("clientareacompanyname") .' '. Lang::trans("clientareaerrorisrequired");
                    return $errors;
                }
            }
        }
    }
});

/*
 * ***********************************************************************
    25. Configure Product Domain & Configure Domains - Product Free Domain
 * ***********************************************************************
*/

add_hook('ClientAreaPage', 2, function($vars) {
    if ($vars['templatefile'] == "configureproductdomain"){
        $productPid = $vars['productinfo']['pid'];
        $searchKey = 'pid';
        $searchValue = $productPid;
        if (isset($_SESSION['cart']['products']) && is_array($_SESSION['cart']['products'])){
            $result = array_filter($_SESSION['cart']['products'], function ($subarray) use ($searchKey, $searchValue) {
                return isset($subarray[$searchKey]) && $subarray[$searchKey] === $searchValue;
            });
            if (count($result) > 0){
                return [
                    'freeDomainNotAllowed' => true
                ];
            }
        }
    }

    if ($vars['templatefile'] == "configureproduct" && isset($vars['productinfo']['freedomaintlds']) && !empty($vars['productinfo']['freedomaintlds']) && is_array($vars['productinfo']['freedomaintlds'])){
        $freeProductDomainOption = \RSThemes\Models\Settings::where('setting', 'product_domain_free_price')->first();
        if (isset($freeProductDomainOption) && $freeProductDomainOption){
            $freeProductDomainOptionValue = $freeProductDomainOption->value;
        }
        if ($freeProductDomainOptionValue == "true"){
            $productPid = $vars['productinfo']['pid'];
            $searchKey = 'pid';
            $searchValue = $productPid;
            if (isset($_SESSION['cart']['products']) && is_array($_SESSION['cart']['products'])){
                $result = array_filter($_SESSION['cart']['products'], function ($subarray) use ($searchKey, $searchValue) {
                    return isset($subarray[$searchKey]) && $subarray[$searchKey] === $searchValue;
                });
                $result = reset($result);
                $freeDomainAssignedToProduct = false;
                if (!empty($result) && (!isset($result['qty']) || $result['qty'] == 1)) {
                    if (isset($result['domain'])){
                        $domain =  explode('.',$result['domain'], 2);
                        $tld = '.'.last($domain);
                        if (in_array($tld, $vars['productinfo']['freedomaintlds'])){
                            $freeDomainAssignedToProduct = true;
                        }
                    }
                }
                return [
                    'freeDomainAssignedToProduct' => $freeDomainAssignedToProduct
                ];
            }
        }  
    }
    if ($vars['templatefile'] == "configuredomains" && isset($vars['domains']) && is_array($vars['domains']) && !empty($vars['domains'])){
        $freeProductDomainOption = \RSThemes\Models\Settings::where('setting', 'product_domain_free_price')->first();
        if (isset($freeProductDomainOption) && $freeProductDomainOption){
            $freeProductDomainOptionValue = $freeProductDomainOption->value;
        }
        if ($freeProductDomainOptionValue == "true"){
            foreach ($vars['domains'] as $key => $domain){
                if ($domain['hosting']){
                    $searchKey = 'domain';
                    $searchValue = $domain['domain'];
                    $result = array_filter($_SESSION['cart']['products'], function ($subarray) use ($searchKey, $searchValue) {
                        return isset($subarray[$searchKey]) && $subarray[$searchKey] === $searchValue;
                    });
                   
                    $result = reset($result);
                    $product = WHMCS\Product\Product::where('id', $result['pid'])->first();
                    if (isset($product['freedomaintlds']) && !empty($product['freedomaintlds']) && isset($product['freedomain']) && $product['freedomain'] != ""){
                        $productFreeDomainTlds = explode(',',$product['freedomaintlds']);
                        if (is_array($productFreeDomainTlds) && !empty($productFreeDomainTlds)){
                            $domainArray =  explode('.',$domain['domain'], 2);
                            $tld = '.'.last($domainArray);
                            if (in_array($tld, $productFreeDomainTlds)){
                                $vars['domains'][$key]['freeDomainAssignedToProduct'] = true;
                            }
                        }
                    }
                }
            }
            return $vars;
        }
    }
});

/*
 * **************************************************************
    26. WordPress Managment icon on the cPanel page
 * **************************************************************
*/

add_hook('ClientAreaPrimarySidebar', 9999, function($vars) {

    $primarySidebar = Menu::primarySidebar();

    if ($primarySidebar && !is_null($primarySidebar->getChild('Service Details Actions'))) {
        $wpManager = $primarySidebar->getChild('Service Details Actions');
        if (!is_null($wpManager->getChild('mg-wp-manager'))){
            $wpManager->getChild('mg-wp-manager')->setIcon('fab fa-wordpress');
        }
    }
});

/*
 * **************************************************************
    27. Assets Cache Key
 * **************************************************************
*/

add_hook('ClientAreaPage', 2, function($vars) {
    $assetsCacheKey = AddonHelper::getCacheKey();
    return [
        'assetsCacheKey' => $assetsCacheKey
    ];
});

/*
 * **************************************************************
    28. Show amount of hidden services/domains
 * **************************************************************
*/

add_hook('ClientAreaPageDomains', 2, function($vars) {
    $template = AddonHelper::getCurrentTemplate();
    $page = (new \RSThemes\Template\Page(AddonHelper::getCurrentTemplateObject(), "clientareadomains"));
    $pageConfig = $page->getConfiguredOption()->getSettings(true);
    if(isset($pageConfig['hideInactiveServicesStatus']) && is_array($pageConfig['hideInactiveServicesStatus'])) {
        $domains = Domain::where("userid", \Auth::client()->id);
        $domains->whereIn("status", $pageConfig['hideInactiveServicesStatus']);
        return ["hiddenInactiveAmount"=>$domains->count()];
    }
});

add_hook('ClientAreaPageServices', 2, function($vars) {
    $template = AddonHelper::getCurrentTemplate();
    $page = (new \RSThemes\Template\Page(AddonHelper::getCurrentTemplateObject(), "clientareadomains"));
    $pageConfig = $page->getConfiguredOption()->getSettings(true);
    if(isset($pageConfig['hideInactiveServicesStatus']) && is_array($pageConfig['hideInactiveServicesStatus'])) {
        $hostings = \RSThemes\Models\Hostings::where("userid", \Auth::client()->id);
        $hostings->whereIn("domainstatus", $pageConfig['hideInactiveServicesStatus']);
        return ["hiddenInactiveAmount"=>$hostings->count()];
    }
});

/*
 * **************************************************************
    29. Custom Language List
 * **************************************************************
*/

add_hook('ClientAreaPage', 2, function($vars) {
    if (isset($vars['locales']) && is_array($vars['locales'])){
        $customLanguageListEnabled = \RSThemes\Models\Settings::where('setting', 'custom_language_list')->first();
        if (isset($customLanguageListEnabled) && $customLanguageListEnabled){
            $customLanguageListEnabledValue = $customLanguageListEnabled->value;
        }
        if ($customLanguageListEnabledValue == "enabled"){
            $customAvailableLanguages = \RSThemes\Models\Settings::where('setting', 'custom_available_languages')->first();
            if (isset($customAvailableLanguages) && $customAvailableLanguages){
                $customAvailableLanguagesValue = $customAvailableLanguages->value;
                $languageList = json_decode($customAvailableLanguagesValue);
                $mylocal = $vars['locales'];
                if (!in_array('all', $languageList)) {
                    foreach ($mylocal as $key => $value) {
                        if (!in_array($value["language"], $languageList)) {
                            unset($mylocal[$key]);
                        }
                    }
                    return [
                        "locales" => $mylocal
                    ];
                }
            }
        }
    }   
});

/*
 * **************************************************************
    30. Domain Revewals - Renewals In Cart Counter
 * **************************************************************
*/

add_hook('ClientAreaPage', 2, function($vars) {
    if ($vars['templatefile'] == "domain-renewals"){
        $renewalsInCart = 0;
        if (isset($_SESSION['cart']['renewalsByType']['domains']) && is_array($_SESSION['cart']['renewalsByType']['domains'])){
            $renewalsInCart = count($_SESSION['cart']['renewalsByType']['domains']);
        }
        return [
            'renewalsInCart' => $renewalsInCart
        ];
    }
});