<?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
   31. Promotion Code Applied to Cart
   32. Show Dedicated IP on Services List
   33. Open Ticket - Related Services - New Layout
   34. Fetch graphics into pages
   35. Checkout Promocode - Ajax Requests
   36. Domain renewals
 * ******************************************
 */

/*
 * ******************************************
   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;

    $displayModeDefault = \RSThemes\Models\Settings::where('setting', 'display_mode_default')->first();
    if ($displayModeDefault) {
        $displayModeDefaultValue = $displayModeDefault->value;
    }
    $darkModeEnabledValue = false; //default value
    if ($displayModeDefaultValue && $displayModeDefaultValue == 'dark') {
        $darkModeEnabledValue = true;
    }

    if ($displayModeSwitcherEnabled) {
        if (isset($_COOKIE['lagom_client_theme_dark_mode'])) { //get cookie value
            $darkModeEnabledValue = filter_var($_COOKIE['lagom_client_theme_dark_mode'] ?? 'false', FILTER_VALIDATE_BOOLEAN);
        }
    }
    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;

            // Get base product price without config options
            $baseProductPrice = [];
            $currencyId = $currency['id'] ?? getCurrency()['id'];
            $productPricing = Capsule::table('tblpricing')
                ->where('type', 'product')
                ->where('relid', $product->id)
                ->where('currency', $currencyId)
                ->first();

            if ($productPricing) {
                $cycleMap = [
                    'monthly' => 'monthly',
                    'quarterly' => 'quarterly',
                    'semiannually' => 'semiannually',
                    'semiannual' => 'semiannually',
                    'annually' => 'annually',
                    'annual' => 'annually',
                    'biennially' => 'biennially',
                    'biennial' => 'biennially',
                    'triennially' => 'triennially',
                    'triennial' => 'triennially'
                ];
                $allCycles = ['monthly', 'quarterly', 'semiannually', 'annually', 'biennially', 'triennially'];
                foreach ($allCycles as $cycleName) {
                    $dbCycle = $cycleMap[$cycleName] ?? $cycleName;
                    $baseProductPrice[$cycleName] = isset($productPricing->{$dbCycle}) ? (float) $productPricing->{$dbCycle} : 0;
                    if ($baseProductPrice[$cycleName] < 0) {
                        $baseProductPrice[$cycleName] = 0; // -1 means not available
                    }
                }
            }

            // Get total config options price for each cycle (one query per product)
            $configOptionsTotal = [];
            $currentCycle = $p['billingcycle'] ?? 'monthly'; // Current selected product cycle

            // Get selected config options from cart for current cycle
            $selectedConfigOptions = [];
            // Check in $vars['products'] (may be in configoptions)
            if (isset($vars['products'][$i]['configoptions']) && is_array($vars['products'][$i]['configoptions'])) {
                foreach ($vars['products'][$i]['configoptions'] as $configOption) {
                    $configId = isset($configOption['id']) ? $configOption['id'] : (isset($configOption['configid']) ? $configOption['configid'] : null);
                    if ($configId) {
                        if (isset($configOption['optionid'])) {
                            $selectedConfigOptions[$configId] = $configOption['optionid']; // configid => optionid (sub-option id)
                        } elseif (isset($configOption['selectedvalue'])) {
                            $selectedConfigOptions[$configId] = $configOption['selectedvalue'];
                        } elseif (isset($configOption['qty'])) {
                            // For quantity
                            $selectedConfigOptions[$configId] = [
                                'optionid' => $configOption['optionid'] ?? null,
                                'qty' => $configOption['qty']
                            ];
                        }
                    }
                }
            }
            // Also check in $_SESSION['cart'] as fallback
            if (empty($selectedConfigOptions) && isset($_SESSION['cart']['products'][$i]['configoptions']) && is_array($_SESSION['cart']['products'][$i]['configoptions'])) {
                foreach ($_SESSION['cart']['products'][$i]['configoptions'] as $configId => $configValue) {
                    if (is_numeric($configValue)) {
                        $selectedConfigOptions[$configId] = $configValue; // configid => optionid
                    } elseif (is_array($configValue) && isset($configValue['optionid'])) {
                        $selectedConfigOptions[$configId] = $configValue['optionid'];
                    }
                }
            }

            $productConfigLinks = Capsule::table('tblproductconfiglinks')->where('pid', $product->id)->pluck('gid')->toArray();
            if (!empty($productConfigLinks)) {
                $configOptions = Capsule::table('tblproductconfigoptions')
                    ->whereIn('gid', $productConfigLinks)
                    ->where('hidden', 0)
                    ->get(['id', 'optiontype', 'qtyminimum']);

                $configOptionIds = $configOptions->pluck('id')->toArray();
                if (!empty($configOptionIds)) {
                    $configSubOptions = Capsule::table('tblproductconfigoptionssub')
                        ->whereIn('configid', $configOptionIds)
                        ->where('hidden', 0)
                        ->get(['id', 'configid']);

                    $subOptionIds = $configSubOptions->pluck('id')->toArray();
                    if (!empty($subOptionIds)) {
                        $pricingData = Capsule::table('tblpricing')
                            ->where('type', 'configoptions')
                            ->whereIn('relid', $subOptionIds)
                            ->where('currency', $currencyId)
                            ->get();

                        // Map pricing to sub-options (relid in tblpricing is sub-option ID)
                        $subOptionPricing = [];
                        foreach ($pricingData as $price) {
                            $subOptionPricing[$price->relid] = $price;
                        }

                        // Calculate sum for each cycle
                        // Map cycle names from cycle() method to database column names
                        $cycleMap = [
                            'monthly' => 'monthly',
                            'quarterly' => 'quarterly',
                            'semiannually' => 'semiannually',
                            'semiannual' => 'semiannually',
                            'annually' => 'annually',
                            'annual' => 'annually',
                            'biennially' => 'biennially',
                            'biennial' => 'biennially',
                            'triennially' => 'triennially',
                            'triennial' => 'triennially'
                        ];

                        // Initialize all possible cycles
                        $allCycles = ['monthly', 'quarterly', 'semiannually', 'annually', 'biennially', 'triennially'];
                        foreach ($allCycles as $cycleName) {
                            $configOptionsTotal[$cycleName] = 0;
                        }

                        foreach ($configOptions as $configOption) {
                            $configId = $configOption->id;
                            $optionType = $configOption->optiontype;

                            // Check if there is a selected value for this config option
                            $selectedOptionId = null;
                            $selectedQty = null;

                            if (isset($selectedConfigOptions[$configId])) {
                                if (is_array($selectedConfigOptions[$configId])) {
                                    $selectedOptionId = $selectedConfigOptions[$configId]['optionid'] ?? null;
                                    $selectedQty = $selectedConfigOptions[$configId]['qty'] ?? null;
                                } else {
                                    $selectedOptionId = $selectedConfigOptions[$configId];
                                }
                            }

                            if ($optionType == 1 || $optionType == 2) {
                                // For dropdown/radio - use selected option if available, otherwise cheapest
                                if ($selectedOptionId && isset($subOptionPricing[$selectedOptionId])) {
                                    // Use selected option for all cycles
                                    $price = $subOptionPricing[$selectedOptionId];
                                    foreach ($allCycles as $cycleName) {
                                        $dbCycle = $cycleMap[$cycleName] ?? $cycleName;
                                        $cyclePrice = isset($price->{$dbCycle}) ? (float) $price->{$dbCycle} : 0;
                                        if ($cyclePrice >= 0) {
                                            $configOptionsTotal[$cycleName] += $cyclePrice;
                                        }
                                    }
                                } else {
                                    // If no selected option, use cheapest
                                    $configSubOptionsForThis = array_filter($configSubOptions->toArray(), function ($sub) use ($configId) {
                                        return $sub->configid == $configId;
                                    });
                                    foreach ($allCycles as $cycleName) {
                                        $dbCycle = $cycleMap[$cycleName] ?? $cycleName;
                                        $cheapest = PHP_INT_MAX;
                                        foreach ($configSubOptionsForThis as $subOption) {
                                            if (isset($subOptionPricing[$subOption->id])) {
                                                $price = $subOptionPricing[$subOption->id];
                                                $cyclePrice = isset($price->{$dbCycle}) ? (float) $price->{$dbCycle} : 0;
                                                if ($cyclePrice >= 0 && $cyclePrice < $cheapest) {
                                                    $cheapest = $cyclePrice;
                                                }
                                            }
                                        }
                                        if ($cheapest != PHP_INT_MAX) {
                                            $configOptionsTotal[$cycleName] += $cheapest;
                                        }
                                    }
                                }
                            } elseif ($optionType == 4) {
                                // For quantity - use selected option with qty if available
                                $qtyToUse = $selectedQty ?? $configOption->qtyminimum ?? 0;
                                if ($qtyToUse > 0) {
                                    if ($selectedOptionId && isset($subOptionPricing[$selectedOptionId])) {
                                        // Use selected option
                                        $price = $subOptionPricing[$selectedOptionId];
                                        foreach ($allCycles as $cycleName) {
                                            $dbCycle = $cycleMap[$cycleName] ?? $cycleName;
                                            $cyclePrice = isset($price->{$dbCycle}) ? (float) $price->{$dbCycle} : 0;
                                            if ($cyclePrice >= 0) {
                                                $configOptionsTotal[$cycleName] += $cyclePrice * $qtyToUse;
                                            }
                                        }
                                    } else {
                                        // If no selected option, use first available
                                        $configSubOptionsForThis = array_filter($configSubOptions->toArray(), function ($sub) use ($configId) {
                                            return $sub->configid == $configId;
                                        });
                                        if (!empty($configSubOptionsForThis)) {
                                            $firstSubOption = reset($configSubOptionsForThis);
                                            if (isset($subOptionPricing[$firstSubOption->id])) {
                                                $price = $subOptionPricing[$firstSubOption->id];
                                                foreach ($allCycles as $cycleName) {
                                                    $dbCycle = $cycleMap[$cycleName] ?? $cycleName;
                                                    $cyclePrice = isset($price->{$dbCycle}) ? (float) $price->{$dbCycle} : 0;
                                                    if ($cyclePrice >= 0) {
                                                        $configOptionsTotal[$cycleName] += $cyclePrice * $qtyToUse;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            try {
                foreach ($cycles[$i] as $key => $cycle) {
                    $active = false;
                    if ($p['billingcycle'] == $cycle->cycle()) {
                        $active = true;
                    }

                    $cycleName = $cycle->cycle();
                    // Map cycle names (may return different variants)
                    $cycleNameMap = [
                        'monthly' => 'monthly',
                        'quarterly' => 'quarterly',
                        'semiannually' => 'semiannually',
                        'semiannual' => 'semiannually',
                        'annually' => 'annually',
                        'annual' => 'annually',
                        'biennially' => 'biennially',
                        'biennial' => 'biennially',
                        'triennially' => 'triennially',
                        'triennial' => 'triennially'
                    ];
                    $normalizedCycleName = $cycleNameMap[$cycleName] ?? $cycleName;
                    $pricingCO = isset($configOptionsTotal[$normalizedCycleName]) ? $configOptionsTotal[$normalizedCycleName] : 0;

                    // Get base product price for this cycle
                    $basePrice = isset($baseProductPrice[$normalizedCycleName]) ? $baseProductPrice[$normalizedCycleName] : 0;

                    // Calculate sum: base price + config options
                    $totalPrice = $basePrice + $pricingCO;

                    // Format config options price
                    $pricingCOFormatted = '';
                    if ($pricingCO > 0) {
                        $pricingCOFormatted = new \WHMCS\View\Formatter\Price($pricingCO, $cycle->price()->getCurrency());
                        $pricingCOFormatted = $pricingCOFormatted->format();
                    }

                    // Format total sum
                    $totalPriceFormatted = '';
                    if ($totalPrice > 0) {
                        $totalPriceFormattedObj = new \WHMCS\View\Formatter\Price($totalPrice, $cycle->price()->getCurrency());
                        $totalPriceFormatted = $totalPriceFormattedObj->format();
                    }

                    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],
                            'active' => $active,
                            'toFullStringCalculated' => $currency['prefix'] . $product_onetime . $currency['suffix'] . '/' . $exploded[1],
                            'pricingCO' => $pricingCOFormatted,
                            'basePrice' => $basePrice,
                            'totalPrice' => $totalPrice,
                            'totalPriceFormatted' => $totalPriceFormatted . '/' . $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(),
                            'active' => $active,
                            //'toFullStringFormatted' => $cycle->price()->format(NULL, $currency) . '/' . $exploded[1],
                            'toFullStringCalculated' => $price->format() . '/' . $exploded[1],
                            'pricingCO' => $pricingCOFormatted,
                            'basePrice' => $basePrice,
                            'totalPrice' => $totalPrice,
                            'totalPriceFormatted' => $totalPriceFormatted . '/' . $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" || $vars['templatefile'] == "supportticketslist") {
        if (isset($_COOKIE['hideInactiveSercices']) && $_COOKIE['hideInactiveSercices'] == "true") {
            $inactiveServices = true;
        } else {
            $inactiveServices = false;
        }

        if (isset($_COOKIE['hideInactiveDomains']) && $_COOKIE['hideInactiveDomains'] == "true") {
            $inactiveDomains = true;
        } else {
            $inactiveDomains = false;
        }

        if (isset($_COOKIE['hideInactiveTickets']) && $_COOKIE['hideInactiveTickets'] == "true") {
            $inactiveTickets = true;
        } else {
            $inactiveTickets = false;
        }

        $hideInacviveServices = [
            "inactiveServices" => $inactiveServices,
            "inactiveDomains" => $inactiveDomains,
            "inactiveTickets" => $inactiveTickets
        ];

        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 ($product['bid']) {
                        $description = Capsule::table("tblbundles")->where("id", $product['bid'])->value('description');
                        $vars['products'][$key]['clearDescription'] = $description;
                    } else {
                        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', 999999999999, 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
        ];
    }
});

/*
 * **************************************************************
    31. Promotion Code Applied to Cart
 * **************************************************************
*/

add_hook('ClientAreaPage', 2, function ($vars) {
    if ($vars['inShoppingCart'] && isset($_SESSION['cart']['promo']) && $_SESSION['cart']['promo']) {
        return [
            'hasPromoInCart' => $_SESSION['cart']['promo']
        ];
    }
});

/*
 * **************************************************************
    32. Show Dedicated IP on Services List
 * **************************************************************
*/

add_hook('ClientAreaPageProductsServices', 2, function ($vars) {
    $client = Menu::context('client');
    $services = $vars['services'];
    foreach ($services as $key => $service) {
        $dedicatedip = Capsule::table('tblhosting')->where('userid', $client->id)->where('id', $service['id'])->value('dedicatedip');
        if ($dedicatedip) {
            $services[$key]['dedicatedip'] = $dedicatedip;
        }
    }
    return array("services" => $services);
});

/*
 * **************************************************************
    33. Open Ticket - Related Services - New Layout
 * **************************************************************
*/

add_hook('ClientAreaPageSubmitTicket', 2, 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() && method_exists($page->getConfiguredOption(), 'getCustomVariables') && isset($page->getConfiguredOption()->getCustomVariables()['page_layout']) && $page->getConfiguredOption()->getCustomVariables()['page_layout'] == 'new') {
                foreach ($vars['relatedservices'] as $key => $relatedService) {
                    if (str_contains($relatedService['id'], "S")) {
                        $currentId = str_replace('S', '', $relatedService['id']);
                        $record = Capsule::table('tblhosting')->where('id', $currentId)->select('domain', 'packageid', 'domainstatus')->first();
                        $product = WHMCS\Product\Product::where('id', $record->packageid)->first();
                        $group = ProductGroup::where('id', $product->gid)->first();
                        $formatName = $product->name;
                        if ($record && isset($record->domain)) {
                            $formatName .= ' <span>(' . $record->domain . ')</span>';
                        }
                        $vars['relatedservices'][$key]['name'] = $formatName;
                        $vars['relatedservices'][$key]['groupName'] = $group->name;
                        $vars['relatedservices'][$key]['rawStatus'] = $record->domainstatus;
                    }
                    if (str_contains($relatedService['id'], "D")) {
                        $label = Lang::trans("clientareahostingdomain");
                        $vars['relatedservices'][$key]['name'] = str_replace($label, '<b class="font-weight-medium">' . $label . '</b>', $relatedService['name']);
                        $currentId = str_replace('D', '', $relatedService['id']);
                        $domainRecord = Capsule::table('tbldomains')->where('id', $currentId)->select('status')->first();
                        if ($domainRecord && isset($domainRecord->status)) {
                            $vars['relatedservices'][$key]['rawStatus'] = $domainRecord->status;
                        }
                    }
                }
                // Sort: products Active, domains Active, then other products, then other domains
                if (isset($vars['relatedservices']) && is_array($vars['relatedservices'])) {
                    usort($vars['relatedservices'], function ($a, $b) {
                        $getWeight = function ($item) {
                            $id = isset($item['id']) ? (string) $item['id'] : '';
                            $isService = strpos($id, 'S') === 0;
                            $isDomain = strpos($id, 'D') === 0;
                            $status = strtolower($item['rawStatus'] ?? '');
                            $isActive = ($status === 'active');
                            if ($isService && $isActive)
                                return 0;
                            if ($isDomain && $isActive)
                                return 1;
                            if ($isService)
                                return 2;
                            if ($isDomain)
                                return 3;
                            return 4; // fallback
                        };
                        $wa = $getWeight($a);
                        $wb = $getWeight($b);
                        if ($wa === $wb) {
                            $an = isset($a['name']) ? strip_tags($a['name']) : '';
                            $bn = isset($b['name']) ? strip_tags($b['name']) : '';
                            return strcasecmp($an, $bn);
                        }
                        return $wa <=> $wb;
                    });
                }
                return $vars;
            }
        }
    }
});

/*
 * **************************************************************
    34. Fetch graphics into pages
 * **************************************************************
*/

add_hook('ClientAreaPage', 1, function ($vars) {
    $template = $vars['templatefile'] ?? '';
    $action = $_GET['a'] ?? '';

    $isCartNonDomain = $template === 'viewcart' && !in_array($action, ['add', 'adddomain', 'domainoptions']);
    $isAllowed = in_array($template, [
        'clientareaproducts',
        'domain-renewals',
        'clientareadomaindetails',
        'clientareadomains',
        'supportticketslist',
        'products',
        'addons',
        'clientareaproductdetails',
        'submitticketstepone',
        'supportticketsubmit-steptwo',
        'supportticketsubmit-stepone',
        'homepage',
        'configureproduct',
        'configureproductdomain',
        'clientareahome',
        'configuredomains',
        'clientareacancelrequest'
    ]);
    if ($isAllowed || $isCartNonDomain) {

        $displayProductGraphics = \RSThemes\Models\Settings::where('setting', 'display_product_graphics')->first();
        $displayProductGraphicsValue = $displayProductGraphics ? $displayProductGraphics->value : 'enabled';

        if ($displayProductGraphicsValue !== 'disabled') {
            return [
                'graphics' => \RSThemes\Models\Graphics::getGraphics(null, null, true),
            ];
        } else {
            return [
                'graphics' => [],
            ];
        }
    }

    return [];
});

add_hook('ClientAreaPageProductsServices', 1, function ($vars) {
    if (isset($vars['client']) && is_object($vars['client']) && $vars['client']->id)
        $productServicesID = [];
    $products = WHMCS\Service\Service::where('userid', $vars['client']->id)->get();
    foreach ($products as $product) {
        $productServicesID[$product->id] = $product->packageid;
    }
    return ['productServicesID' => $productServicesID];
});

add_hook('ClientAreaPageSupportTickets', 1, function ($vars) {
    $tickets = $vars['tickets'];
    if (isset($tickets) && is_array($tickets) && !empty($tickets)) {
        $ticketIds = array_column($tickets, 'id');
        $deptIds = Capsule::table('tbltickets')
            ->whereIn('id', $ticketIds)
            ->pluck('did', 'id')
            ->toArray();
        return ['ticketsDepartmentsID' => $deptIds];
    }
    return [];
});

add_hook('ClientAreaPage', 3, function ($vars) {
    if ($vars['templatefile'] == "clientareahome") {
        $userId = isset($vars['uid']) ? $vars['uid'] : $_SESSION['uid'];
        $map = [];

        if ($userId) {
            $services = Capsule::table('tblhosting')
                ->where('userid', $userId)
                ->get(['id', 'packageid']);

            foreach ($services as $service) {
                $map[$service->id] = $service->packageid;
            }
        }
        $vars['serviceProductMap'] = $map;


    }
    if ($vars['templatefile'] == "configuredomains") {
        if (isset($_SESSION['cart']['domains']) && is_array($_SESSION['cart']['domains']) && isset($vars['domains']) && is_array($vars['domains'])) {
            $sessionDomainsTypes = [];
            foreach ($_SESSION['cart']['domains'] as $sdomain) {
                if (isset($sdomain['domain']) && isset($sdomain['type'])) {
                    $sessionDomainsTypes[$sdomain['domain']] = $sdomain['type'];
                }
            }
            foreach ($vars['domains'] as $key => $domain) {
                if (isset($domain['domain']) && isset($sessionDomainsTypes[$domain['domain']])) {
                    $vars['domains'][$key]['type'] = $sessionDomainsTypes[$domain['domain']];
                }
            }
        }
    }

    if ($vars['templatefile'] == "configureproduct") {
        $pid = $vars['productinfo']['pid'];
        $addons = Capsule::table('tbladdons')
            ->select('id')
            ->whereRaw("FIND_IN_SET(?, packages)", [$pid])
            ->pluck('id')
            ->toArray();

        $vars['assignedAddons'] = $addons;
    }

    if ($vars['templatefile'] == "viewcart") {
        // Get domain addon prices (dnsmanagement, emailforwarding, idprotection)
        if (isset($vars['domains']) && is_array($vars['domains'])) {
            $currency = getCurrency(WHMCS\Session::get("uid"), WHMCS\Session::get("currency"));
            $currencyId = $currency['id'] ?? getCurrency()['id'];
            $addonPricing = Capsule::table('tblpricing')
                ->where('type', 'domainaddons')
                ->where('relid', 0)
                ->where('currency', $currencyId)
                ->first();

            if ($addonPricing) {
                // Map addon prices: msetupfee = DNS Management, qsetupfee = Email Forwarding, ssetupfee = ID Protection
                // These are base prices per year
                $dnsPriceBase = isset($addonPricing->msetupfee) ? (float) $addonPricing->msetupfee : 0;
                $emailPriceBase = isset($addonPricing->qsetupfee) ? (float) $addonPricing->qsetupfee : 0;
                $idProtectionPriceBase = isset($addonPricing->ssetupfee) ? (float) $addonPricing->ssetupfee : 0;

                // Add base prices and calculated prices to each domain
                foreach ($vars['domains'] as $key => $domain) {
                    // Get registration period (default to 1 year if not set)
                    $regPeriod = isset($domain['regperiod']) ? (int) $domain['regperiod'] : 1;

                    // Calculate prices for current registration period
                    $dnsPrice = $dnsPriceBase * $regPeriod;
                    $emailPrice = $emailPriceBase * $regPeriod;
                    $idProtectionPrice = $idProtectionPriceBase * $regPeriod;

                    // Format calculated prices
                    $dnsPriceFormatted = '-';
                    $emailPriceFormatted = '-';
                    $idProtectionPriceFormatted = '-';

                    if ($dnsPrice > 0) {
                        $dnsPriceObj = new \WHMCS\View\Formatter\Price($dnsPrice, $currency);
                        $dnsPriceFormatted = $dnsPriceObj->format();
                    }
                    if ($emailPrice > 0) {
                        $emailPriceObj = new \WHMCS\View\Formatter\Price($emailPrice, $currency);
                        $emailPriceFormatted = $emailPriceObj->format();
                    }
                    if ($idProtectionPrice > 0) {
                        $idProtectionPriceObj = new \WHMCS\View\Formatter\Price($idProtectionPrice, $currency);
                        $idProtectionPriceFormatted = $idProtectionPriceObj->format();
                    }

                    // Add base prices (per year) for JavaScript calculations
                    if (isset($domain['dnsmanagement']) && $domain['dnsmanagement']) {
                        $vars['domains'][$key]['dnsmanagementPrice'] = $dnsPriceFormatted;
                        $vars['domains'][$key]['dnsmanagementPriceBase'] = $dnsPriceBase;
                    }
                    if (isset($domain['emailforwarding']) && $domain['emailforwarding']) {
                        $vars['domains'][$key]['emailforwardingPrice'] = $emailPriceFormatted;
                        $vars['domains'][$key]['emailforwardingPriceBase'] = $emailPriceBase;
                    }
                    if (isset($domain['idprotection']) && $domain['idprotection']) {
                        $vars['domains'][$key]['idprotectionPrice'] = $idProtectionPriceFormatted;
                        $vars['domains'][$key]['idprotectionPriceBase'] = $idProtectionPriceBase;
                    }
                }
            }
        }
    }

    if ($vars['templatefile'] == "clientareahome" || $vars['templatefile'] == "configuredomains" || $vars['templatefile'] == "configureproduct" || $vars['templatefile'] == "viewcart") {
        return $vars;
    }

});

add_hook('ClientAreaPageProductDetails', 3, function ($vars) {
    if ($vars['addons'] && !empty($vars['addons'])) {
        foreach ($vars['addons'] as $key => $addon) {
            if (isset($addon['id'])) {
                $addonId = Capsule::table('tblhostingaddons')
                    ->where('id', $addon['id'])
                    ->value('addonid');

                if ($addonId) {
                    $vars['addons'][$key]['addonid'] = $addonId;
                }
            }
        }
        return $vars;
    }
});

add_hook('ClientAreaPage', 2, function ($vars) {
    $template = $vars['templatefile'] ?? '';

    // Zamień 'TWOJA-NAZWA-STRONY' na rzeczywistą nazwę
    if ($template === 'clientareacancelrequest') {
        $productServicesID = [];

        // Pobierz ID zalogowanego użytkownika
        $userId = isset($vars['client']) && is_object($vars['client'])
            ? $vars['client']->id
            : ($_SESSION['uid'] ?? null);

        if ($userId) {
            $products = WHMCS\Service\Service:: where('userid', $userId)->get();
            foreach ($products as $product) {
                $productServicesID[$product->id] = $product->packageid;
            }
        }

        return ['productServicesID' => $productServicesID];
    }

    return [];
});

/*
 * **************************************************************
    35. Checkout Promocode - Ajax Requests
 * **************************************************************
*/

add_hook('ClientAreaPage', 1, function ($vars) {
    if ($vars['templatefile'] == "viewcart") {
        $currency = getCurrency(WHMCS\Session::get("uid"), WHMCS\Session::get("currency"));
        if (App::getFromRequest("addPromoCode") && App::getFromRequest("checkcode")) {
            $promocode = App::getFromRequest("checkcode");
            $promomessage = SetPromoCode($promocode);

            $payload = calcCartTotals(null, false, $currency);

            $promotype = $payload["promotype"];
            $promovalue = $payload["promovalue"];
            $promorecurring = $payload["promorecurring"];

            $promodescription = $promotype == "Percentage" ? $promovalue . "%" : $promovalue;
            if ($promotype == "Price Override") {
                $promodescription .= " " . Lang::trans("orderpromopriceoverride");
            } elseif ($promotype == "Free Setup") {
                $promodescription = Lang::trans("orderpromofreesetup");
            }
            $promoRecurFor = (int) WHMCS\Database\Capsule::table("tblpromotions")->where("code", $smartyvalues["promotioncode"])->pluck("recurfor")->first();
            if ($promoRecurFor == 0) {
                $promodescription .= " " . $promorecurring . " " . Lang::trans("orderdiscount");
            } else {
                $forCycles = Lang::trans("orderForm.promoCycles", [":cycles" => $promoRecurFor]);
                $promodescription .= " " . $promorecurring . " " . Lang::trans("orderdiscount") . " </span><span class='font-weight-normal'> " . $forCycles . '.';
                unset($forCyles);
            }
            $payload["promotiondescription"] = $promodescription;
            $payload['promomessage'] = $promomessage;
            $payload['promotionCode'] = $promocode;
            $response = new WHMCS\Http\JsonResponse();
            $response->setData($payload);

            $response->send();
            WHMCS\Terminus::getInstance()->doExit();
        }

        if (App::getFromRequest("removePromoCode")) {
            $_SESSION["cart"]["promo"] = "";
            $payload = calcCartTotals(null, false, $currency);
            $response = new WHMCS\Http\JsonResponse();
            $response->setData($payload);

            $response->send();
            WHMCS\Terminus::getInstance()->doExit();
        }
    }
});

/*
 * **************************************************************
    36. Domain renewals
 * **************************************************************
*/


add_hook('ClientAreaPage', 1, function ($vars) {

    if (isset($_POST['domids']) && $_POST['domids']) {
        return [
            'domids' => $_POST['domids']
        ];
    }

});
