<?php

use WHMCS\Database\Capsule;

function XUIONEConfigOption() {
    $head_return = '';
    if (basename($_SERVER["SCRIPT_NAME"]) == 'configproducts.php') {
        $check = Capsule::table('tblproducts')
                ->where('servertype', '=', 'XUIONE')
                ->where('id', '=', $_REQUEST['id'])
                ->get();
    } elseif (basename($_SERVER["SCRIPT_NAME"]) == 'configaddons.php') {
        $check = Capsule::table('tbladdons')
                ->where('module', '=', 'XUIONE')
                ->wherenotIn('server_group_id', [0])
                ->where('id', '=', $_REQUEST['id'])
                ->get();
    }
    if ($_REQUEST['action'] == 'edit' || $_REQUEST['action'] == 'manage') {
        if (isset($check) && !empty($check)) {
            $head_return .= '
             <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            <script type="text/javascript">
               function customfield(){  
               if($("#conf-dialog-custom-fieldXUIONE").is(":data(dialog)"))
                        {
                            $("#conf-dialog-custom-fieldXUIONE").dialog("destroy"); 
                        }
                        $("#conf-dialog-custom-fieldXUIONE").attr("title", "Product Custom Fields");
                        $("#conf-dialog-custom-fieldXUIONE").html("<p style=\"text-align:center\"><img src=\"images/loading.gif\" alt=\"loading...\"/></p>");
                        $("#conf-dialog-custom-fieldXUIONE").dialog({minWidth: 650}); 
                        val = $(this).parent().find("input").val(); 
                        var selectedoption=jQuery("select[name=\'packageconfigoption[2]\']").val();
                         jQuery.post("../modules/servers/XUIONE/XtreamConfig.php",{stormajax:"create-config",id:"' . $_REQUEST['id'] . '",conf_id:"' . $_REQUEST['conf_id'] . '",selected_conf_id:selectedoption}, function(data){
                            $("#conf-dialog-custom-fieldXUIONE").html(data);
                        });
                   } 
              </script>
              <div id="conf-dialog-custom-fieldXUIONE" title="">
              </div>';
            $head_return .= '
            <script type="text/javascript">
    jQuery(document).ready(function () { 
            jQuery("input[type=radio][name=paytype]").change(function() {
                if($(this).attr("id") == "PayType-OneTime")
                {
                    var productSelect = jQuery("select[name=\'packageconfigoption[2]\']").val();
                    if(productSelect != "reselleraccount" && productSelect != "resellercredits" && productSelect != "superreselleraccount" && productSelect != "addonpackage" )
                    {
                        $("#tblModuleSettings tbody tr td").filter(function () {
                        return $(this).text() === "Billing Months";
                        }).show();
                        jQuery("input[name=\'packageconfigoption[21]\']").attr("type","number");
                        jQuery("input[name=\'packageconfigoption[21]\']").attr("min","0");
                        jQuery("input[name=\'packageconfigoption[21]\']").attr("max","100");
                        jQuery("input[name=\'packageconfigoption[21]\']").parent().show();
                    }
                    
                }
                else
                {
                    $("#tblModuleSettings tbody tr td").filter(function () {
                    return $(this).text() === "Billing Months";
                    }).hide();
                    jQuery("input[name=\'packageconfigoption[21]\']"
                    ).parent().hide();
                }
             });
        jQuery(document).ajaxComplete(function () {
            var ConditionForProductAndAddon = "' . basename($_SERVER['PHP_SELF']) . '";
            if(ConditionForProductAndAddon == "configproducts.php")
            {
                jQuery("select[name=\'packageconfigoption[2]\'] option[value=\'addonpackage\']").remove();
            }
             
            var selectedoption = jQuery("select[name=\'packageconfigoption[2]\']").val();
            enablefieldinxtream(selectedoption)
            jQuery("select[name=\'packageconfigoption[2]\']").change(function () { 
                enablefieldinxtream(this.value);
            });
            jQuery("input[name=\'packageconfigoption[10]\']").attr("readonly", "readonly");
            jQuery("input[name=\'packageconfigoption[22]\']").attr("readonly", "readonly");
            
            $("input[type=radio][name=\'packageconfigoption[5]\']").change(function () {
                if (this.value == "Yes") 
                {
                    $("#tblModuleSettings tbody tr td").filter(function () {
                    return $(this).text() === "Trial Hours";
                    }).show();
                    jQuery("input[name=\'packageconfigoption[18]\']").parent().show();
                    $("#tblModuleSettings tbody tr td").filter(function () {
                    return $(this).text() === "Billing Months";
                    }).hide();
                    jQuery("input[name=\'packageconfigoption[21]\']").parent().hide();
                    
                }
                else 
                {
                    $("#tblModuleSettings tbody tr td").filter(function () {
                    return $(this).text() === "Trial Hours";
                    }).hide();
                    jQuery("input[name=\'packageconfigoption[18]\']").parent().hide();
                    if ($("#PayType-OneTime").prop("checked")) 
                    {
                        var productSelect = jQuery("select[name=\'packageconfigoption[2]\']").val();
                        if(productSelect != "reselleraccount" && productSelect != "resellercredits" && productSelect != "superreselleraccount" && productSelect != "addonpackage" )
                        {
                            $("#tblModuleSettings tbody tr td").filter(function () {
                            return $(this).text() === "Billing Months";
                            }).show();
                            jQuery("input[name=\'packageconfigoption[21]\']").attr("type","number");
                            jQuery("input[name=\'packageconfigoption[21]\']").attr("min","0");
                            jQuery("input[name=\'packageconfigoption[21]\']").attr("max","100");
                            jQuery("input[name=\'packageconfigoption[21]\']").parent().show();
                        }
                    }
                }
            });
        });
    });
    function enablefieldinxtream($value) {
        if ($value == "resellercredits") {
            showallconfigfirst();
            $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Max Con." || $(this).text() === "Trial Hours" || $(this).text() === "Billing Months" || $(this).text() === "Packages";
            }).hide();
            jQuery("input[name=\'packageconfigoption[4]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[6]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[8]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[19]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[20]\']").parent().parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[9]\']").parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[12]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[14]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[15]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[17]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[18]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[21]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[22]\']").parent().hide();
        } else if ($value == "reselleraccount") {
            showallconfigfirst();
            $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Fill Credits" || $(this).text() === "Trial Hours" || $(this).text() === "Select Xtream Super-Reseller" || $(this).text() === "Do you want to sync Credit to X.C Panel?"|| $(this).text() === "Billing Months" || $(this).text() === "Watch Streams!" || $(this).text() === "Select XUI Super-Reseller Group"  || $(this).text() === "Packages";
            }).hide();
            jQuery("input[name=\'packageconfigoption[4]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[6]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[8]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[19]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[20]\']").parent().parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[9]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[11]\']").parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[13]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[15]\']").parent().parent().parent().hide(); 
            jQuery("input[name=\'packageconfigoption[18]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[21]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[22]\']").parent().hide();

            
        } else if ($value == "streamline" || $value == "streamlineonly" || $value == "streamlineeng" || $value == "streamlineengmag") {
            showallconfigfirst();
            $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Fill Credits" || $(this).text() === "Trial Hours" || $(this).text() === "Select Xtream Reseller Group" || $(this).text() === "Do you want to sync Credit to X.C Panel?"|| $(this).text() === "Billing Months"  || $(this).text() === "Packages";
            }).hide();
            jQuery("input[name=\'packageconfigoption[3]\']").parent().hide();
            jQuery("select[name=\'packageconfigoption[12]\']").parent().hide();
            jQuery("select[name=\'packageconfigoption[13]\']").parent().parent().hide(); 
            jQuery("input[name=\'packageconfigoption[18]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[21]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[22]\']").parent().hide();
            var istrail = jQuery("input[name=\'packageconfigoption[5]\']:checked").val();
            if (istrail == "Yes") {
                $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Trial Hours";
                }).show();
                jQuery("input[name=\'packageconfigoption[18]\']").parent().show();

                $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Billing Months";
                }).hide();
                jQuery("input[name=\'packageconfigoption[21]\']").parent().hide();
            }
            else
            {
                if ($("#PayType-OneTime").prop("checked")) 
                    {
                        var productSelect = jQuery("select[name=\'packageconfigoption[2]\']").val();
                        if(productSelect != "reselleraccount" && productSelect != "resellercredits" && productSelect != "superreselleraccount" && productSelect != "addonpackage" )
                        {
                            $("#tblModuleSettings tbody tr td").filter(function () {
                            return $(this).text() === "Billing Months";
                            }).show();
                            jQuery("input[name=\'packageconfigoption[21]\']").attr("type","number");
                            jQuery("input[name=\'packageconfigoption[21]\']").attr("min","0");
                            jQuery("input[name=\'packageconfigoption[21]\']").attr("max","100");
                            jQuery("input[name=\'packageconfigoption[21]\']").parent().show();
                        }
                    }
            }
        } else if ($value == "magdevice" || $value == "engdevice") {   
            showallconfigfirst();
            $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Fill Credits" || $(this).text() === "Trial Hours"  || $(this).text() === "ISP Lock" || $(this).text() === "Select Xtream Reseller Group" || $(this).text() === "Do you want to sync Credit to X.C Panel?" || $(this).text() === "Packages";
             }).hide();
            jQuery("input[name=\'packageconfigoption[3]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[6]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[7]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[19]\']").parent().parent().parent().hide(); 
            jQuery("select[name=\'packageconfigoption[12]\']").parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[13]\']").parent().parent().hide(); 
             jQuery("input[name=\'packageconfigoption[18]\']").parent().hide();
             jQuery("input[name=\'packageconfigoption[22]\']").parent().hide();
            var istrail = jQuery("input[name=\'packageconfigoption[5]\']:checked").val();
            if (istrail == "Yes") 
            {
                $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Trial Hours";
                }).show();
                jQuery("input[name=\'packageconfigoption[18]\']").parent().show();

                $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Billing Months";
                }).hide();
                jQuery("input[name=\'packageconfigoption[21]\']").parent().hide();
            }
            else
            {
                if ($("#PayType-OneTime").prop("checked")) 
                {
                    var productSelect = jQuery("select[name=\'packageconfigoption[2]\']").val();
                    if(productSelect != "reselleraccount" && productSelect != "resellercredits" && productSelect != "superreselleraccount" && productSelect != "addonpackage" )
                    {
                        $("#tblModuleSettings tbody tr td").filter(function () {
                        return $(this).text() === "Billing Months";
                        }).show();
                        jQuery("input[name=\'packageconfigoption[21]\']").attr("type","number");
                        jQuery("input[name=\'packageconfigoption[21]\']").attr("min","0");
                        jQuery("input[name=\'packageconfigoption[21]\']").attr("max","100");
                        jQuery("input[name=\'packageconfigoption[21]\']").parent().show();
                    }
                }
            }
        } else if ($value == "superreselleraccount") {
            showallconfigfirst();
            $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Trial Hours" || $(this).text() === "Billing Months" || $(this).text() === "Packages";
             }).hide();
            jQuery("input[name=\'packageconfigoption[4]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[6]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[8]\']").parent().parent().parent().hide();            
            jQuery("input[name=\'packageconfigoption[19]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[20]\']").parent().parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[9]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[11]\']").parent().parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[12]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[15]\']").parent().parent().parent().hide(); 
            jQuery("input[name=\'packageconfigoption[18]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[21]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[22]\']").parent().hide();
        } else if ($value == "addonpackage") {
            showallconfigfirst();
            $("#tblModuleSettings tbody tr td").filter(function () {
                return $(this).text() === "Trial Hours" || $(this).text() === "Billing Months" || $(this).text() === "Select XUI Super-Reseller Group";
             }).hide();
            jQuery("input[name=\'packageconfigoption[4]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[6]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[8]\']").parent().parent().parent().hide();            
            jQuery("input[name=\'packageconfigoption[19]\']").parent().parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[20]\']").parent().parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[9]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[11]\']").parent().parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[12]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[15]\']").parent().parent().parent().hide(); 
            jQuery("input[name=\'packageconfigoption[18]\']").parent().parent().hide();
            jQuery("input[name=\'packageconfigoption[21]\']").parent().hide();
            jQuery("input[name=\'packageconfigoption[14]\']").parent().parent().hide();
            jQuery("select[name=\'packageconfigoption[13]\']").parent().hide();
        }
    }
    function showallconfigfirst() {
        $("#tblModuleSettings tbody tr td").filter(function () {
            return $(this).text() === "Watch Streams!" || $(this).text() === "Trial Hours" || $(this).text() === "ISP Lock" || $(this).text() === "MAG Portal link" || $(this).text() === "Max Con." || $(this).text() === "Is this Product for Reseller?" || $(this).text() === "Select XUI Super-Reseller Group" || $(this).text() === "Fill Credits" || $(this).text() === "Select Xtream Reseller Group" || $(this).text() === "Packages";
        }).show();

        jQuery("input[name=\'packageconfigoption[3]\']").parent().parent().show();
        jQuery("input[name=\'packageconfigoption[3]\']").parent().show();
        jQuery("input[name=\'packageconfigoption[4]\']").parent().show();

        jQuery("input[name=\'packageconfigoption[5]\']").parent().parent().parent().show();
        jQuery("input[name=\'packageconfigoption[5]\']").parent().parent().show();
        jQuery("input[name=\'packageconfigoption[6]\']").parent().parent().show();

        jQuery("input[name=\'packageconfigoption[7]\']").parent().parent().show();
        jQuery("input[name=\'packageconfigoption[8]\']").parent().show();
        jQuery("input[name=\'packageconfigoption[8]\']").parent().parent().parent().show();
        jQuery("input[name=\'packageconfigoption[19]\']").parent().show();
        jQuery("input[name=\'packageconfigoption[19]\']").parent().parent().parent().show();
        jQuery("input[name=\'packageconfigoption[20]\']").parent().show();
        jQuery("input[name=\'packageconfigoption[20]\']").parent().parent().parent().show();

        jQuery("select[name=\'packageconfigoption[9]\']").parent().parent().show();
        jQuery("select[name=\'packageconfigoption[10]\']").parent().parent().show();
        jQuery("select[name=\'packageconfigoption[10]\']").parent().parent().parent().show();

        jQuery("input[name=\'packageconfigoption[11]\']").parent().parent().show();
        jQuery("select[name=\'packageconfigoption[12]\']").parent().show();
        jQuery("select[name=\'packageconfigoption[12]\']").parent().parent().show();

        jQuery("select[name=\'packageconfigoption[13]\']").parent().parent().parent().show();
        jQuery("select[name=\'packageconfigoption[13]\']").parent().show();
        jQuery("select[name=\'packageconfigoption[13]\']").parent().parent().show();

        jQuery("input[name=\'packageconfigoption[14]\']").parent().show();
        jQuery("input[name=\'packageconfigoption[15]\']").parent().parent().show();
        jQuery("input[name=\'packageconfigoption[15]\']").parent().parent().parent().show();

        jQuery("input[name=\'packageconfigoption[17]\']").parent().parent().show();
        jQuery("input[name=\'packageconfigoption[18]\']").parent().parent().show();
        jQuery("input[name=\'packageconfigoption[18]\']").parent().parent().parent().show(); 

        jQuery("input[name=\'packageconfigoption[22]\']").parent().show();
    }
     function tariffPlan() {
       var bouquetval = jQuery("input[name=\'packageconfigoption[10]\']").val();
       var SecVar = "load-storm-tariff";
       if ($("#conf-dialogXUIONE").is(":data(dialog)"))
        {
            $("#conf-dialogXUIONE").dialog("destroy");
        }
        $("#conf-dialogXUIONE").attr("title", " Bouquets ");
        $("#conf-dialogXUIONE").html("<p style=\"text-align:center\"><img src=\"images/loading.gif\" alt=\"loading...\"/></p>");
        $("#conf-dialogXUIONE").dialog({minWidth: 650}); 
        jQuery.post("../modules/servers/XUIONE/XtreamConfig.php", {stormajax: "load-plans", id: "' . $_REQUEST['id'] . '", conf_id:bouquetval,sectionIs:SecVar }, function (data) {
            $("#conf-dialogXUIONE").html(data);
        });
    }
    function tariffPlanForPcakage() {
       var bouquetval = jQuery("input[name=\'packageconfigoption[22]\']").val();
       var SecVar = "load-package-addon";
       if ($("#conf-dialogXUIONE").is(":data(dialog)"))
        {
            $("#conf-dialogXUIONE").dialog("destroy");
        }
        $("#conf-dialogXUIONE").attr("title", " Bouquets ");
        $("#conf-dialogXUIONE").html("<p style=\"text-align:center\"><img src=\"images/loading.gif\" alt=\"loading...\"/></p>");
        $("#conf-dialogXUIONE").dialog({minWidth: 650}); 
        jQuery.post("../modules/servers/XUIONE/XtreamConfig.php", {stormajax: "load-plans", id: "' . $_REQUEST['id'] . '", conf_id:bouquetval,sectionIs:SecVar}, function (data) {
            $("#conf-dialogXUIONE").html(data);
        });
    } 
</script>
              <div id="conf-dialogXUIONE" title="">
              </div>';
        }
    }
    return $head_return;
}

function XtreamMAGCheckOne($params) {
    if (isset($params['filename']) && !empty($params['filename']) && $params['filename'] == 'cart') {
        if ($params['action'] == 'confproduct') {
            if (isset($_SESSION['cart']['cartsummarypid'])) {
                $xtreamConfig = Capsule::table('mod_XUIOneConfig')->get();
                $returndata = array();
                if (isset($xtreamConfig) && !empty($xtreamConfig)) {
                    foreach ($xtreamConfig as $config) {
                        $returndata[$config->setting] = $config->value;
                    }
                }
                $data = checkproductcustomfieldsOne($_SESSION['cart']['cartsummarypid'], $returndata['checkmagdevice']);
                $username = checkproductcustomfieldsOne($_SESSION['cart']['cartsummarypid'], 'Username');
                $password = checkproductcustomfieldsOne($_SESSION['cart']['cartsummarypid'], 'Password');
                if (isset($returndata['configoption_field_name']) && !empty($returndata['configoption_field_name']))
                    $extra = checkproductconfigoptionOne($_SESSION['cart']['cartsummarypid'], $returndata['configoption_field_name']);
            }
//Extra Connections
            return <<<HTML
                <script type="text/javascript">  
                 $(document).ready(function(){ 
		 $(document).on('ifChecked', '#customfield{$data['id']}', function(event) { 
		  jQuery('#customfield{$username['id']}').parent().hide(1000);
                                                  jQuery('#customfield{$password['id']}').parent().hide(1000);
                                                  jQuery('#inputConfigOption{$extra['id']}').parent().parent().hide(1000);
					});
					$(document).on('ifUnchecked', '#customfield{$data['id']}', function(event) {
						 jQuery('#customfield{$username['id']}').parent().show(1000); 
                                                 jQuery('#customfield{$password['id']}').parent().show(1000);
					}); 
})
 
                </script>
HTML;
        }
    }
}

function checkproductcustomfieldsOne($product_id, $customfieldkey) {
    $config = Capsule::table('tblproducts')
            ->where('servertype', '=', 'XUIONE')
            ->where('id', '=', $product_id)
            ->get();
    if (isset($config) && !empty($config)) {
        $fieldId = Capsule::table('tblcustomfields')
                ->where('fieldname', '=', $customfieldkey)
                ->where('type', '=', 'product')
                ->where('relid', '=', $product_id)
                ->select('tblcustomfields.id')
                ->get();
        return (array) $fieldId[0];
    }
    return'';
}

function checkproductconfigoptionOne($product_id, $configfieldname) {
    $config = Capsule::table('tblproducts')
            ->where('servertype', '=', 'XUIONE')
            ->where('id', '=', $product_id)
            ->get();
    if (isset($config) && !empty($config)) {
        $configuration = Capsule::table('tblproductconfigoptions')
                ->join('tblproductconfiglinks', 'tblproductconfigoptions.gid', '=', 'tblproductconfiglinks.gid')
                ->where('tblproductconfiglinks.pid', '=', $product_id)
                ->where('tblproductconfigoptions.optionname', '=', $configfieldname)
                ->select('tblproductconfigoptions.id')
                ->get();
        return (array) $configuration[0];
    }
    return'';
}

//Check Connection 
function XUIONETestConnectionHooks($productId) {

    $servers = Capsule::table('tblproducts')
            ->join('tblservergroupsrel', 'tblproducts.servergroup', '=', 'tblservergroupsrel.groupid')
            ->join('tblservers', 'tblservergroupsrel.serverid', '=', 'tblservers.id')
            ->where('tblproducts.id', '=', $productId)
            ->select('tblservers.*')
            ->get();
    if (isset($servers) && !empty($servers)) {
        
        foreach ($servers as $server) {
           
            $sqlusername = $server->username;
            $sqlpassword = decrypt($server->password);
            $sqldbname = $server->accesshash;
            $sqlhost = $server->ipaddress;
            list($sqldbname, $sqlport) = explode(':', $sqldbname);
            if (isset($sqlport) && !empty($sqlport))
                $con = mysqli_connect($sqlhost, $sqlusername, $sqlpassword, $sqldbname, $sqlport);
            else
                $con = mysqli_connect($sqlhost, $sqlusername, $sqlpassword, $sqldbname);

// Check connection 
            if (!$con) {
                XUIONE_WHMCSReconnect();
                logModuleCall('XUIONE', 'Check Connection', 'Connection', "Failed to connect to MySQL: " . mysqli_connect_error(), '', '');
                return true;
            }
        }
    }
    return $con;
}

add_hook("ClientAreaFooterOutput", 1, "XtreamMAGCheckOne"); #This hook runs on the load of every client area page 

add_hook("AdminAreaHeadOutput", 1, "XUIONEConfigOption"); #This hook runs on every admin area page load and can accept a return of information to be added to the <head> of your output.


add_hook('AfterConfigOptionsUpgrade', 1, function($vars) {
    include_once('XUIONE.php');
    $serviceid = Capsule::select("SELECT relid FROM tblupgrades WHERE id = '" . $vars['upgradeid'] . "'");
    $command = 'GetClientsProducts';
    $postData = array(
        'serviceid' => $serviceid[0]->relid,
    );

    $results = localAPI($command, $postData, GetAdminIdForLocalAPIOne());
    $getprod = array();
    $nameval = array();
    $name = array();
    $eConnection = array();
    $action = 'configupgrade';
    $selectpid = Capsule::select("SELECT id AS pid , servertype AS moduletype, servergroup AS serverid, configoption1, configoption2,  configoption3, configoption4,  configoption5, configoption6, configoption7, configoption8, configoption9, 
            configoption10, configoption11, configoption12, configoption13, configoption14, configoption15, configoption16, configoption17, configoption18,
            configoption19, configoption20, configoption21, configoption22, configoption23, configoption24 FROM tblproducts WHERE id = '" . $results['products']['product'][0]['pid'] . "'");

    foreach ($results['products']['product'][0]['customfields']['customfield'] as $fields) {
        $name[$fields['name']] = $fields['value'];
    }
    $array1 = array('serviceid' => $results['products']['product'][0]['id'], 'clientid' => $results['products']['product'][0]['clientid'], 'status' => $results['products']['product'][0]['status'], 'username' => $results['products']['product'][0]['username'], 'password' => $results['products']['product'][0]['password']);
    $array2 = config_opt_extraconOne($selectpid[0]);
    $vars = array_merge($array1, $array2);
    $vars['customfields'] = $name;
    $vars['configoptions']['Extra Connections'] = $results['products']['product'][0]['configoptions']['configoption'][0]['value'];
    $vars['action'] = $action;
    XUIONE_ChangePackage($vars);
});

function GetAdminIdForLocalAPIOne() {
    $admin = Capsule::table('tbladmins')
            ->where('roleid', '=', 1)
            ->get();
    $adminUsername = $admin[0]->username;
    return $adminUsername;
}

function config_opt_extraconOne($data) {
    if (is_object($data)) {
        $data = get_object_vars($data);
    }
    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    } else {
        return $data;
    }
}