<?php
if (!defined("WHMCS"))
    die("This file cannot be accessed directly");

use WHMCS\Database\Capsule;

add_hook('EmailPreSend', 1, function ($vars) {
    $merge_fields = [];
    $test = trim($vars['messagename']);
    if ($test == "IPTV Service Details") {

        $HostinData = Capsule::table('tblhosting')->where('id', '=', $vars['relid'])->get();
        $ProductId = $HostinData[0]->packageid;
        $returnData = "";
        $Hostname = Capsule::table('tblproducts')
                ->join('tblservergroupsrel', 'tblproducts.servergroup', '=', 'tblservergroupsrel.groupid')
                ->join('tblservers', 'tblservergroupsrel.serverid', '=', 'tblservers.id')
                ->where('tblproducts.id', $ProductId)
                ->select('tblservers.assignedips')
                ->get();
        if (!empty($Hostname)) {
            $returnData = $Hostname[0]->assignedips;
        }
        $merge_fields['portal_url'] = trim($returnData);
        $merge_fields['service_server_hostname'] = trim($returnData);

        return $merge_fields;
    }
});

add_hook('AcceptOrder', 1, function ($vars) {
    $order = Capsule::table('tblorders')->where('id', '=', $vars['orderid'])->get();
    if (isset($order[0]->invoiceid) && !empty($order[0]->invoiceid)) {
        $admin = Capsule::table('tbladmins')
                ->where('roleid', '=', 1)
                ->get();
        $adminUsername = $admin[0]->username;
        $paymentmethodmethod = 'GetPaymentMethods';
        $postData = array(
        );
        $paymentmethod = localAPI($paymentmethodmethod, $postData, $adminUsername);
        $command = 'AddInvoicePayment';
        $postData = array(
            'invoiceid' => $order[0]->invoiceid,
            'transid' => 'Test' . XtreamCodeGenrateRandomui(),
            'gateway' => $paymentmethod['paymentmethods']['paymentmethod'][0]['module'],
        );
        $results = localAPI($command, $postData, $adminUsername);
        logModuleCall('XUIONE', 'Accept Order', 'Inovice Id:' . $order[0]->invoiceid, $results, '', '');
    }
});
add_hook('ClientAreaPage', 1, function ($vars) {
    if (isset($_SESSION['uid']) && !empty($_SESSION['uid'])) {
        $testing = '';
        $clientdata = Capsule::table('tblclients')->where('id', '=', $_SESSION['uid'])->get();
        if (isset($clientdata[0]->groupid) && !empty($clientdata[0]->groupid)) {
            $clientgrop = Capsule::table('tblclientgroups')->where('id', '=', $clientdata[0]->groupid)->get();
            if ($clientgrop[0]->groupname == 'Reseller' || $clientgrop[0]->groupname == 'Super-Reseller') {
                $productscount = Capsule::table('tblproducts')
                        ->select(Capsule::raw('*'))
                        ->where('servertype', '=', 'XUIONE')
                        ->where('configoption2', '=', 'reselleraccount')
                        ->orwhere('configoption2', '=', 'superreselleraccount')
                        ->count();
                if (isset($productscount) && !empty($productscount)) {
                    $products = Capsule::table('tblproducts')
                            ->select(Capsule::raw('*'))
                            ->where('servertype', '=', 'XUIONE')
                            ->where('configoption2', '=', 'reselleraccount')
                            ->orwhere('configoption2', '=', 'superreselleraccount')
                            ->get();
                    foreach ($products as $product) {
                        $results = xtream_getClientProductsui($_SESSION['uid'], $product->id);
                        if ($results['result'] == "success") {
                            if (!empty($results['products'])) {
                                foreach ($results['products']['product'] as $ProductDt) {
                                    if ($vars['filename'] == 'clientarea' && $vars['clientareaaction'] != 'addfunds' && $vars['clientareaaction'] != 'services' && $vars['clientareaaction'] != 'invoices' && $vars['clientareaaction'] != 'productdetails' && $ProductDt['status'] == 'Active') {
                                        $_SESSION['producttype'] = 'Xtream';
                                        if ($vars["action"] == "details" || $vars["action"] == "creditcard" || $vars["action"] == "changepw") {
                                            //no redirection
                                        } else {
                                            header('location:index.php?m=xtreamuionedashboard');
                                            exit;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
});

add_hook('ClientAreaHeaderOutput', 1, function ($vars) {
    if (isset($_SESSION['uid']) && !empty($_SESSION['uid'])) {
        $clientdata = Capsule::table('tblclients')->where('id', '=', $_SESSION['uid'])->get();
        if (isset($clientdata[0]->groupid) && !empty($clientdata[0]->groupid)) {
            $clientgrop = Capsule::table('tblclientgroups')->where('id', '=', $clientdata[0]->groupid)->get();
            if ($clientgrop[0]->groupname == 'Reseller' || $clientgrop[0]->groupname == 'Super-Reseller') {
                if ($_SESSION['producttype'] == 'Xtream') {
                    $product = Capsule::table('tblproducts')->where('configoption2', '=', 'reselleraccount')->orwhere('configoption2', '=', 'superreselleraccount')->select('id')->get();
                    $resellerproducts = Capsule::table('tblhosting')->where('userid', '=', $_SESSION['uid'])->select('packageid')->get();
                    foreach ($resellerproducts as $resellerproduct) {
                        $resellerproductid[] = $resellerproduct->packageid;
                    }
                    foreach ($product as $productids) {
                        if (in_array($productids->id, $resellerproductid)) {
                            $productid = $productids->id;
                        }
                    }
                    if (isset($productid) && !empty($productid)) {


                        $returndata = array();
                        $xtreamConfig = Capsule::table('mod_XUIOneConfig')->get();
                        if (isset($xtreamConfig) && !empty($xtreamConfig)) {
                            foreach ($xtreamConfig as $config) {
                                $returndata[$config->setting] = $config->value;
                            }
                        }
                        if ($returndata['syncredit'] == 'on') {
                            $xtreamConfig = Capsule::table('mod_XUIOneConfig')->get();
                            $returndata = array();
                            if (isset($xtreamConfig) && !empty($xtreamConfig)) {
                                foreach ($xtreamConfig as $config) {
                                    $returndata[$config->setting] = $config->value;
                                }
                            }
                            $servers = Capsule::table('tblproducts')
                                    ->join('tblservergroupsrel', 'tblproducts.servergroup', '=', 'tblservergroupsrel.groupid')
                                    ->join('tblservers', 'tblservergroupsrel.serverid', '=', 'tblservers.id')
                                    ->where('tblproducts.id', '=', $productid)
                                    ->select('tblservers.*', 'tblproducts.configoption17')
                                    ->get();
                            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 (mysqli_connect_errno()) {
                                    return "Failed to connect to MySQL: " . mysqli_connect_error();
                                }
                                $email = $clientdata[0]->email;
                                $resultcredits = mysqli_query($con, "SELECT credits FROM users WHERE email='$email'");
                                $credits = mysqli_fetch_assoc($resultcredits);
                                if ($credits['credits'] != $clientdata[0]->credit) {
                                    $leftcredits = $credits['credits'] - $clientdata[0]->credit;
                                    $type = ($leftcredits < 0) ? 'remove' : 'add';
                                    $AddCredit = 'AddCredit';
                                    $postData = array(
                                        'clientid' => $_SESSION['uid'],
                                        'description' => "Difference in Credits X.C cr: " . $credits['credits'] . " WHMCS cr: " . $clientdata[0]->credit,
                                        'amount' => abs($leftcredits),
                                        'type' => $type
                                    );
                                    $admin = Capsule::table('tbladmins')
                                            ->where('roleid', '=', 1)
                                            ->get();
                                    $adminUsername = $admin[0]->username;
                                    $resultsCredit = localAPI($AddCredit, $postData, $adminUsername);
                                    $html = 'Number of Credit Found in X.C panel : ' . $credits['credits'] . '<br>Number of Credit in WHMCS : ' . $clientdata[0]->credit . '<br>' . 'Result : ' . $resultsCredit;
                                    if ($resultsCredit['result'] == 'success') {
                                        logModuleCall('XUIONE', 'Add Credit', 'Email Address : ' . $email, $html, '', '');
                                    } else {
                                        logModuleCall('XUIONE', 'Add Credit', 'Email Address : ' . $email, $html, '', '');
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if ($_SESSION['xtreamuserid'] == $_SESSION['uid']) {
        ?>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript">
            var localSessionClientId = <?php echo ($_SESSION['xtreamuserid'] != "") ? $_SESSION['xtreamuserid'] : "''"; ?>;
            var loginclientval = sessionStorage.getItem("loginclientval");
            var loginsecret = sessionStorage.getItem("loginsecret");
            if (loginclientval != "" && loginclientval != null)
            {
                if (localSessionClientId != loginclientval)
                {
                    $.ajax({
                        method: "POST",
                        url: "modules/addons/xtreamuionedashboard/lib/Client/logoutajax.php",
                        data: {session: 'Changextreamuserid', clientid: loginclientval, loginhashpass: loginsecret},
                        success: function (response)
                        {
                            if (response == 'yes') {
                                sessionStorage.clear();
                                window.location = "clientarea.php";

                            }
                        }
                    });
                }
            }
        </script>   
        <?php
    }
});
//UpdateInvoiceTotal
//InvoiceCreated
include_once __DIR__ . DIRECTORY_SEPARATOR . 'functions.php';

add_hook('InvoiceCreated', 1, function ($vars) {
    if (empty($_SESSION['adminid']) && empty($_SESSION['uid'])) {
        $config = Capsule::table('mod_XUIOneConfig')->where('setting', '=', 'creditapply')->get();
        if (isset($config) && !empty($config)) {
            if (isset($config[0]->value) && $config[0]->value == 'on') {
                $admin = Capsule::table('tbladmins')
                        ->where('roleid', '=', 1)
                        ->get();
                $adminUsername = $admin[0]->username;
                $getinvoice = localAPI('GetInvoice', array('invoiceid' => $vars['invoiceid']), $adminUsername);
                if ($getinvoice['status'] != 'Paid') {
                    //Check if client is related to Reseller 
                    $userid = $getinvoice['userid'];
                    $checkdetials = Capsule::table('mod_XUIAffs_clients')
                            ->where('clientid', '=', $userid)
                            ->get();
                    if (isset($checkdetials) && !empty($checkdetials)) {
                        //Get Affiliates details  
                        $getAffiliates = Capsule::table('tblaffiliates')
                                ->where('id', '=', $checkdetials[0]->affiliatesid)
                                ->get();
                        if (isset($getAffiliates) && !empty($getAffiliates)) {
                            global $CONFIG;
                            $resellerid = $getAffiliates[0]->clientid;
                            if (isset($CONFIG['Reseller' . $resellerid]) && !empty($CONFIG['Reseller' . $resellerid])) {
                                $checked = $CONFIG['Reseller' . $resellerid];
                            }
                            if ($checked == 'Enable') {
                                $credit = Capsule::table('tblclients')
                                        ->select('credit', 'firstname', 'lastname', 'email')
                                        ->where('id', '=', $getAffiliates[0]->clientid)
                                        ->get();
                                $admin = Capsule::table('tbladmins')
                                        ->where('roleid', '=', 1)
                                        ->get();
                                $adminUsername = $admin[0]->username;
                                $affdetails = $credit[0];
                                $add_credit = $getinvoice['total'];
                                $AddCredit = 'AddCredit';
                                $postData = array(
                                    'clientid' => $userid,
                                    'description' => 'Added funds by ' . $affdetails->firstname . ' ' . $affdetails->lastname,
                                    'amount' => $add_credit,
                                );
                                $resultsCredit = localAPI($AddCredit, $postData, $adminUsername);
                                if ($resultsCredit['result'] == 'success') {
                                    Capsule::table('tblcredit')->insert(
                                            ['clientid' => $getAffiliates[0]->clientid, 'date' => date('Y-m-d'), 'description' => 'Add Credit to Client - ' . $userid, 'amount' => -$add_credit]
                                    );
                                    $removeCredit = $affdetails->credit - $add_credit;
                                    Capsule::table('tblclients')
                                            ->where('id', '=', $getAffiliates[0]->clientid)
                                            ->update(
                                                    [
                                                        'credit' => $removeCredit,
                                                    ]
                                    );
                                    $command = 'ApplyCredit';
                                    $postData = array(
                                        'invoiceid' => $vars['invoiceid'],
                                        'amount' => $add_credit,
                                    );
                                    $results = localAPI($command, $postData, $adminUsername);
                                    logModuleCall('Xtream Dashboard', 'ApplyCredit', $postData, $results, '', '');
                                }
                            }
                        }
                    }
                }
            }
        }
    }
});
/* ------------------------------------------------ */



/* ------------------------------------------------ */

function XtreamCheckMAGexistsui($params) {
    #Check Stalker MAC exists
    $cart = $_SESSION['cart'];
    foreach ($cart['products'] as $product) {
        $servers = Capsule::table('tblproducts')
                ->join('tblservergroupsrel', 'tblproducts.servergroup', '=', 'tblservergroupsrel.groupid')
                ->join('tblservers', 'tblservergroupsrel.serverid', '=', 'tblservers.id')
                ->where('tblproducts.id', '=', $product['pid'])
                ->select('tblservers.*')
                ->get();
        $xtreamConfig = Capsule::table('mod_XUIOneConfig')->get();
        $returndata = array();
        if (isset($xtreamConfig) && !empty($xtreamConfig)) {
            foreach ($xtreamConfig as $config) {
                $returndata[$config->setting] = $config->value;
            }
        }
        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 (mysqli_connect_errno()) {
                return "Failed to connect to MySQL: " . mysqli_connect_error();
            }
            $fieldid = Capsule::table('tblcustomfields')
                    ->where('fieldname', $returndata['custom_field_mag'])
                    ->where('type', 'product')
                    ->where('relid', $product['pid'])
                    ->get();
            if (isset($fieldid) && !empty($fieldid)) {
                $newmac = $product['customfields'][$fieldid[0]->id];
                if (isset($newmac) && !empty($newmac)) {
# Inserting Now New User into 
// First checking if user already exist with reqeuest username  
                    $resultmag_devices = mysqli_query($con, "SELECT * FROM mag_devices WHERE mac='" . base64_encode($newmac) . "'");
                    if (mysqli_num_rows($resultmag_devices) != 0) {
                        logModuleCall('Xtream Integration', 'Check Mac-Address Exists : ' . $newmac, $newmac, 'MAC Already Exists!', '', '');
                        $return[] = "MAC address already in use";
                    }
                }
            }
            $resellerid = Capsule::table('tblcustomfields')
                    ->where('fieldname', 'Reseller Email')
                    ->where('type', 'product')
                    ->where('relid', $product['pid'])
                    ->get();
            if (isset($resellerid[0]->id) && !empty($resellerid[0]->id)) {
                $email = $product['customfields'][$resellerid[0]->id];
                $result = mysqli_query($con, "SELECT username FROM users WHERE email='$email'");
                if (!$result) {
                    $radiussqlerror = mysqli_error($con);
                    XtreamCode_WHMCSReconnectOPui();
                    logModuleCall('XUIONE', 'Check Reseller Exists', 'Email Address : ' . $email, "XUIONE Database Query Error: " . $radiussqlerror, '', '');
                    $return[] = "Error in Connection with Server. Please contach Administrator";
                }
                if (mysqli_num_rows($result) == 0) {
                    $return[] = "Reseller Email Address doesn't exists. Please check and try again.";
                }
            }
        }
        return $return;
    }
}

function XtreamCodeGenrateRandomui($length = 7, $add_dashes = false, $available_sets = 'lud') {
    $sets = array();
    if (strpos($available_sets, 'l') !== false)
        $sets[] = 'abcdefghjkmnpqrstuvwxyz';
    if (strpos($available_sets, 'u') !== false)
        $sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ';
    if (strpos($available_sets, 'd') !== false)
        $sets[] = '23456789';
    $all = '';
    $password = '';
    foreach ($sets as $set) {
        $password .= $set[array_rand(str_split($set))];
        $all .= $set;
    }
    $all = str_split($all);
    for ($i = 0; $i < $length - count($sets); $i++)
        $password .= $all[array_rand($all)];
    $password = str_shuffle($password);
    if (!$add_dashes)
        return $password;
    $dash_len = floor(sqrt($length));
    $dash_str = '';
    while (strlen($password) > $dash_len) {
        $dash_str .= substr($password, 0, $dash_len) . '-';
        $password = substr($password, $dash_len);
    }
    $dash_str .= $password;
    return $dash_str;
}

add_hook("ShoppingCartValidateProductUpdate", 1, "XtreamCheckMAGexistsui");
////Run After a Cron Job Completed
//add_hook('AfterCronJob', 1, function() { 
//}); 
add_hook('InvoicePaid', 1, function ($vars) {
    if (isset($_SESSION['clientID']) && !empty($_SESSION['clientID'])) {
        $command = 'GetInvoice';
        $postData = array(
            'invoiceid' => $vars['invoiceid'],
        );
        $admin = Capsule::table('tbladmins')
                ->where('roleid', '=', 1)
                ->get();
        $adminUsername = $admin[0]->username;

        $results = localAPI($command, $postData, $adminUsername);
        $credit = $results['total'];
        if ($_SESSION['clientID'] == $results['userid']) {
            $affdetails = CheckAffCreditOPui();
            $removeCredit = $affdetails->credit - $credit;
            RemoveWHMCSCreditOPui($removeCredit);
            $con = XtreamDashboard_testconnectionOPui();
            RemoveXtreamCreditOPui($credit, $con);
            WHMCSdoLoginui();
        }
    }
});

function XtreamCode_WHMCSReconnectOPui() {
    require( ROOTDIR . "/configuration.php" );
    $whmcsmysql = mysqli_connect($db_host, $db_username, $db_password, $db_name);
}

function WHMCSResellerServerIdOPui($account) {
    $serverid = 0;
    $products = Capsule::table('tblproducts')
            ->select(Capsule::raw('*'))
            ->where('servertype', '=', 'XUIONE')
            ->where('configoption2', '=', $account)
            ->get();
    foreach ($products as $productdb) {
        $productids[] = $productdb->id;
    }
    $command = 'GetClientsProducts';
    $postData = array(
        'clientid' => $_SESSION['resellerid'],
        'stats' => true,
    );
    $admin = Capsule::table('tbladmins')
            ->where('roleid', '=', 1)
            ->get();
    $adminUsername = $admin[0]->username;
    $results = localAPI($command, $postData, $adminUsername);
    foreach ($results['products']['product'] as $product) {
        if (in_array($product['pid'], $productids)) {
            $serverid = $product['serverid'];
        }
    }
    return $serverid;
}

function XtreamDashboard_testconnectionOPui() {
    /* CreateConnection */
    $clientdata = Capsule::table('tblclients')->where('id', '=', $_SESSION['resellerid'])->get();
// Get common module parameters 
    $clientgrop = Capsule::table('tblclientgroups')->where('id', '=', $clientdata[0]->groupid)->get();
    if ($clientgrop[0]->groupname == 'Reseller') {
        $account = 'reselleraccount';
    } elseif ($clientgrop[0]->groupname == 'Super-Reseller') {
        $account = 'superreselleraccount';
    }
    $serverid = WHMCSResellerServerIdOPui($account);
    $serverdetails = Capsule::table('tblservers')->where('id', '=', $serverid)->get();
    foreach ($serverdetails 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 (mysqli_connect_errno()) {
            logModuleCall('XUIONE', 'Check Connection', 'Connection', "Failed to connect to MySQL: " . mysqli_connect_error(), '', '');
            return true;
        }
    }
    return $con;
}

function WHMCSdoLoginui() {
    $_SESSION['uid'] = $_SESSION['xtreamuserid'];
    $_SESSION['upw'] = $_SESSION['xtreampasswordhash'];
}

function CheckAffCreditOPui() {
    $credit = Capsule::table('tblclients')
            ->select('credit', 'firstname', 'lastname', 'email')
            ->where('id', '=', $_SESSION['resellerid'])
            ->get();
    return $credit[0];
}

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

function RemoveXtreamCreditOPui($amount, $con) {
    $xtreamConfig = Capsule::table('mod_XUIOneConfig')->get();
    $returndata = array();
    if (isset($xtreamConfig) && !empty($xtreamConfig)) {
        foreach ($xtreamConfig as $config) {
            $returndata[$config->setting] = $config->value;
        }
    }
    $tblclients = Capsule::table('tblclients')->where('id', $_SESSION['resellerid'])->select('email')->get();
    $email = $tblclients[0]->email;
    $result = mysqli_query($con, "SELECT username,credits FROM users WHERE email='" . $tblclients[0]->email . "'");
    if (!$result) {
        $radiussqlerror = mysqli_error($con);
        XtreamCode_WHMCSReconnectOPui();
        logModuleCall('XUIONE', 'Check Reseller Exists', 'Email Address : ' . $email, "XUIONE Database Query Error: " . $radiussqlerror, '', '');
        return "XUIONE Database Query Error: " . $radiussqlerror;
    }
    if (mysqli_num_rows($result) > 0) {
        if ($returndata['syncredit'] == 'on') {
            $resellerdata = mysqli_fetch_assoc($result);
            $remaningamount = $resellerdata['credits'] - $amount;
            $update = mysqli_query($con, "UPDATE users SET credits ='$remaningamount' WHERE email='$email'");
            if (!$update) {
                $radiussqlerror = mysqli_error($con);
                XtreamCode_WHMCSReconnectOPui();
                logModuleCall('XUIONE', 'Error Add Credits', 'Email Address : ' . $email, "XUIONE Database Query Error: " . $radiussqlerror, '', '');
                return "XUIONE Database Query Error: " . $radiussqlerror;
            }
        }
    }
}

function RemoveWHMCSCreditOPui($credit) {
    $updatedUserCount = Capsule::table('tblclients')
            ->where('id', '=', $_SESSION['resellerid'])
            ->update(
            [
                'credit' => $credit,
            ]
    );
    return true;
}
