<?php
use Illuminate\Database\Capsule\Manager as Capsule;

add_hook('ClientAreaHeadOutput', 1, function($vars) {
   $template = $vars['template'];   
if($_GET['m']=='ResellersCenter')
{

    $currencyData = getCurrency($_SESSION['uid']);
    $prefix = $currencyData['prefix'];
    $cCode = $currencyData['code']; 
    $rsCrRowData = Capsule::table("tblclients")->select('credit')->where('id',$_SESSION['uid'])->first();
    $rsCredit = $rsCrRowData->credit;

    if($_GET['mg-page']=='configuration'){
        $rsCreditDiv = 'jQuery("#RCConfiguration").find(".caption").append("<span>(Credit Balance: '.$prefix.$rsCredit.' '.$cCode.')</span>")';
    }

    return <<<HTML
    <link href="includes/hooks/wgs_reseller_center/css/resellers_center_custom_css.css" rel="stylesheet">
    <script type="text/javascript" src="includes/hooks/wgs_reseller_center/js/resellers_center_custom_js.js"></script>
    <script type="text/javascript">
    	jQuery(document).ready(function () {
    		jQuery('.full-screen-module-container').find('.page-content').before('<div class="wgs-page-content"></div>');
    		var menu = jQuery('.full-screen-module-container').find('.top-menu').find('.navbar-nav');

    		//add "Domains" link in Resellers Center Client Area Menus
    		var link = "javascript:do_wgs_reseller_custom_action('wgsDomainsDataRsLink','domains');";
    		menu.append('<li><a href="' + link + '" id="wgsDomainsDataRsLink"><i class="fa fa-cogs"></i><span>Domains</span></a></li>');

    		//add "Domains" link in Resellers Center Client Area Menus
    		var link = "javascript:do_wgs_reseller_custom_action('wgsClientsDataRsLink','clients');";
    		menu.append('<li><a href="' + link + '" id="wgsClientsDataRsLink"><i class="fa fa-cogs"></i><span>Clients Actions</span></a></li>');            

            $rsCreditDiv

    	});
	</script>
HTML;
}
});

add_hook('InvoicePaid', 1, function($vars) {
    $invoiceid = $vars['invoiceid'];
    try {
        Capsule::schema()->create(
            'ResellersCenter_ClientInvoices',
            function ($table) {
                $table->increments('id');
                $table->integer('reseller_id');
                $table->integer('rsclientid');
                $table->integer('clientid');
                $table->integer('domainid');
                $table->integer('renewal_period');
                $table->integer('relinvoice_id');
                $table->integer('status');
            }
        );
     } catch (\Exception $e) {
         //logActivity("Unable to create mod_soyoustart: {$e->getMessage()}");
     }
     $resellerInvoice = Capsule::table("ResellersCenter_ClientInvoices")->where('relinvoice_id',$invoiceid)->where('status','0')->first();
     if(!empty($resellerInvoice)){
            $command = 'DomainRenew';
            $postData = array('domainid' => $resellerInvoice->domainid,'regperiod' => $resellerInvoice->renewal_period);
            $adminUsername = ''; // Optional for WHMCS 7.2 and later
            $results = localAPI($command, $postData, $adminUsername);            
            if($results['result']=='success'){
                Capsule::table("ResellersCenter_ClientInvoices")->where('relinvoice_id',$invoiceid)->where('status','0')->update(array('status'=>'1'));
                $domainData = Capsule::table("tbldomains")->where('id',$resellerInvoice->domainid)->where('userid',$resellerInvoice->clientid)->first();
               Capsule::table("tbldomains")->where('id',$resellerInvoice->domainid)->where('userid',$resellerInvoice->clientid)->update(array('nextduedate'=>$domainData->expirydate,'nextinvoicedate'=>$domainData->expirydate));
                logActivity('#'.$resellerInvoice->domainid.' domain renew successfully', $resellerInvoice->rsclientid);
            }else{
                logActivity($results['message'].':'.$results['error'], $resellerInvoice->rsclientid);
            }
          //  echo '<pre>'; print_r($results);die('test');
     }
    //echo '<pre>'; echo $invoiceid; die();
});

add_hook('ClientAreaPage', 1, function($vars) {
	//echo '<pre>'; print_r($_POST); die('');
    //Capsule::table('tblhosting')->select('id','packageid')->where('userid',$_GET["userid"])->orderBy('id', 'asc')->take(1)->get();
    if(isset($_POST['wgs_reseller_custom_gaction']) && $_POST['wgs_reseller_custom_gaction']=='renewdomain' && !empty($_POST['domainid']) && !empty($_POST['userid'])){
        //echo '<pre>'; print_r($_POST); die('JMD');
        //error_reporting(E_ALL); ini_set('display_errors', 1); 
        $domainid = $_POST['domainid'];
        $rsclientid = $_SESSION['uid'];
        $userid = $_POST['userid'];
        $renewalPeriod = $_POST['renewalPeriod'];
        $resellerData = Capsule::table("ResellersCenter_Resellers")->select('id')->where('client_id',$rsclientid)->first();   
        $rsId = $resellerData->id;
        try {
            Capsule::schema()->create(
                'ResellersCenter_ClientInvoices',
                function ($table) {
                    $table->increments('id');
                    $table->integer('reseller_id');
                    $table->integer('rsclientid');
                    $table->integer('clientid');
                    $table->integer('domainid');
                    $table->integer('renewal_period');
                    $table->integer('relinvoice_id');
                    $table->integer('status');
                }
            );
         } catch (\Exception $e) {         
             //logActivity("Unable to create mod_soyoustart: {$e->getMessage()}");
         }
         //$rsData = Capsule::table("tbldomains")->where('id',$domainid)->where('userid',$userid)->first();
         $domainData = Capsule::table("tbldomains")->where('id',$domainid)->where('userid',$userid)->first();
         $renewAmount = $domainData->recurringamount;




         $rsclientData = Capsule::table("tblclients")->select('currency','country','state')->where('id',$rsclientid)->first();
         $rsCountry = $rsclientData->country;
         $rsState = $rsclientData->state;
         $clientData = Capsule::table("tblclients")->select('currency')->where('id',$userid)->first();
         if($rsclientData->currency != $clientData->currency){
            $tldData = explode('.', $domainData->domain, 2);
            $tld = $tldData[1];
            $tldPrice = Capsule::table("tbldomainpricing")->join('tblpricing', 'tblpricing.relid', '=', 'tbldomainpricing.id')->where('tbldomainpricing.extension','.'.$tld)->where('tblpricing.type','domainrenew')->where('tblpricing.currency',$rsclientData->currency)->select('tblpricing.msetupfee')->orderBy('tblpricing.id', 'asc')->first();
            if(!empty($tldPrice) && $tldPrice->msetupfee > '0'){
                $renewAmount = $tldPrice->msetupfee;
            }
            //
         }

         $command = 'CreateInvoice';
         $postData = array(
            'userid' => $rsclientid,
            'status' => 'Unpaid',
            'sendinvoice' => '1',
            'paymentmethod' => $domainData->paymentmethod,            
            'date' => date('Y-m-d'),
            'duedate' => date('Y-m-d'),
         );
         $startData = $domainData->nextduedate;

         for($r=1; $r<=$renewalPeriod; $r++){            
            $endData = date('Y-m-d', strtotime('+ 1 year' . $startData));
            $itemdescription = 'Domain Renew -'.$domainData->domain.'- 1 Year/s ('.$startData.' - '. $endData .')';
            $postData['itemdescription'.$r] = $itemdescription;
            $postData['itemamount'.$r] = $renewAmount;
            $postData['itemtaxed'.$r] = '1';
            $startData = $endData;
         }


        $taxlevels = Capsule::table("tbltax")->select('taxrate')->where('country',$rsCountry)->where('state',$rsState)->orderBy('level', 'asc')->take(2)->get();        
        if(empty($taxlevels)){
            $taxlevels = Capsule::table("tbltax")->select('taxrate')->where('country',$rsCountry)->where('state','')->orderBy('level', 'asc')->take(2)->get();
        }
        if(empty($taxlevels)){
            $taxlevels = Capsule::table("tbltax")->select('taxrate')->where('country','')->where('state','')->orderBy('level', 'asc')->take(2)->get();
        }

        if(isset($taxlevels[0])){ $postData['taxrate'] = $taxlevels[0]->taxrate; }
        if(isset($taxlevels[1])){ $postData['taxrate2'] = $taxlevels[1]->taxrate; }
        //echo '<pre>'; print_r($postData); die('JMD');

         $adminUsername = ''; // Optional for WHMCS 7.2 and later
         $results = localAPI($command, $postData, $adminUsername);
         //echo '<pre>'; print_r($results); die();         
         if($results['result']=='success'){
            $invoiceid = $results['invoiceid'];
            Capsule::table("ResellersCenter_ClientInvoices")->insert(array('reseller_id'=>$rsId,'rsclientid'=>$rsclientid,'clientid'=>$userid,'domainid'=>$domainid,'renewal_period'=>$renewalPeriod,'relinvoice_id'=>$invoiceid));
            //Capsule::table("tblinvoiceitems")->where('invoiceid',$invoiceid)->update(array('type'=>'Domain','relid'=>$domainid));
            header('location:viewinvoice.php?id='.$invoiceid);die();
         }else{
            header('location:index.php?m=ResellersCenter');die();
         }
        die();
    }

    if(isset($_POST['wgs_reseller_custom_action']) && !empty($_POST['wgs_reseller_custom_action']) && !empty($_SESSION['uid'])){
    	require(__DIR__ . '/wgs_reseller_center/'.$_POST['wgs_reseller_custom_action'].'.php');die();
    }

    if(isset($_POST['wgs_reseller_custom_ajax']) && !empty($_POST['wgs_reseller_custom_ajax']) && !empty($_SESSION['uid'])){
        require(__DIR__ . '/wgs_reseller_center/ajax.php');die();   
    }
});


add_hook('PreRegistrarGetEPPCode', 1, function($vars) {   
   if(isset($_GET['action']) && $_GET['action']=='domaingetepp' && !empty($_GET['domainid'])){
        $domainid = $_GET['domainid'];
        $ccData = Capsule::table('ResellersCustomData')->where('type', 'domain')->where('relid', $domainid)->where('setting', 'transferlock')->select('value')->first();
        if($ccData->value=='yes'){
            $result['abortWithError']='Your domain is locked from admin you can not transfer your domain.';
            return $result;
        }   
   } 
});
