<?php

/*
 * ***********************************************
   RS Studio Template Hook
   1. Namespaces
   2. Sidebar Configuration
   3. Request Cancellation Button On Free Product
   4. View Ticket - Hide Ticket Priority
   5. Account Sidebar Box Display
   6. View Ticket - Ticket Sidebars - New Layout
   7. Open Ticket - Ticket Sidebars - New Layout
   8. Add Funds
   9. Affiliates
   10. Invoices
   11. Server Status
   12. Mass Payment
   13. Client Area Domains Sidebar Box Display
 * ***********************************************
 */

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

use RSThemes\Models\Settings;
use WHMCS\Database\Capsule;
use RSThemes\Template\Template;
use RSThemes\Template\Page;
use WHMCS\User\Client;
use RSThemes\Helpers\Lang as RsLang;
use RSThemes\Helpers\AddonHelper;
use \RSThemes\Template\Style;

/*
 * ******************************************
   2. Sidebar Configuration
 * ******************************************
 */

add_hook('ClientAreaSidebars', 2, function($vars) {
    $primarySidebar = Menu::primarySidebar();
    $secondarySidebar = Menu::secondarySidebar();

    //dashboard
    if ($primarySidebar && !is_null($primarySidebar->getChild('Client Details'))) {
        $primarySidebar->getChild('Client Details')->setClass('panel-client-details');
        
        //show client id in Client Details Panel
        $client = \Menu::context("client");
        if (!is_null($client)) {
            if (Settings::where('setting', 'show_client_id')->first()->value && Settings::where('setting', 'show_client_id')->first()->value == "displayed"){
                if (Capsule::schema()->hasTable('ResellersCenter_ResellersClients')){
                    $resellersCheck = Capsule::table('ResellersCenter_ResellersClients')
                    ->where('client_id', $client->id)
                    ->value('id');
                }
                if (isset($resellersCheck) && $resellersCheck){
                    $clientId = $resellersCheck;
                }
                else{
                    $clientId = $client->id;
                }
                
                $show_id = '#'.$clientId.' ';
                $details = "";
                if ($client->companyName) {
                    $details .= "<strong>". $show_id . $client->companyName . "</strong><br><em>" . $client->fullName . "</em><br>";
                } else {
                    $details .= "<strong>". $show_id . $client->fullName . "</strong><br>";
                }
                $details .= $client->address1 . "<br>";
                if ($client->address2) {
                    $details .= $client->address2 . "<br>";
                }
                $address = [];
                if ($client->city) {
                    $address[] = $client->city;
                }
                if ($client->state) {
                    $address[] = $client->state;
                }
                if ($client->postcode) {
                    $address[] = $client->postcode;
                }
                $details .= implode(", ", $address) . "<br>" . $client->countryName;
                if ($client->taxId) {
                    $details .= "<br>" . $client->taxId;
                }
                $primarySidebar->getChild('Client Details')->setBodyHtml($details);
            }
        }
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Client Contacts'))) {
        $secondarySidebar->getChild('Client Contacts')->setClass('panel-client-contacts');
        $secondarySidebar->getChild('Client Contacts')->addChild('more')
        ->setUri('clientarea.php?action=contacts')
        ->setLabel(Lang::trans('more'))
        ->setClass('contact-more')
        ->setIcon('fa-ticket ls ls-more')
        ->setOrder(1000);
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Client Shortcuts'))) {
        $shortcutsSidebar = $secondarySidebar->getChild('Client Shortcuts');
        if (!is_null($shortcutsSidebar->getChild('Order New Services'))){
            $shortcutsSidebar->getChild('Order New Services')->setIcon('fa-ticket ls ls-basket');
        }
        if (!is_null($shortcutsSidebar->getChild('Register New Domain'))){
            $shortcutsSidebar->getChild('Register New Domain')->setIcon('fa-ticket ls ls-dns');
        }
        if (!is_null($shortcutsSidebar->getChild('Logout'))){
            $shortcutsSidebar->getChild('Logout')->setIcon('fa-ticket ls ls-reply');
        }
    }
    //my account
    if ($primarySidebar && !is_null($primarySidebar->getChild('My Account'))) {
        $accountSidebar = $primarySidebar->getChild('My Account');
        if (!is_null($accountSidebar->getChild('My Details'))){
            $accountSidebar->getChild('My Details')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($accountSidebar->getChild('Billing Information'))){
            $accountSidebar->removeChild('Billing Information');
        }
        if (!is_null($accountSidebar->getChild('Payment Methods'))){
            $accountSidebar->getChild('Payment Methods')->setIcon('fa-ticket ls ls-credit-card');
        }
        if (!is_null($accountSidebar->getChild('Contacts/Sub-Accounts'))){
            $accountSidebar->getChild('Contacts/Sub-Accounts')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($accountSidebar->getChild('Change Password'))){
            $accountSidebar->getChild('Change Password')->setIcon('fa-ticket ls ls-padlock');
        }
        if (!is_null($accountSidebar->getChild('Security Settings'))){
            $accountSidebar->getChild('Security Settings')->setIcon('fa-ticket ls ls-shield');
        }
        if (!is_null($accountSidebar->getChild('Email History'))){
            $accountSidebar->getChild('Email History')->setIcon('fa-ticket ls ls-envelope');
        }
    }
    if ($primarySidebar && !is_null($primarySidebar->getChild('My Account')) && $secondarySidebar && !is_null($secondarySidebar->getChild('Billing'))) {
        $primarySidebar->removeChild('My Account');
    }

    //account
    if ($primarySidebar && !is_null($primarySidebar->getChild('Account'))) {
        $accountSidebar = $primarySidebar->getChild('Account');
        if (!is_null($accountSidebar->getChild('My Details'))){
            $accountSidebar->getChild('My Details')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($accountSidebar->getChild('Billing Information'))){
            $accountSidebar->removeChild('Billing Information');
        }
        if (!is_null($accountSidebar->getChild('Payment Methods'))){
            $accountSidebar->getChild('Payment Methods')->setIcon('fa-ticket ls ls-credit-card');
        }
        if (!is_null($accountSidebar->getChild('Contacts/Sub-Accounts'))){
            $accountSidebar->getChild('Contacts/Sub-Accounts')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($accountSidebar->getChild('Change Password'))){
            $accountSidebar->getChild('Change Password')->setIcon('fa-ticket ls ls-padlock');
        }
        if (!is_null($accountSidebar->getChild('Security Settings'))){
            $accountSidebar->getChild('Security Settings')->setIcon('fa-ticket ls ls-shield');
        }
        if (!is_null($accountSidebar->getChild('Account Security'))){
            $accountSidebar->getChild('Account Security')->setIcon('fa-ticket ls ls-shield');
        }
        if (!is_null($accountSidebar->getChild('Email History'))){
            $accountSidebar->getChild('Email History')->setIcon('fa-ticket ls ls-envelope');
        }
        if (!is_null($accountSidebar->getChild('User Management'))){
            $accountSidebar->getChild('User Management')->setIcon('fa-ticket ls ls-configure');
        }
    }
    if ($primarySidebar && !is_null($primarySidebar->getChild('Account')) && $secondarySidebar && !is_null($secondarySidebar->getChild('Billing'))) {
        $primarySidebar->removeChild('Account');
    }

    // your profile
    if ($primarySidebar && !is_null($primarySidebar->getChild('Profile'))) {
        $profileSidebar = $primarySidebar->getChild('Profile');
        if (!is_null($profileSidebar->getChild('Your Profile'))){
            $profileSidebar->getChild('Your Profile')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($profileSidebar->getChild('Change Password'))){
            $profileSidebar->getChild('Change Password')->setIcon('fa-ticket ls ls-padlock');
        }
        if (!is_null($profileSidebar->getChild('User Security'))){
            $profileSidebar->getChild('User Security')->setIcon('fa-ticket ls ls-shield');
        }
        if (!is_null($profileSidebar->getChild('Logout'))){
            $profileSidebar->getChild('Logout')->setIcon('fa-ticket ls ls-sign-out');
        }
        if (!is_null($profileSidebar->getChild('Switch Account'))){
            $profileSidebar->getChild('Switch Account')->setIcon('fa-ticket ls ls-refresh');
        }

    }

    // Support
    if ($primarySidebar && !is_null($primarySidebar->getChild('Support Knowledgebase Categories'))) {
        $primarySidebar->removeChild('Support Knowledgebase Categories');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Support Knowledgebase Tag Cloud'))) {
        $secondarySidebar->getChild('Support Knowledgebase Tag Cloud')->setClass('panel-styled-group panel-support-tags');
    }
    if ($primarySidebar && !is_null($primarySidebar->getChild('Ticket Information'))) {
        $primarySidebar->getChild('Ticket Information')->setClass('panel-styled-group panel-ticket-information');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Recent Tickets'))) {
        $secondarySidebar->getChild('Recent Tickets')->setClass('panel-styled-group');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Attachments'))) {
        $secondarySidebar->getChild('Attachments')->setClass('panel-styled-group panel-ticket-attachements');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('CC Recipients'))) {
        $secondarySidebar->getChild('CC Recipients')->setClass('panel-styled-group panel-ticket-cc');
    }
    
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Support'))) {
        $supportSidebar = $secondarySidebar->getChild('Support');
        if (!is_null($supportSidebar->getChild('Support Tickets'))){
            $supportSidebar->getChild('Support Tickets')->setIcon('fa-ticket ls ls-ticket-tag');
        }
        if (!is_null($supportSidebar->getChild('Announcements'))){
            $supportSidebar->getChild('Announcements')->setIcon('fa-ticket ls ls-text-cloud');
        }
        if (!is_null($supportSidebar->getChild('Knowledgebase'))){
            $supportSidebar->getChild('Knowledgebase')->setIcon('fa-ticket ls ls-document-info');
        }
        if (!is_null($supportSidebar->getChild('Downloads'))){
            $supportSidebar->getChild('Downloads')->setIcon('fa-ticket ls ls-download-square');
        }
        if (!is_null($supportSidebar->getChild('Network Status'))){
            $supportSidebar->getChild('Network Status')->setIcon('fa-ticket ls ls-range');
        }
        if (!is_null($supportSidebar->getChild('Open Ticket'))){
            $supportSidebar->getChild('Open Ticket')->setIcon('fa-ticket ls ls-new-window');
        }
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Popular Downloads'))) {
        $secondarySidebar->removeChild('Popular Downloads');
    }
    if ($primarySidebar && !is_null($primarySidebar->getChild('Ticket List Status Filter'))) {
        $primarySidebar->removeChild('Ticket List Status Filter');
    }

    if ($primarySidebar && !is_null($primarySidebar->getChild('Announcements Months'))) {
        $annoucementSidebar = $primarySidebar->getChild('Announcements Months');
        if (!is_null($annoucementSidebar->getChild('Older'))){
            $annoucementSidebar->getChild('Older')->setIcon('fa-ticket ls ls-hourglass');
        }
        if (!is_null($annoucementSidebar->getChild('RSS Feed'))){
            $annoucementSidebar->getChild('RSS Feed')->setIcon('fa-ticket ls ls-rss');
        }
    }
    

    // Billing
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Billing'))) {
        $billingSidebar = $secondarySidebar->getChild('Billing');
        if (!is_null($billingSidebar->getChild('Invoices'))){
            $billingSidebar->getChild('Invoices')->setIcon('fa-ticket ls ls-document');
        }
        if (!is_null($billingSidebar->getChild('Quotes'))){
            $billingSidebar->getChild('Quotes')->setIcon('fa-ticket ls ls-text-cloud');
        }
        if (!is_null($billingSidebar->getChild('Mass Payment'))){
            $billingSidebar->getChild('Mass Payment')->setIcon('fa-ticket ls ls-bank-note');
        }
        if (!is_null($billingSidebar->getChild('Manage Credit Card'))){
            $billingSidebar->getChild('Manage Credit Card')->setIcon('fa-ticket ls ls-credit-card');
        }
        if (!is_null($billingSidebar->getChild('Add Funds'))){
            $billingSidebar->getChild('Add Funds')->setIcon('fa-ticket ls ls-credit');
        }
    }
    
    if ($primarySidebar && !is_null($primarySidebar->getChild('My Quotes Status Filter'))) {
        $primarySidebar->removeChild('My Quotes Status Filter');
    }

    //my services
    if ($primarySidebar && !is_null($primarySidebar->getChild('My Services Status Filter'))) {
        $primarySidebar->removeChild('My Services Status Filter');
    }
    if ($primarySidebar && !is_null($primarySidebar->getChild('Service Details Overview'))) {
        $servicesSidebar = $primarySidebar->getChild('Service Details Overview');
        if (!is_null($servicesSidebar->getChild('Information'))){
            $servicesSidebar->getChild('Information')->setIcon('fa-ticket ls ls-dashboard');
        }
        if (!is_null($servicesSidebar->getChild('Change Password'))){
            $servicesSidebar->getChild('Change Password')->setIcon('fa-ticket ls ls-padlock');
        }
        if (!is_null($servicesSidebar->getChild('Downloads'))){
            $servicesSidebar->getChild('Downloads')->setIcon('fa-ticket ls ls-download-square');
        }
        if (!is_null($servicesSidebar->getChild('Addons'))){
            $servicesSidebar->getChild('Addons')->setIcon('fa-ticket ls ls-addon');
        }
    }
    if ($primarySidebar && !is_null($primarySidebar->getChild('Service Details Actions'))) {
        $servicesSidebar = $primarySidebar->getChild('Service Details Actions');
        if (!is_null($servicesSidebar->getChild('Login to cPanel'))){
            $servicesSidebar->getChild('Login to cPanel')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('cpanel'))){
            $servicesSidebar->getChild('cpanel')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('Manage'))){
            $servicesSidebar->getChild('Manage')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('Login to Plesk'))){
            $servicesSidebar->getChild('Login to Plesk')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('plesk'))){
            $servicesSidebar->getChild('plesk')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('Login to WHM'))){
            $servicesSidebar->getChild('Login to WHM')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('whm'))){
            $servicesSidebar->getChild('whm')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('Login to Webmail'))){
            $servicesSidebar->getChild('Login to Webmail')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('webmail'))){
            $servicesSidebar->getChild('webmail')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($servicesSidebar->getChild('Change Password'))){
            $servicesSidebar->getChild('Change Password')->setIcon('fa-ticket ls ls-padlock');
        }
        if (!is_null($servicesSidebar->getChild('Cancel'))){
            $servicesSidebar->getChild('Cancel')->setIcon('fa-ticket ls ls-denial');
        }
        if (!is_null($servicesSidebar->getChild('Upgrade/Downgrade'))){
            $servicesSidebar->getChild('Upgrade/Downgrade')->setIcon('fa-ticket ls ls-new-window');
        }
        if (!is_null($servicesSidebar->getChild('Upgrade/Downgrade Options'))){
            $servicesSidebar->getChild('Upgrade/Downgrade Options')->setIcon('fa-ticket ls ls-configure');
        }        
        if (!is_null($servicesSidebar->getChild('Renew Service'))){
            $servicesSidebar->getChild('Renew Service')->setIcon('fa-ticket ls ls-refresh');
        }        
    }

    if ($secondarySidebar && !is_null($secondarySidebar->getChild('My Services Actions'))) {
        $servicesSidebar = $secondarySidebar->getChild('My Services Actions');
        if (!is_null($servicesSidebar->getChild('Place a New Order'))){
            $servicesSidebar->getChild('Place a New Order')->setIcon('fa-ticket ls ls-box');
        }
        if (!is_null($servicesSidebar->getChild('View Available Addons'))){
            $servicesSidebar->getChild('View Available Addons')->setIcon('fa-ticket ls ls-addon');
        }
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Sitelock Sidebar Promo'))) {
        $secondarySidebar->removeChild('Sitelock Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Spamexperts Sidebar Promo'))) {
        $secondarySidebar->removeChild('Spamexperts Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Ssl Sidebar Promo'))) {
        $secondarySidebar->removeChild('Ssl Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Weebly Sidebar Promo'))) {
        $secondarySidebar->removeChild('Weebly Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Codeguard Sidebar Promo'))) {
        $secondarySidebar->removeChild('Codeguard Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Sitelockvpn Sidebar Promo'))) {
        $secondarySidebar->removeChild('Sitelockvpn Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Marketgoo Sidebar Promo'))) {
        $secondarySidebar->removeChild('Marketgoo Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Ox Sidebar Promo'))) {
        $secondarySidebar->removeChild('Ox Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Symantec Sidebar Promo'))) {
        $secondarySidebar->removeChild('Symantec Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Sitebuilder Sidebar Promo'))) {
        $secondarySidebar->removeChild('Sitebuilder Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Cpanelseo Sidebar Promo'))) {
        $secondarySidebar->removeChild('Cpanelseo Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Nordvpn Sidebar Promo'))) {
        $secondarySidebar->removeChild('Nordvpn Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Xovinow Sidebar Promo'))) {
        $secondarySidebar->removeChild('Xovinow Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Threesixtymonitoring Sidebar Promo'))) {
        $secondarySidebar->removeChild('Threesixtymonitoring Sidebar Promo');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Socialbee Sidebar Promo'))) {
        $secondarySidebar->removeChild('Socialbee Sidebar Promo');
    }

    //Upgrade Downgrade
    if ($primarySidebar && !is_null($primarySidebar->getChild('Upgrade Downgrade'))) {
        $primarySidebar->getChild('Upgrade Downgrade')->setClass('panel-summary panel-summary-primary panel-upgrade');
    }

    //my domains
    if ($primarySidebar && !is_null($primarySidebar->getChild('My Domains Status Filter'))) {
        $primarySidebar->removeChild('My Domains Status Filter');
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('My Domains Actions'))) {
        $domainsSidebar = $secondarySidebar->getChild('My Domains Actions');
        if (!is_null($domainsSidebar->getChild('Renew Domain'))){
            $domainsSidebar->getChild('Renew Domain')->setIcon('fa-ticket ls ls-refresh');
        }
        if (!is_null($domainsSidebar->getChild('Register a New Domain'))){
            $domainsSidebar->getChild('Register a New Domain')->setIcon('fa-ticket ls ls-dns');
        }
        if (!is_null($domainsSidebar->getChild('Transfer in a Domain'))){
            $domainsSidebar->getChild('Transfer in a Domain')->setIcon('fa-ticket ls ls-transfer');
        }
    }
    //domains management
    if ($primarySidebar && !is_null($primarySidebar->getChild('Domain Details Management'))) {
        $domainsDetailsSidebar = $primarySidebar->getChild('Domain Details Management');
        if (!is_null($domainsDetailsSidebar->getChild('Overview'))){
            $domainsDetailsSidebar->getChild('Overview')->setIcon('fa-ticket ls ls-dashboard');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Auto Renew Settings'))){
            $domainsDetailsSidebar->getChild('Auto Renew Settings')->setIcon('fa-ticket ls ls-refresh');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Modify Nameservers'))){
            $domainsDetailsSidebar->getChild('Modify Nameservers')->setIcon('fa-ticket ls ls ls-share');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Registrar Lock Status'))){
            $domainsDetailsSidebar->getChild('Registrar Lock Status')->setIcon('fa-ticket ls ls-shield');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Release Domain'))){
            $domainsDetailsSidebar->getChild('Release Domain')->setIcon('fa-ticket ls ls-refresh');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Domain Addons'))){
            $domainsDetailsSidebar->getChild('Domain Addons')->setIcon('fa-ticket ls ls-addon');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Domain Contacts'))){
            $domainsDetailsSidebar->getChild('Domain Contacts')->setIcon('fa-ticket ls ls-user');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Manage Private Nameservers'))){
            $domainsDetailsSidebar->getChild('Manage Private Nameservers')->setIcon('fa-ticket ls ls-share');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Manage DNS Host Records'))){
            $domainsDetailsSidebar->getChild('Manage DNS Host Records')->setIcon('fa-ticket ls ls-dns');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Manage Email Forwarding'))){
            $domainsDetailsSidebar->getChild('Manage Email Forwarding')->setIcon('fa-ticket ls ls-envelope');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Get EPP Code'))){
            $domainsDetailsSidebar->getChild('Get EPP Code')->setIcon('fa-ticket ls ls-input-code');
        }
    }
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Domain Details Actions'))) {
        $domainsDetailsActionsSidebar = $secondarySidebar->getChild('Domain Details Actions');
        if (!is_null($domainsDetailsActionsSidebar->getChild('Renew Domain'))){
            $domainsDetailsActionsSidebar->getChild('Renew Domain')->setIcon('fa-ticket ls ls-refresh');
        }
        if (!is_null($domainsDetailsActionsSidebar->getChild('Register a New Domain'))){
            $domainsDetailsActionsSidebar->getChild('Register a New Domain')->setIcon('fa-ticket ls ls-dns');
        }
        if (!is_null($domainsDetailsActionsSidebar->getChild('Transfer in a Domain'))){
            $domainsDetailsActionsSidebar->getChild('Transfer in a Domain')->setIcon('fa-ticket ls ls-transfer');
        }
    }
    //orderform
    if ($secondarySidebar && !is_null($secondarySidebar->getChild('Actions'))) {
        $cartActionsSidebar = $secondarySidebar->getChild('Actions');
        if (!is_null($cartActionsSidebar->getChild('Domain Renewals'))){
            $cartActionsSidebar->getChild('Domain Renewals')->setIcon('fa-ticket ls ls-refresh');
        }
        if (!is_null($cartActionsSidebar->getChild('Renew Services'))){
            $cartActionsSidebar->getChild('Renew Services')->setIcon('fa-ticket ls ls-refresh');
        }
        if (!is_null($cartActionsSidebar->getChild('Domain Registration'))){
            $cartActionsSidebar->getChild('Domain Registration')->setIcon('fa-ticket ls ls-dns');
        }
        if (!is_null($cartActionsSidebar->getChild('Domain Transfer'))){
            $cartActionsSidebar->getChild('Domain Transfer')->setIcon('fa-ticket ls ls-transfer');
        }
        if (!is_null($cartActionsSidebar->getChild('View Cart'))){
            $cartActionsSidebar->getChild('View Cart')->setIcon('fa-ticket ls ls-basket');
        }
    }

    if ($primarySidebar && !is_null($primarySidebar->getChild('Email Actions - S403'))) {
        $domainsDetailsSidebar = $primarySidebar->getChild('Email Actions - S403');
        if (!is_null($domainsDetailsSidebar->getChild('Manage'))){
            $domainsDetailsSidebar->getChild('Manage')->setIcon('fa-ticket ls ls-user');
            $domainsDetailsSidebar->getChild('Manage')->setClass('d-flex align-center btn-service-sso');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Manage OX'))){
            $domainsDetailsSidebar->getChild('Manage OX')->setIcon('fa-ticket ls ls-configure');
        }
        if (!is_null($domainsDetailsSidebar->getChild('Upgrade OX'))){
            $domainsDetailsSidebar->getChild('Upgrade OX')->setIcon('fa-ticket ls ls ls-new-window');
        }
    }
});

/*
 * **********************************************
   3. Request Cancellation Button On Free Product
 * **********************************************
 */

add_hook('ClientAreaPrimarySidebar', 1, function($primarySidebar) {
    // Get the handle for the Service Details Overview sidebar
    $serviceDetailsOverview = $primarySidebar->getChild('Service Details Actions');

    // Make sure the handle is not null
    if (!is_null($serviceDetailsOverview)) {
        GLOBAL $smarty;
        $templateVars = $smarty->getTemplateVars();
        $template = new Template($templateVars['template']);
        $page = new Page($template, 'clientareaproductdetails');
        $show_cancellation_button = false;
        if (isset($page) && $page){
            if ($page->getConfiguredOption()){
                $settings = $page->getConfiguredOption()->getSettings(true);
            }
        }
        if (isset($settings) && is_array($settings)){
            if (isset($settings['freeProductCancellation']) && $settings['freeProductCancellation'] == 1){
                $show_cancellation_button = true;
            }
        }

        // Make sure the ID is available
        if (!empty($_REQUEST['id']) && $show_cancellation_button) {
            $serviceId = (int) $_REQUEST['id'];

            // Check if this is a free service
            $billingCycle = Capsule::table('tblhosting')
                ->where('id', $serviceId)
                ->value('billingcycle');
            if ($billingCycle === 'Free Account') {               
                // Add the cancellation request menu item for the service to the sidebar
                $serviceDetailsOverview->addChild(
                    'freeServiceCancellationRequest',
                    [
                        'name' => 'CancellationRequest',
                        'label' => Lang::trans('clientareacancelrequestbutton'),
                        'uri' => '/clientarea.php?action=cancel&id=' . $serviceId,
                        'icon' => 'fa-ticket ls ls-denial',
                        'order' => 90,
                    ]
                );
            }
        }
    }
});

/*
 * **********************************************
   4. View Ticket - Hide Ticket Priority
 * **********************************************
 */

add_hook('ClientAreaSidebars', 2, function($vars) {
    $primarySidebar = Menu::primarySidebar();
    $secondarySidebar = Menu::secondarySidebar();

    $ticketInformation = $primarySidebar->getChild('Ticket Information');

    if (!is_null($ticketInformation)) {
        GLOBAL $smarty;
        $templateVars = $smarty->getTemplateVars();
        $template = new Template($templateVars['template']);
        $page = new Page($template, 'viewticket');
        $hideTicketPriority = false;
        if (isset($page) && $page){
            if ($page->getConfiguredOption()){
                $settings = $page->getConfiguredOption()->getSettings(true);
            }
        }
        if (isset($settings) && is_array($settings)){
            if (isset($settings['hideTicketPriority']) && $settings['hideTicketPriority'] == 1){
                $hideTicketPriority = true;
            }
        }
        
        if (isset($hideTicketPriority) && $hideTicketPriority){
            if (!is_null($ticketInformation->getChild('Priority'))){
                if ($page->getConfiguredOption() && method_exists($page->getConfiguredOption(), 'getCustomVariables') && isset($page->getConfiguredOption()->getCustomVariables()['page_layout']) && $page->getConfiguredOption()->getCustomVariables()['page_layout'] == 'new'){
                    $ticketInformation->removeChild('Priority');
                }
                else {
                    $ticket = Menu::context("ticket");
                    if ($ticket){
                        $status = $ticket->status;
                        $ticketStatuses = \WHMCS\Database\Capsule::table("tblticketstatuses")->get()->all();
                        $ticketStatusColor = "";
                        foreach ($ticketStatuses as $ticketStatus) {
                            if($ticketStatus->title == $status) {
                                $ticketStatusColor = $ticketStatus->color;
                            }
                            if(!$ticketStatus->showactive && !$ticketStatus->showawaiting) {
                                $closedTicketStatuses[] = $ticketStatus->title;
                            }
                        }
                        $statusPlain = preg_replace("/[^a-z]/i", "", strtolower($status));
                        $displayStatus = \Lang::trans("supportticketsstatus" . $statusPlain);
                        if($displayStatus == "supportticketsstatus" . $statusPlain) {
                            $displayStatus = $status;
                        }
                        $ticketInformation->removeChild('Priority');
                        $ticketInformation->addChild('Priority',
                            [
                                'name' => 'Priority',
                                'label' => "<span class=\"title\">" .Lang::trans('supportticketsstatus'). "</span><br>" . "<span class=\"label\" style=\"background-color:" . $ticketStatusColor . ";\">" . $displayStatus . "</span> ",
                                "attributes" => ["class" => "ticket-details-children"],
                                'order' => 50,
                            ]
                        );
                    }
                }
            }
        }
    }
});

/*
 * **************************************************************
    5. Account Sidebar Box Display
 * **************************************************************
*/

add_hook('ClientAreaPrimarySidebar', 0, function() {
    $client = Menu::context("client");
    if(is_null($client)) {
        return;
    }
    GLOBAL $smarty;
    $vars = $smarty->getTemplateVars();
    $primarySidebar = Menu::primarySidebar();
    $accountPages = ['clientareadetails', 'account-user-management', 'account-user-permissions', 'account-paymentmethods', 'account-paymentmethods-manage', 'account-contacts-manage', 'account-contacts-new', 'clientareasecurity', 'clientareaemails', 'user-profile', 'user-switch-account', 'user-password', 'user-security'];
    if ($client && in_array($vars['templatefile'], $accountPages)){
        $templatefile = $vars['templatefile'];
        if ($templatefile == 'account-user-permissions'){
            $templatefile = 'account-user-management';
        } else if ($templatefile == 'account-paymentmethods-manage'){
            $templatefile = 'account-paymentmethods';
        } else if ($templatefile == 'account-contacts-new'){
            $templatefile = 'account-contacts-manage';
        }
        $displayAccountBoxDisplay = Settings::where('setting', 'show_account_details_sidebar_box')->first();
        if (isset($displayAccountBoxDisplay) && $displayAccountBoxDisplay){
            $displayAccountBoxDisplayValue = $displayAccountBoxDisplay->value;
        }
        if ($displayAccountBoxDisplayValue == "enabled"){
            $acccountDetailsSidebarBox = Settings::where('setting', 'acccount_details_sidebar_box')->first();

            if (isset($acccountDetailsSidebarBox) && $acccountDetailsSidebarBox){
                $acccountDetailsSidebarBoxValue = $acccountDetailsSidebarBox->value;
                $accountPages = json_decode($acccountDetailsSidebarBoxValue);

                if (in_array($templatefile, $accountPages) || in_array('all', $accountPages)){
                    $details = "";
                    if($client->companyName) {
                        $details .= "<strong>" . $client->companyName . "</strong><br><em>" . $client->fullName . "</em><br>";
                    } else {
                        $details .= "<strong>" . $client->fullName . "</strong><br>";
                    }
                    $details .= $client->address1 . "<br>";
                    if($client->address2) {
                        $details .= $client->address2 . "<br>";
                    }
                    $address = [];
                    if($client->city) {
                        $address[] = $client->city;
                    }
                    if($client->state) {
                        $address[] = $client->state;
                    }
                    if($client->postcode) {
                        $address[] = $client->postcode;
                    }
                    $details .= implode(", ", $address) . "<br>" . $client->countryName;
                    if($client->taxId) {
                        $details .= "<br>" . $client->taxId;
                    }
                    //$updateText = Lang::trans("update");
                    //$clientDetailsFooter = "    <a href=\"clientarea.php?action=details\" class=\"btn btn-success btn-sm btn-block\">\n        <i class=\"fas fa-pencil-alt\"></i> " . $updateText . "\n    </a>";

                    $primarySidebar->addChild('Client Details',
                        [
                            'name' => 'Client Details',
                            'label' => Lang::trans("yourinfo"),
                            'bodyHtml' => $details,
                            //'footerHtml' => $clientDetailsFooter,
                            'order' => 1,
                        ]
                    );
                }
            }
        }
    }
});

/*
 * **************************************************************
    6. View Ticket - Ticket Sidebars - New Layout
 * **************************************************************
*/

add_hook('ClientAreaPage', 3, function($vars) {
    
    $primarySidebar = Menu::primarySidebar();
    $secondarySidebar = Menu::secondarySidebar();
    $ticket = Menu::context("ticket");
    if(!$ticket) {
        return '';
    }

    GLOBAL $smarty;
    $templateVars = $smarty->getTemplateVars();
    $template = new Template($templateVars['template']);
    $page = new Page($template, 'viewticket');

    if (isset($page) && $page){
        if ($page->getConfiguredOption() && method_exists($page->getConfiguredOption(), 'getCustomVariables') &&  isset($page->getConfiguredOption()->getCustomVariables()['page_layout']) && $page->getConfiguredOption()->getCustomVariables()['page_layout'] == 'new'){

            // Ticket Information Sidebar Panel
            $ticketInformation = $primarySidebar->getChild('Ticket Information');
            if (!is_null($ticketInformation)){ 
                $primarySidebar->removeChild('Ticket Information');
                $carbon = Menu::context("carbon");
                $ticketId = $ticket->id;
                $c = $ticket->c;
                $cc = $ticket->cc;
                $departmentId = $ticket->departmentId;
                $dateOpened = $ticket->date;
                $ticketRef = $ticket->ticketNumber;
                $subject = $ticket->subject;
                $priority = $ticket->priority;
                $status = $ticket->status;
                $lastReply = $ticket->lastReply;
                $dateOpened = fromMySQLDate($dateOpened, 1, 1);
                $departmentName = getDepartmentName($departmentId);
                $priority = Lang::trans("supportticketsticketurgency" . strtolower($priority));
                $ticketClosed = false;
                $closedTicketStatuses = [];
                $ticketStatuses = \WHMCS\Database\Capsule::table("tblticketstatuses")->get()->all();
                $ticketStatusColor = "";
                foreach ($ticketStatuses as $ticketStatus) {
                    if($ticketStatus->title == $status) {
                        $ticketStatusColor = $ticketStatus->color;
                    }
                    if(!$ticketStatus->showactive && !$ticketStatus->showawaiting) {
                        $closedTicketStatuses[] = $ticketStatus->title;
                    }
                }
                if(in_array($status, $closedTicketStatuses)) {
                    $ticketClosed = true;
                }
                $statusPlain = preg_replace("/[^a-z]/i", "", strtolower($status));
                $displayStatus = Lang::trans("supportticketsstatus" . $statusPlain);
                if($displayStatus == "supportticketsstatus" . $statusPlain) {
                    $displayStatus = $status;
                }
                $detailsChildren = [
                    [
                        "name" => "Status", "label" => "<div class=\"list-group-item-content\"><span class=\"title\">" . Lang::trans("supportticketsstatus") . ": </span>" . "<span class=\"status\" style=\"--status-color:" . $ticketStatusColor . ";\">" . $displayStatus . "</span></div>", 
                        'icon' => 'lm lm-flag',
                        "attributes" => ["class" => ""], 
                        "order" => 5
                    ], 
                    [
                        "name" => "Requestor", "label" => "<div class=\"list-group-item-content\"><span class=\"title\">" . Lang::trans("requestor") . "</span>" . "<span class=\"flex-container\">" . str_replace('label ', 'label label-xs label-rounded ', $ticket->getRequestorDisplayLabel()) . "</span>" . "</div>", 
                        'icon' => 'lm lm-user-circle',
                        "attributes" => ["class" => ""], 
                        "order" => 10
                    ], 
                    [
                        "name" => "Department", "label" => "<div class=\"list-group-item-content\"><span class=\"title\">" . Lang::trans("supportticketsdepartment") . "</span>" . $departmentName . "</div>", 
                        "icon" => 'lm lm-direction-sign',
                        "attributes" => ["class" => ""], 
                        "order" => 20
                    ], 
                    [
                        "name" => "Date Opened", "label" => "<div class=\"list-group-item-content\"><span class=\"title\">" . Lang::trans("supportticketsubmitted") . "</span>" . $dateOpened . "</div>", 
                        "icon" => "lm lm-calendar",
                        "attributes" => ["class" => ""], "order" => 30
                    ], 
                    [
                        "name" => "Last Updated", "label" => "<div class=\"list-group-item-content\"><span class=\"title\">" . Lang::trans("supportticketsticketlastupdated") . "</span>" . $carbon->parse($lastReply)->diffForHumans() . "</div>", 
                        "icon" => "lm lm-clock",
                        "attributes" => ["class" => ""], "order" => 40
                    ]
                ];

                $hideTicketPriority = false;
                if (isset($page) && $page){
                    if ($page->getConfiguredOption()){
                        $settings = $page->getConfiguredOption()->getSettings(true);
                    }
                }
                if (isset($settings) && is_array($settings)){
                    if (isset($settings['hideTicketPriority']) && $settings['hideTicketPriority'] == 1){
                        $hideTicketPriority = true;
                    }
                }
                if (!isset($hideTicketPriority) || !$hideTicketPriority){
                    $detailsChildren[] = [
                        "name" => "Priority", "label" => "<div class=\"list-group-item-content\"><span class=\"title\">" . Lang::trans("supportticketspriority") . "</span>" . $priority . "</div>", 
                        "icon" => "lm lm-info",
                        "attributes" => ["class" => ""], 
                        "order" => 50
                    ];
                }

                
                $primarySidebar->addChild('Ticket Information',
                    [
                        'name' => 'Ticket Information',
                        'label' => Lang::trans("ticketinfo"),
                        'order' => 10,
                    ]
                )->setClass('panel-styled-group panel-ticket-information');

                $mobileBodyHtml = '<div class="list-group">';
                $index = 0;
                foreach ($detailsChildren as $child){
                    $primarySidebar->getChild('Ticket Information')->addChild($child['name'],
                        [
                            'name' => $child['name'],
                            'label' => $child['label'],
                            'icon'  => 'fa fa-test list-group-item-content ' .$child['icon'],
                            'attributes' => $child['attributes'],
                            'order' => $child['order'],
                        ]
                    );
                    if ($index === 0) {
                        $mobileBodyHtml .= '<div class="list-group-item collapsed" data-toggle="collapse" href="#panelTicketInfoMobile" aria-controls="panelTicketInfoMobile"><i class="'.$child['icon'].'"></i>'.$child['label'].'<i class="ls ls-caret ml-auto mr-0"></i></div><div class="collapse" id="panelTicketInfoMobile">';
                    } else {
                        $mobileBodyHtml .= '<div class="list-group-item"><i class="'.$child['icon'].'"></i>'.$child['label'].'</div>';
                    }
                    $index++;
                    
                } 

                $mobileBodyHtml .= '</div></div>';

                $primarySidebar->addChild('Ticket Information Mobile',
                    [
                        'name' => 'Ticket Information Mobile',
                        'label' => Lang::trans("ticketinfo"),
                        'order' => 11,
                        'bodyHtml' => $mobileBodyHtml,
                        'attributes' => [
                            'class' => 'panel-styled-group panel-ticket-information panel-ticket-information-mobile'
                        ]
                    ]
                );


            }

            // Ticket Attachments Sidebar Panel
            if (!is_null($secondarySidebar->getChild('Attachments'))){
                $secondarySidebar->removeChild('Attachments');
            }

            // Ticket CC Recipients Sidebar Panel
            if (!is_null($secondarySidebar->getChild('CC Recipients'))){
                $secondarySidebar->removeChild('CC Recipients');
            }

            // Ticket Custom Fields Panel
            if (!is_null($secondarySidebar->getChild('Custom Fields'))){
                $secondarySidebar->removeChild('Custom Fields');
            }

            // Support Links Panel
            if (!is_null($secondarySidebar->getChild('Support'))){
                $secondarySidebar->removeChild('Support');
            }
        }
    }
});


/*
 * **************************************************************
    7. Open Ticket - Ticket Sidebars - New Layout
 * **************************************************************
*/

add_hook('ClientAreaPage', 3, function($vars) {
    
    $primarySidebar = Menu::primarySidebar();
    $secondarySidebar = Menu::secondarySidebar();
    
    GLOBAL $smarty;
    $templateVars = $smarty->getTemplateVars();
    
    if ($templateVars['filename'] == "submitticket" && isset($templateVars['deptid'])){
        $template = new Template($templateVars['template']);
        $page = new Page($template, 'supportticketsubmit-steptwo');
        $kbsuggestions = false;
        if(WHMCS\Config\Setting::getValue("SupportTicketKBSuggestions")) {
            $kbsuggestions = true;
        }

        if (isset($page) && $page){
            if ($page->getConfiguredOption() && method_exists($page->getConfiguredOption(), 'getCustomVariables') && isset($page->getConfiguredOption()->getCustomVariables()['page_layout']) && $page->getConfiguredOption()->getCustomVariables()['page_layout'] == 'new'){
                // Support Links Panel
                if (!is_null($secondarySidebar->getChild('Support'))){
                    $secondarySidebar->removeChild('Support');
                }
                // Recent Tickets Panel
                if (!is_null($secondarySidebar->getChild('Recent Tickets'))){
                    $secondarySidebar->removeChild('Recent Tickets');
                }
                
                if ($kbsuggestions){
                    $iconPath = __DIR__ . "/../../assets/svg-icon/64-knowledgebase-search.tpl";
                    $iconHtml = '';
                    $rslang = RsLang::factory(AddonHelper::getTemplate()->getFullPath());
                
                    $kbDescLang = $rslang->trans('support.kb_search_sidebar.desc');
                    $kbSearchPlaceholder = $rslang->trans('support.kb_search_sidebar.placeholder');
                    $kbSearchNoDataDesc = $rslang->trans('support.kb_search_sidebar.no_data_desc');
                    $kbSearchNoDataBtnLang = $rslang->trans('generals.clear_filters');
                    
                    if (file_exists($iconPath)) {
                        $iconHtml = file_get_contents($iconPath);
                    }

                    $kbsuggestionsBodyHtml = '<div class="kb-suggestion-form" data-knowledgebase-search data-size="sm" data-ajax-url="'.$templateVars['webroot'].'/templates/'.$templateVars['template'].'">
                        <div class="icon">'.$iconHtml.'</div>
                        <div class="desc text-center p-sm">'.$kbDescLang.'</div>
                        <div class="search-field">
                            <input class="form-control input-sm" data-knowledgebase-search-input placeholder="'.$kbSearchPlaceholder.'"/>
                            <div class="search-field-icon"><i class="ls ls-search"></i></div>
                            <div class="search-field-loader loader hidden" data-knowledgebase-search-loader>
                                <div class="spinner spinner-sm"><div class="rect1"></div><div class="rect2"></div><div class="rect3"></div><div class="rect4"></div><div class="rect5"></div></div>
                            </div>
                            <div class="search-field-results list-group has-scroll list-group-xxs" data-knowledgebase-search-results data-btn-clear-lang="'.$kbSearchNoDataBtnLang.'" data-lang-nodata-desc="'.$kbSearchNoDataDesc.'" data-lang-nodata="'.Lang::trans("knowledgebasenoarticles").'"></div>
                        </div>
                    </div>
                    <div class="kb-articles hidden" data-knowledgebase-ticket-search>
                        <div class="list-group list-group-xs limited-list-group" data-knowledgebase-ticket-search-content>
                        
                        </div>
                        <a class="btn btn-link btn-xs w-100 mt-1" data-knowledgebase-more-article>Load More Suggestion</a>
                    </div>
                    ';

                    $primarySidebar->addChild('Knowledgebase Suggestions',
                        [
                            'name' => 'Knowledgebase Suggestions',
                            'label' => Lang::trans("kbsuggestions"),
                            'order' => 20,
                            'bodyHtml' => $kbsuggestionsBodyHtml
                        ]
                    )->setClass('panel-styled-group');
                }
            }
        }
    } else {
        return;
    }
});


/*
 * **************************************************************
    8. Add Funds
 * **************************************************************
*/
add_hook('ClientAreaSidebars', 2, function($vars) {
    $primarySidebar = Menu::primarySidebar();

    if ($primarySidebar && !is_null($primarySidebar->getChild('Add Funds'))) {
        $primarySidebar->removeChild('Add Funds');
        GLOBAL $smarty;
        $templateVars = $smarty->getTemplateVars();
        if (!$templateVars['addfundsdisabled'] && $templateVars['templatefile'] == "clientareaaddfunds"){
            $template = new Template($templateVars['template']);
            $style = new Style($template,$template->getActiveStyle());
            $items = $style->getCustomSettings();
            $data = [];
            $panelClass = 'panel-summary panel-summary-primary';
            foreach($items['group'] as $indexGroup=>$valueGroup){
                foreach($valueGroup['styles'] as $indexItem=>$valueItem){
                    if ($valueItem['variableName'] == 'sidebarBoxStyle'){
                        if ($valueItem['value']){
                            $currentColor = $valueItem['value'];
                        } else {
                            $currentColor = $valueItem['default'];
                        }               
                        $panelClass = 'panel-summary panel-summary-'.$currentColor;
                        break;
                    }
                }
            }
            
            $bodyHtml = '
                <div class="summary-total">
                    <div class="price price-left-h price-sm">
                        <span class="price-total">
                            '.LANG::trans('invoiceaddcreditdesc1').'
                        </span> 
                        <span class="price-amount">
                            '.$templateVars['clientsstats']['creditbalance'].'
                        </span>
                    </div>
                </div>    
                <div class="summary-content">
                    <ul class="summary-list">
                        <li class="list-item faded">
                            <span class="item-name">'.LANG::trans('addfundsminimum').'</span>
                            <span class="item-value">'.$templateVars['minimumamount'].'</span>
                        </li>
                        <li class="list-item faded">
                            <span class="item-name">'.LANG::trans('addfundsmaximum').'</span>
                            <span class="item-value">'.$templateVars['maximumamount'].'</span>
                        </li>
                        <li class="list-item faded">
                            <span class="item-name">'.LANG::trans('addfundsmaximumbalance').'</span>
                            <span class="item-value">'.$templateVars['maximumbalance'].'</span>
                        </li>
                    </ul>
                </div>
            ';


            $alert = '<div class="alert alert-lagom alert-info alert-sm alert-panel">
                <div class="alert-icon ls ls-info-circle"></div>
                <div class="alert-body">
                    '.str_replace(['*', '.'], '', LANG::trans('addfundsnonrefundable')).'
                </div>
            </div>';

            $primarySidebar->addChild('Add Funds',
                [
                    'name' => 'Add Funds',
                    'label' => false,
                    'order' => 1,
                    "attributes" => ["noHeading" => true, "alert" => $alert],
                    'bodyHtml' => $bodyHtml
                ]
            )->setClass($panelClass);
        }
    }
});


/*
 * **************************************************************
    9. Affiliates
 * **************************************************************
*/

add_hook('ClientAreaSidebars', 2, function($vars) {
    $primarySidebar = Menu::primarySidebar();
    GLOBAL $smarty;
    $templateVars = $smarty->getTemplateVars();
   
    if ($templateVars['templatefile'] == "affiliates") {

        if (!$templateVars['inactive']){
            $template = new Template($templateVars['template']);
            $style = new Style($template,$template->getActiveStyle());
            $items = $style->getCustomSettings();
            $data = [];
            $panelClass = 'panel-summary panel-summary-primary panel-add-funds';
            foreach($items['group'] as $indexGroup=>$valueGroup){
                foreach($valueGroup['styles'] as $indexItem=>$valueItem){
                    if ($valueItem['variableName'] == 'sidebarBoxStyle'){
                        if ($valueItem['value']){
                            $currentColor = $valueItem['value'];
                        } else {
                            $currentColor = $valueItem['default'];
                        }               
                        $panelClass = 'panel-summary panel-summary-'.$currentColor.' panel-add-funds';
                        break;
                    }
                }
            }
            
            $bodyHtml = '
                <div class="summary-total">
                    <div class="price price-sm price-left-h">
                        <span class="price-total">'.LANG::trans('affiliatescommissionsavailable').'</span>
                        <span class="price-amount">'.$templateVars['balance'].'</span>
                    </div>
                </div>
                <div class="summary-content">
                    <ul class="summary-list">
                        <li class="list-item faded">
                            <span class="item-name">'.LANG::trans('affiliatescommissionspending').'</span>
                            <span class="item-value">'.$templateVars['pendingcommissions'].'</span>
                        </li>
                        <li class="list-item faded">
                             <span class="item-name">'.LANG::trans('affiliateswithdrawn').'</span>
                            <span class="item-value">'.$templateVars['withdrawn'].'</span>
                        </li>
                    </ul>
                </div>
            ';
            $url = $_SERVER['PHP_SELF'] . '?action=withdrawrequest';
            if (!$templateVars['withdrawlevel'] || $templateVars['withdrawrequestsent']){
                $disabled = '';
                if (!$templateVars['withdrawlevel'] || $templateVars['withdrawrequestsent']){
                    $disabled = 'disabled';
                }
                $footerHtml = '
                    <button tabindex="0" href="'.$url.'" class="btn btn-primary-faded btn-block" '.$disabled.'>
                        <i class="ls ls-bank-note"></i> '.LANG::trans('affiliatesrequestwithdrawal').'
                    </button>   
                ';
            } else {
                $disabled = '';
                if (!$templateVars['withdrawlevel'] || $templateVars['withdrawrequestsent']){
                    $disabled = 'disabled';
                }
                $footerHtml = '
                    <form method="POST" action="'.$_SERVER['PHP_SELF'].'">
                        <input type="hidden" name="action" value="withdrawrequest" />
                        <button tabindex="0" type="submit" href="'.$url.'" class="btn btn-primary-faded btn-block '.$disabled.'" '.$disabled.'>
                            <i class="ls ls-bank-note"></i> '.LANG::trans('affiliatesrequestwithdrawal').'
                        </button>
                    </form>
                ';
            }
            $alert = false;
            if ($templateVars['withdrawrequestsent']){
                $alert = '
                    <div class="alert alert-success alert-sm alert-panel">
                        <i class="alert-icon ls ls-info-circle"></i>
                        <p>'.LANG::trans('affiliateswithdrawalrequestsuccessful').'</p>
                    </div>
                ';
            } else {
                if (!$templateVars['withdrawlevel']){
                    $minimum = $templateVars['affiliatePayoutMinimum'];
                    $langText = LANG::trans('affiliateWithdrawalSummary');
                    $langText = str_replace(':amountForWithdrawal', $minimum, $langText);

                    $alert = '
                        <div class="alert alert-lagom alert-info alert-sm alert-panel">
                            <i class="alert-icon ls ls-info-circle"></i>
                            '.$langText.'
                        </div>
                    ';
                }
            }

            $primarySidebar->addChild('Available Commissions Balance',
                [
                    'name' => 'Available Commissions Balance',
                    'label' => false,
                    'order' => 1,
                    "attributes" => ["noHeading" => true, "alert" => $alert],
                    'bodyHtml' => $bodyHtml,
                    'footerHtml' => $footerHtml
                ]
            )->setClass($panelClass);
        }
    }
});

/*
 * **************************************************************
    10. Invoices
 * **************************************************************
*/

add_hook('ClientAreaSidebars', 2, function($vars) {
    $primarySidebar = Menu::primarySidebar();

    if ($primarySidebar && !is_null($primarySidebar->getChild('My Invoices Status Filter'))) {
        $primarySidebar->removeChild('My Invoices Status Filter');
    }
    if ($primarySidebar && !is_null($primarySidebar->getChild('My Invoices Summary'))) {
        $primarySidebar->removeChild('My Invoices Summary');
        GLOBAL $smarty;
        $templateVars = $smarty->getTemplateVars();

        if ($templateVars['clientsstats']['numdueinvoices'] !=0 && $templateVars['templatefile'] == 'clientareainvoices'){

            $template = new Template($templateVars['template']);
            $style = new Style($template,$template->getActiveStyle());
            $items = $style->getCustomSettings();
            $data = [];
            $panelClass = 'panel-summary panel-summary-primary';
            foreach($items['group'] as $indexGroup=>$valueGroup){
                foreach($valueGroup['styles'] as $indexItem=>$valueItem){
                    if ($valueItem['variableName'] == 'sidebarBoxStyle'){
                        if ($valueItem['value']){
                            $currentColor = $valueItem['value'];
                        } else {
                            $currentColor = $valueItem['default'];
                        }               
                        $panelClass = 'panel-summary panel-summary-'.$currentColor;
                        break;
                    }
                }
            }

            $invoiceLang = LANG::trans('invoicesduemsg');
            $numDue = $templateVars['clientsstats']['numdueinvoices'];
            $placeholder = '';
            $message = sprintf($invoiceLang, $numDue, $placeholder);

            $bodyHtml = '
                <div class="price price-sm price-left">
                    <span class="price-title">'.$message.'</span>
                    <span class="price-amount">'.$templateVars['clientsstats']['dueinvoicesbalance'].'</span>
                </div>    
            ';

            $footerHtml = false;

            if ($templateVars['condlinks']['masspay'] && $templateVars['clientsstats']['numdueinvoices'] !=0){
                $smarty->assign('classes', 'spinner-sm');
                $loaderHtml = $smarty->fetch($templateVars['template'].'/includes/common/loader.tpl');

                $footerHtml = '
                    <a tabindex="0" href="clientarea.php?action=masspay&all=true" class="btn btn-primary-faded btn-block" data-btn-loader>
                        <span><i class="ls ls-share"></i>'.LANG::trans('invoicespaynow').'</span>
                        <div class="loader loader-button hidden" >
                            '.$loaderHtml.'  
                        </div>
                    </a>
                ';
            }

            $primarySidebar->addChild('My Invoices Summary',
                [
                    'name' => 'My Invoices Summary',
                    'label' => false,
                    'order' => 1,
                    "attributes" => ["noHeading" => true],
                    'bodyHtml' => $bodyHtml,
                    'footerHtml' => $footerHtml
                ]
            )->setClass($panelClass);
        }

    }
});

/*
 * **************************************************************
    11. Server Status
 * **************************************************************
*/

add_hook('ClientAreaSidebars', 2, function($vars) {
    $primarySidebar = Menu::primarySidebar();

    if ($primarySidebar && !is_null($primarySidebar->getChild('Network Status'))) {
        $primarySidebar->removeChild('Network Status');

        GLOBAL $smarty;
        $templateVars = $smarty->getTemplateVars();
        
        if ($templateVars['templatefile'] == "serverstatus")
        $panelClass = 'panel-default panel-actions view-filter-btns';
        $primarySidebar->addChild('Network Status',
            [
                'name' => 'Network Status',
                'label' => false,
                'order' => 1,
                "attributes" => ["noHeading" => true],
            ]
        )->setClass($panelClass);

        $primarySidebar->getChild('Network Status')->addChild('View RSS Feed',
            [
                'name' => 'View RSS Feed',
                'uri' => $templateVars['webroot'].'/networkissuesrss.php',
                'label' => 'View RSS Feed',
                'icon'  => 'fa fa-test ls ls-rss',
                'order' => 1,
            ]
        );
    }
});

/*
 * **************************************************************
    12. Mass Payment
 * **************************************************************
*/

add_hook('ClientAreaSidebars', 2, function($vars) {
    $secondarySidebar = Menu::secondarySidebar();

    GLOBAL $smarty;
    $templateVars = $smarty->getTemplateVars();

    if ($templateVars['templatefile'] == "masspay"){

        $template = new Template($templateVars['template']);
        $style = new Style($template,$template->getActiveStyle());
        $items = $style->getCustomSettings();
        $data = [];
        $panelClass = 'panel-summary panel-summary-primary view-invoice';
        foreach($items['group'] as $indexGroup=>$valueGroup){
            foreach($valueGroup['styles'] as $indexItem=>$valueItem){
                if ($valueItem['variableName'] == 'sidebarBoxStyle'){
                    if ($valueItem['value']){
                        $currentColor = $valueItem['value'];
                    } else {
                        $currentColor = $valueItem['default'];
                    }               
                    $panelClass = 'panel-summary panel-summary-'.$currentColor.' view-invoice';
                    break;
                }
            }
        }

        $bodyHtml = '
            <div class="price price-sm price-left-h">
                <span class="price-title">'.LANG::trans('invoicestotaldue').'</span> 
                <span class="price-amount">'.$templateVars['total'].'</span>
            </div>    
        ';

        $invoiceitems = $templateVars['invoiceitems'];
        $gateways = $templateVars['gateways'];
        $LANG = $templateVars['LANG'];

        $smarty->assign('classes', 'spinner-sm');
        $loaderHtml = $smarty->fetch($templateVars['template'].'/includes/common/loader.tpl');

        $footerHtml = '<form method="post" action="clientarea.php?action=masspay">
            <input type="hidden" name="geninvoice" value="true" />';

        foreach ($invoiceitems as $invid => $invoiceitem) {
            $footerHtml .= '<input type="hidden" name="invoiceids[]" value="' . $invid . '" />';
        }

        $footerHtml .= '<fieldset>
                <div class="form-group">
                    <label for="paymentmethod" class="control-label">' . $LANG['orderpaymentmethod'] . ':</label>
                    <select name="paymentmethod" id="paymentmethod" class="form-control">';

        foreach ($gateways as $gateway) {
            $footerHtml .= '<option value="' . $gateway['sysname'] . '">' . $gateway['name'] . '</option>';
        }

        $footerHtml .= '</select>
                </div>
                <button tabindex="0" type="submit" value="' . $LANG['masspaymakepayment'] . '" class="btn btn-primary-faded btn-block" id="btnMassPayMakePayment" data-btn-loader>                            
                    <span><i class="ls ls-share"></i>' . $LANG['masspaymakepayment'] . '</span>
                    <div class="loader loader-button hidden" >
                        '.$loaderHtml.'  
                    </div>
                </button> 
            </fieldset>
        </form>';

        $secondarySidebar->addChild('Mass Payment Summary',
            [
                'name' => 'Mass Payment Summary',
                'label' => false,
                'order' => 1,
                "attributes" => ["noHeading" => true],
                'bodyHtml' => $bodyHtml,
                'footerHtml' => $footerHtml
            ]
        )->setClass($panelClass);
    }
});

/*
 * **************************************************************
    13. Client Area Domains Sidebar Box Display
 * **************************************************************
*/

add_hook('ClientAreaSidebars', 2, function($vars) {
    $secondarySidebar = Menu::secondarySidebar();

    GLOBAL $smarty;
    $templateVars = $smarty->getTemplateVars();

    if ($templateVars['templatefile'] == "clientareadomains"){

        $template = new Template($templateVars['template']);
        $page = new Page($template, 'clientareadomains');
        $hideBox = false;

        if (isset($page) && $page){
            if ($page->getConfiguredOption()){
                $settings = $page->getConfiguredOption()->getSettings(true);
            }
        }

        if (isset($settings) && is_array($settings)){
            if (isset($settings['HideRegisterDomainsBox']) && $settings['HideRegisterDomainsBox'] == 1){
                $hideBox = true;
            }
        }

        if ($hideBox) {
            return;
        }

        $style = new Style($template,$template->getActiveStyle());
        $items = $style->getCustomSettings();
        $panelClass = 'panel-sidebar panel-sidebar-primary panel-register';

        foreach($items['group'] as $indexGroup=>$valueGroup){
            foreach($valueGroup['styles'] as $indexItem=>$valueItem){
                if ($valueItem['variableName'] == 'sidebarBoxStyle'){
                    if ($valueItem['value']){
                        $currentColor = $valueItem['value'];
                    } else {
                        $currentColor = $valueItem['default'];
                    }
                    $panelClass = 'panel-sidebar panel-sidebar-'.$currentColor.' panel-register';
                    break;
                }
            }
        }

        $token = $templateVars['token'];

        $bodyHtml = '
            <form method="post" action="'.$templateVars['WEB_ROOT']. '/domainchecker.php">
                <input type="hidden" name="token" value="'.$token.'" />
                <div class="input-group m-b-2x">
                    <span class="input-group-addon">
                        <i class="lm lm-globe"></i>
                    </span>
                    <input type="text" 
                           name="domain" 
                           placeholder="'.$templateVars['LANG']['exampledomain'].'" 
                           class="form-control" 
                           required 
                           autocomplete="off" />
                </div>
                <button type="submit" class="btn btn-primary-faded btn-block">
                    <i class="ls ls-share"></i> '.$templateVars['LANG']['search'].'
                </button>
            </form>
        ';

        $secondarySidebar->addChild('Domain Search Panel',
            [
                'name' => 'Domain Search Panel',
                'label' => $templateVars['LANG']['orderregisterdomain'],
                'icon' => 'fa-chevron-up',
                'order' => 1,
                'bodyHtml' => $bodyHtml,
            ]
        )->setClass($panelClass);
    }
});