<?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>');

        //add "Domains" link in Resellers Center Client Area Menus
        var link = "javascript:do_wgs_reseller_custom_action('wgsRenewBulkDomainsRsLink','renewbulkdomains');";
        menu.append('<li><a href="' + link + '" id="wgsRenewBulkDomainsRsLink"><i class="fa fa-cogs"></i><span>Renew Bulk Domains</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) {

    //if(isset($_GET['testbysom']) && $_GET['testbysom']=='dfordomain'){
        global $smarty;
        $urlDomain = $_SERVER['SERVER_NAME'];   
        //echo $_SERVER['SCRIPT_NAME']. " ".$_SESSION['uid'];

                  
        if(basename($_SERVER['SCRIPT_NAME'])=='clientarea.php' && empty($_GET))
        {
	        $noOffDomains = Capsule::table('tbldomains')->where('userid',$_SESSION['uid'])->where('status','Active')->count();
	        $smarty->assign('wgdnoOffDomains', $noOffDomains);
	    }    

        if($urlDomain != 'dfordomains.com')
        { 

            if(basename($_SERVER['SCRIPT_NAME'])=="index.php" && empty($_SESSION['uid'])){
              $resellerLoginstatus=true;
              $smarty->assign('resellerLoginstatus', $resellerLoginstatus);  
            }

            $rsSettingLogo = '';
            $rsSettingData = Capsule::select("select reseller_id,  reseller_id from ResellersCenter_ResellersSettings where setting='domain' and value like '%" . $urlDomain . "%' ");
            if(!empty($rsSettingData)){
                $rsSettingData01 = Capsule::select("select value from ResellersCenter_ResellersSettings where setting='logo' and reseller_id ='" . $rsSettingData[0]->reseller_id . "' ");            
                if(!empty($rsSettingData01)){
                    $rsSettingLogo = $rsSettingData01[0]->value;
                }
                $getClientId = Capsule::table('ResellersCenter_Resellers')->where('id', $rsSettingData[0]->reseller_id)->first();
                $clientData = Capsule::table('tblclients')->where('id', $getClientId->client_id)->first();
                //print_r($clientData);
                if($clientData->companyname != '')
                  $smarty->assign('resellercompanyname', $clientData->companyname);
            }
            $smarty->assign('rsSettingLogo', $rsSettingLogo);
        }    
    //}
	//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('groupid','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('tblpricing.tsetupfee',$rsclientData->groupid.'.00')->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;
        }   
   } 
});

add_hook('AdminAreaHeadOutput', 1, function($vars) {
  if($_POST['wgs_check_client_type']=='reseller'){ 
     $id = $_POST['clientid'];
      $rsData = Capsule::table('ResellersCenter_Resellers')->where('client_id', $id)->count();
      if($rsData !='0')
      {
        $type = '<span class="label active">Reseller</span>';
      }else{
          $type = '--';
      }  
     $data = array('clientid' => $id, 'type' => $type);
     echo json_encode($data);die();
  }

$pageName =basename($_SERVER['SCRIPT_NAME']);
if($pageName=='clients.php'){
return <<<HTML
    
<script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('#sortabletbl0').find('tr').each(function(index){
        id = jQuery(this).find('td').eq(1).find('a').text();        
        if(index=='0'){
           jQuery(this).append('<th>Type</th>');
        }else{
            jQuery(this).append('<td id="rstype' + id + '">--</td>');
            jQuery.ajax({
                type: 'POST',
                url: '',
                data: 'clientid=' + id + '&wgs_check_client_type=reseller',
                success: function (resp){
                    var result = JSON.parse(resp); 
                    jQuery('#rstype'+result.clientid).html(result.type);
                }
            });          
        }
    });
});    
</script>
HTML;

}
if($pageName=='clientssummary.php'){  
  $userid = $_GET['userid'];
  $rsData = Capsule::table('ResellersCenter_Resellers')->where('client_id', $userid)->count();
  $type = '';
  if($rsData !='0')
  {
    $type = '<span class="label active">Reseller</span>';
  }

  $rsData = Capsule::table('ResellersCenter_ResellersClients')->join('ResellersCenter_Resellers', 'ResellersCenter_Resellers.id', '=', 'ResellersCenter_ResellersClients.reseller_id')->where('ResellersCenter_ResellersClients.client_id', $userid)->select('ResellersCenter_Resellers.client_id')->first();
  if(!empty($rsData)){
    $type = '<a href="clientssummary.php?userid='.$rsData->client_id.'"><span class="label active">View Reseller</span></a>'; 
  }

return <<<HTML
    
<script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('.client-summary-name').append('$type');
});    
</script>
HTML;

}
});


/*add_hook('InvoiceCreated', 1, function($vars) {
   $invoiceId = $vars['invoiceid'];
   //echo '<pre>'; print_r($vars);
   $rsData = Capsule::table('ResellersCenter_Invoices')->select('reseller_id')->where('relinvoice_id', $invoiceId)->first();
   if(!empty($rsData)){
      //echo '<pre>'; print_r($rsData);
      //echo '<pre>'; print_r($_SESSION);
      $uData = Capsule::table('ResellersCenter_Invoices')->select('id')->where('userid', $_SESSION['uid'])->where('reseller_id', $rsData->reseller_id)->orderBy('id', 'desc')->first();
      //echo '<pre>'; print_r($uData); 
      if(!empty($rsData)){        
        //die('work');
          header('location:rcviewinvoice.php?id='.$uData->id);
      }
   }   
   //die('working..');
	 //echo '<pre>'; print_r($vars); die();	
});*/