<?php
/*
*   Whitelabel Proxy 1.0.9
*/

use WHMCS\Database\Capsule as DB;
use WHMCS\Module\Addon\ProxyCheap\APIHelper;
use WHMCS\Module\Addon\ProxyCheap\BillingCyclesHelper;
use WHMCS\Module\Server\ProxyCheap\ClientAreaActions;
use Carbon\Carbon;

function proxycheap_ConfigOptions($params)
{
    $proxylist = (new WHMCS\Module\Addon\ProxyCheap\Commands\V2\GetProxyTypes($apiparams, []))->get();

$types = [];

foreach( (array)$proxylist->services as $proxy)
{
    if($proxy->plans)
    {
        foreach((array)$proxy->plans as $plan)
        {

            $types[$proxy->id.'|'.$plan->id] = $proxy->label.' - '.$plan->label;
        }    
    }
    else
    {
        if(strpos(strtolower($proxy->label), 'retired') !== false) continue;
        $types[$proxy->id] = $proxy->label;
    }
    
}
$types['ADDON_BANDWIDTH'] = 'Bandwidth (Addon)';
$types['ADDON_EXTENSION'] = 'Extension Period (Addon)';

    return [
        "serviceType" => [
            "FriendlyName" => "Service Type",
            "Type" => "dropdown",
            "Options" => $types,
            "Description" => "",
            "Default" => "DATACENTER",
        ],

    ];
}

function proxycheap_MetaData()
{
    return array(
        'DisplayName' => 'Proxy-Cheap',
        'RequiresServer' => false
    );
}


function proxycheap_CreateAccount($params)
{
    //echo('<pre>'); var_dump(BillingCyclesHelper::getMonthsByCycle($params['model']->billingcycle), $params); exit;
    if ($params['Service Type'] == 'ADDON_BANDWIDTH') {
        if ($params['qty'] < 1) {
            return 'Wrong quantity';
        }

        $bandwidthToAdd = $params['qty'];

        $apiparams = APIHelper::getApiCredentials();

        $input = [];
        $input['proxy_account_id'] = $params['password'];

        $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetProxyInfo($apiparams, $input))->get();
        logModuleCall('ProxyCheap', 'GET orders/' . $input['proxy_account_id'] . '/proxies', $input, $proxydetails);

        foreach ($proxydetails as $proxy) {

            $buybwRequest = (new WHMCS\Module\Addon\ProxyCheap\Commands\AddBandwidth($apiparams, ['bandwidth' => $bandwidthToAdd, 'id' => $proxy->id]))->post();
            logModuleCall('ProxyCheap', 'POST proxies/' . $proxy->id . '/buy-bandwidth', [], $buybwRequest);
        }
        return 'success';
    } elseif ($params['Service Type'] == 'ADDON_EXTENSION') {
        if ($params['qty'] < 1) {
            return 'Wrong quantity';
        }

        $monthsToAdd = $params['qty'];

        $apiparams = APIHelper::getApiCredentials();

        if ($params['customfields']['proxyid']) {
            $payload=['periodInMonths' => $monthsToAdd, 'id' => trim($params['customfields']['proxyid'])];
            $buybwRequest = (new WHMCS\Module\Addon\ProxyCheap\Commands\ExtendPeriod($apiparams, $payload))->post();
            logModuleCall('ProxyCheap', 'POST proxies/' . $params['customfields']['proxyid'] . '/extend-period', $payload, $buybwRequest);

            //Update due date from API
            $dateToUpdate = Carbon::parse($buybwRequest->expiresAt)->format('Y-m-d');
            $params['model']['service']->nextduedate = $dateToUpdate;
            $params['model']['service']->save();

            return 'success';
        }
        return 'Cannot create. Proxy ID Custom field is empty';
    }
    
    $serviceId = strpos($params['configoption1'], '|') !== false ? explode('|', $params['configoption1'])[0] : $params['configoption1'];
    $planId = strpos($params['configoption1'], '|') !== false ? explode('|', $params['configoption1'])[1] : null;

    $input2 = ['planId' => $planId, 'service' => $serviceId];
    $readDetailsCommand = (new WHMCS\Module\Addon\ProxyCheap\Commands\V2\OrderConfiguration(APIHelper::getApiCredentials(), $input2))->post();

    $input = $params['customfields'];

    //handle cases where bandwidth is limited
    if($readDetailsCommand->metadata->availability->traffic && $readDetailsCommand->metadata->availability->traffic->min == $readDetailsCommand->metadata->availability->traffic->max)
    {
        $input['traffic'] = $readDetailsCommand->metadata->availability->traffic->min;
    }


    $input = array_merge($input, $params['configoptions'], $input2);

    if($readDetailsCommand->metadata->visibility->periods !== false)
    {
        $input['AutoExtend'] = ['isEnabled' => false];
        $input['period'] = ['unit' => 'months', 'value' => BillingCyclesHelper::getMonthsByCycle($params['model']->billingcycle)];
    }

    
    if (!BillingCyclesHelper::getMonthsByCycle($params['model']->billingcycle)) {
        return 'Invalid billing cycle';
    }

    if($input['packageId'])
    {
        $input['packageId'] = (string) $input['packageId'];
    }

    $apiparams = APIHelper::getApiCredentials();
    $createAccountCommand = (new WHMCS\Module\Addon\ProxyCheap\Commands\V2\Execute($apiparams, $input))->post();

    logModuleCall('ProxyCheap', 'POST order/v2/execute', $input, $createAccountCommand);

    if ($createAccountCommand) {
        $params["model"]->serviceProperties->save(['password' => $createAccountCommand->id]);
        //save order id in password field

        if($params['model']->nextduedate !== date('Y-m-d'))
        {
            $date = new DateTime($params['model']->nextduedate);
            $monthsToAdd = BillingCyclesHelper::getMonthsByCycle($params['model']->billingcycle);
            $date->modify("+$monthsToAdd months");
            $newDate = $date->format("Y-m-d");

            \WHMCS\Service\Service::where("id", $params['serviceid'])->update(['nextduedate' =>  $newDate]);
        }

        return "success";
    }
    return 'Some input data are invalid.';
}

function proxycheap_AdminServicesTabFields($params)
{

    $apiCredentials = APIHelper::getApiCredentials();
$WHMCSURL =  \WHMCS\Config\Setting::getValue("systemurl");
$connectScript = <<<JS
            <script>
            $('#proxy_connect').click(function () {
                // Wywołanie GET do API
                $.ajax({
                    url: '{$WHMCSURL}index.php?m=proxycheap&json=1&c=GetProxyById&proxyid='+$('#proxy_id').val(),
                    type: 'GET',
                    success: function (data) {
                        // Obsługa sukcesu
                        if(data?.metadata?.orderId)
                        { 
                            jQuery('#inputPassword').val(data.metadata.orderId);
                             jQuery.growl.notice(
                                {
                                    title: 'Success!',
                                    message: 'New order has been set'
                                }
                            );
                        }
                        else
                        {
                                jQuery.growl.error(
                                {
                                    title: 'Error',
                                    message: data.message
                                }
                            );
                        }

                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(data)
                    }
                });
            });
                </script>
JS;                
        $return['Connect service'] = '<input type="text" id="proxy_id" name="proxy_id" placeholder="Input proxy ID here" class="form-control input-inline input-200"><button type="button" id="proxy_connect" class="btn btn-success">Connect</button>'.$connectScript;
    if ($apiCredentials && $params['password'] && strpos($params['password'], '-') !== false) {

        $input = [];
        $input['proxy_account_id'] = $params['password'];
        $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetProxyInfo($apiCredentials, $input))->get();
        
       // $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetOrder($apiCredentials, $input))->get();
//\WHMCS\Service\Service::where("id", $params['serviceid'])->update(['nextduedate' => Carbon::parse($proxydetails[0]->expiresAt)->format('Y-m-d')]);
//echo  ('<pre>'); var_dump($params['serviceid'], $proxydetails); exit;
        if ($proxydetails) {
            foreach ($proxydetails as $proxy) {
                $proxyKey = 'Proxy ' . $proxy->id;
                $auth = $proxy->authentication->whitelistedIps ? 'Whitelisted IP:' . implode(', ', $proxy->authentication->whitelistedIps) : 'Username: ' . $proxy->authentication->username . ' Password:' . $proxy->authentication->password;
                $conn = $proxy->connection->publicIp ? 'Access IP: ' . $proxy->connection->publicIp . ':' . $proxy->connection->httpPort . ' ' . ($proxy->connection->socks5Port ? 'SOCKS5 Port: ' . $proxy->connection->socks5Port : '') : '';
                $expires = 'Expiration Date: <strong>' . ( fromMySQLDate($proxy->expiresAt, 1) === '00/00/0000' ? 'Never' : fromMySQLDate($proxy->expiresAt, 1) ). '</strong>';
                $return[$proxyKey] =  $proxy->status . '<br />' . $proxy->networkType . '<br />' . $auth . '<br />' . $conn . ' ' . $expires;
            }
        }
        
       
    }
     return $return;
}


function proxycheap_SuspendAccount($params)
{
    if ($params['Service Type'] == 'ADDON_BANDWIDTH') {
        return 'This action is not supported for addon.';
    }

    $apiparams = APIHelper::getApiCredentials();

    $input = [];
    $input['proxy_account_id'] = $params['password'];

    $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetProxyInfo($apiparams, $input))->get();

    logModuleCall('ProxyCheap', 'GET orders/' . $input['proxy_account_id'] . '/proxies', $input, $proxydetails);

    foreach ($proxydetails as $proxy) {

        $autoextendRequest = (new WHMCS\Module\Addon\ProxyCheap\Commands\AutoExtend($apiparams, ['autoextend' => 'disable', 'id' => $proxy->id]))->post();
        logModuleCall('ProxyCheap', 'POST proxies/' . $proxy->id . '/auto-extend/disable', [], $autoextendRequest);
    }
    return "success";
}

function proxycheap_UnsuspendAccount($params)
{
    if ($params['Service Type'] == 'ADDON_BANDWIDTH') {
        return 'success';
    }
    $apiparams = APIHelper::getApiCredentials();

    $input = [];
    $input['proxy_account_id'] = $params['password'];

    $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetProxyInfo($apiparams, $input))->get();

    logModuleCall('ProxyCheap', 'GET orders/' . $input['proxy_account_id'] . '/proxies', $input, $proxydetails);

    foreach ($proxydetails as $proxy) {

        $autoextendRequest = (new WHMCS\Module\Addon\ProxyCheap\Commands\AutoExtend($apiparams, ['autoextend' => 'enable', 'id' => $proxy->id]))->post();
        logModuleCall('ProxyCheap', 'POST proxies/' . $proxy->id . '/auto-extend/enable', [], $autoextendRequest);
    }
    return "success";
}

function proxycheap_TerminateAccount($params)
{
    if ($params['Service Type'] == 'ADDON_BANDWIDTH') {
        return 'success';
    }

    $apiparams = APIHelper::getApiCredentials();

    $input = [];
    $input['proxy_account_id'] = $params['password'];

    $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetProxyInfo($apiparams, $input))->get();

    logModuleCall('ProxyCheap', 'GET orders/' . $input['proxy_account_id'] . '/proxies', $input, $proxydetails);
    foreach ($proxydetails as $proxy) {

        $autoextendRequest = (new WHMCS\Module\Addon\ProxyCheap\Commands\AutoExtend($apiparams, ['id' => $proxy->id, 'autoextend' => 'disable']))->post();
        logModuleCall('ProxyCheap', 'POST proxies/' . $proxy->id . '/disable', [], $autoextendRequest);

        $autoextendRequest = (new WHMCS\Module\Addon\ProxyCheap\Commands\Cancel($apiparams, ['id' => $proxy->id]))->post();
        logModuleCall('ProxyCheap', 'POST proxies/' . $proxy->id . '/cancel', [], $autoextendRequest);
    }
    return "success";
}

function proxycheap_Renew($params)
{
    if ($params['Service Type'] == 'ADDON_BANDWIDTH') {
        return 'success';
    }

    //proxycheap_UnsuspendAccount($params);
    $apiparams = APIHelper::getApiCredentials();

    $input = [];
    $input['proxy_account_id'] = $params['password'];

    $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetProxyInfo($apiparams, $input))->get();

    logModuleCall('ProxyCheap', 'GET orders/' . $input['proxy_account_id'] . '/proxies', $input, $proxydetails);
    foreach ($proxydetails as $proxy) {

        $extendRequest = (new WHMCS\Module\Addon\ProxyCheap\Commands\ExtendPeriod($apiparams, ['id' => $proxy->id, 'periodInMonths' =>  BillingCyclesHelper::getMonthsByCycle($params['model']->billingcycle)]))->post();
        logModuleCall('ProxyCheap', 'POST proxies/' . $proxy->id . '/extend-period', [], $extendRequest);
    }
    return "success";
}

function proxycheap_ClientArea($params)
{
    $apiparams = APIHelper::getApiCredentials();

    $input = [];
    $input['proxy_account_id'] = $params['password'];

    if ($_GET['a'] === 'whitelist') {
        if ($_GET['act'] === 'save') {
            return ClientAreaActions::saveWhitelist($apiparams);
        }
        $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetProxyInfo($apiparams, $input))->get();
        $proxy =  array_column($proxydetails, null, 'id')[$_GET['proxy_id']];
        return [
            'templatefile' => 'proxycheap-whitelist',
            'vars' => [
                'proxy' => $proxy,
            ]
        ];
    } elseif ($_GET['a'] === 'extend') {
        if ($_GET['act'] === 'save') {
            return ClientAreaActions::saveExtend($params['packageid']);
        }
        return [
            'templatefile' => 'proxycheap-extend',
            'vars' => [
                'proxy_id' => (int)trim($_GET['proxy_id']),
            ]
        ];
    } elseif ($_GET['a'] === 'buybw') {
        if ($_GET['act'] === 'save') {
            return ClientAreaActions::saveBuybw($params['packageid']);
        }
        return [
            'templatefile' => 'proxycheap-buybw',
            'vars' => [
                'proxy_id' => (int)trim($_GET['proxy_id']),
            ]
        ];
    }
    elseif($_GET['a'] == 'switchprotocol')
    {
        $proxy_id = (int) $_GET['proxy_id'];
        $newProtocol = $_GET['p'];
        if($proxy_id && $newProtocol && in_array($newProtocol, ['HTTP', 'SOCKS5']))
        {
            $proxyOneInfo = (array)(new WHMCS\Module\Addon\ProxyCheap\Commands\SetProxyProtocol($apiparams, ['proxy_id' => $proxy_id]))->post($newProtocol);
         }


    }
   elseif($_GET['a'] == 'changeauth')
    {
        $proxy_id = (int) $_GET['proxy_id'];
        $auths = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetAvailableAuths($apiparams, ['proxy_id' => $proxy_id]))->get();

        if ($_GET['act'] === 'save') {
            return ClientAreaActions::saveAuth($apiparams);
        }
        
        $ipWhitelist = [];
        if($auths->currentAuthenticationType === 'IP_WHITELIST')
        {
            $ipWhitelist = (new WHMCS\Module\Addon\ProxyCheap\Commands\WhitelistIP($apiparams, ['proxy_id' => $proxy_id]))->get();
        }
      
        return [
            'templatefile' => 'proxycheap-whitelist',
            'vars' => [
                'proxy' => $proxy,
                'auths' => (array)$auths,
                'ipWhitelist' => (array)$ipWhitelist,
                'strings' => ['IP_WHITELIST' => 'IP Whitelist', 'USERNAME_PASSWORD' => 'Username & Password'],
                'currentAuthType' => isset($auths->currentAuthenticationType) ? $auths->currentAuthenticationType : null,
            ]
        ];
    }
    elseif($_GET['a'] == 'regeneratecredentials')
    {
     
        $proxy_id = (int) $_GET['proxy_id'];
        $RegenerateCredentials = (new WHMCS\Module\Addon\ProxyCheap\Commands\RegenerateCredentials($apiparams, ['proxy_id' => $proxy_id]))->post();
        if($RegenerateCredentials)
        {
            header("Location: ".$_SERVER['HTTP_REFERER']);
            exit;
        }
    }
    elseif($_GET['a'] == 'rotate_ip')
    {
     
        $proxy_id = (int) $_GET['proxy_id'];
        $RegenerateCredentials = (new WHMCS\Module\Addon\ProxyCheap\Commands\RotateIP($apiparams, ['proxy_id' => $proxy_id]))->post();
        if($RegenerateCredentials)
        {
            header("Location: ".$_SERVER['HTTP_REFERER']);
            exit;
        }
    }
    $proxydetails = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetProxyInfo($apiparams, $input))->get();

    if(!$proxydetails) { $proxydetails=[]; }

    $proxyOneInfo = null;
    $protocols = null;
    $credentialgenerator = null;
    if(count($proxydetails) === 1 )
    {
        $proxyOneInfo = (array)(new WHMCS\Module\Addon\ProxyCheap\Commands\GetOneProxyInfo($apiparams, ['proxy_id' => $proxydetails[0]->id]))->get();

        $protocols = (array)(new WHMCS\Module\Addon\ProxyCheap\Commands\GetAvailableProtocols($apiparams, ['proxy_id' => $proxydetails[0]->id]))->get();

        if($proxydetails[0]->networkType === 'MOBILE' && $proxydetails[0]->status === 'ACTIVE')
        {
            $credentialgenerator = (new WHMCS\Module\Addon\ProxyCheap\Commands\CredentialsGenerator($apiparams, ['proxy_id' => $proxydetails[0]->id]))->get();

            if(isset($credentialgenerator->credentials))
            {
                $credentialgenerator = $credentialgenerator->credentials;
            }
           
        }
        else
        {
            $auths = (new WHMCS\Module\Addon\ProxyCheap\Commands\GetAvailableAuths($apiparams, ['proxy_id' => $proxydetails[0]->id]))->get();
        }

    }
    //echo('<pre>'); var_dump($proxyOneInfo); exit;
    return [
        'templatefile' => $_GET['a'] === 'whitelist' ? 'proxycheap-whitelist' : 'proxycheap-clientarea',
        'vars' => [
            'proxies' => $proxydetails,
            'customhostname' => $apiparams['residentialDomain'],
            'oneproxyinfo' => $proxyOneInfo,
            'protocols' => $protocols,
            'currentAuthType' => isset($auths->currentAuthenticationType) ? $auths->currentAuthenticationType : null,
            'credentialgenerator' => !empty($credentialgenerator) ? array_combine(array_map(function($item) { return strtolower($item->region); }, $credentialgenerator), $credentialgenerator) : null,
        ]
    ];
}
