<?php
use Illuminate\Database\Capsule\Manager as Capsule;
	$rsClientId = $_SESSION['uid'];	
	$resellerData = Capsule::table("ResellersCenter_Resellers")->select('id')->where('client_id',$rsClientId)->first();
	$rsId = $resellerData->id;

	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='removerecords'){
		$zoneId = $_POST['zoneId'];
		$lineId = $_POST['lineId'];
		$result = localAPI('dnsmanager' ,array('dnsaction' => 'removeRecords','zone_id' => $zoneId,'records' => array(array('id' => $lineId))));
		echo json_encode($result);die();
	}

	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='addzone'){
		$postfields  = array(
				 'action' => 'dnsmanager',
				 'dnsaction' => 'createZone',
				 'zone_name' => $_POST['name'], 
				 'type' => '1',
				 'relid' => $_POST['domainid'],
				 'zone_ip' => $_POST['ip'],
				 'userid' => $_POST['clientId'],
			);
		$results = localAPI('dnsmanager', $postfields, '');		
		$zoneData = Capsule::table("dns_manager2_zone")->select('id')->where('clientid',$_POST['clientId'])->where('relid',$_POST['domainid'])->where('type','1')->first();
		$results['zoneid'] = $zoneData->id;
		echo json_encode($results);die();
	}

	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='updatednsmanager'){
		$zoneId = $_POST['zoneId'];
		$domainId = $_POST['domainId'];
		$clientId = $_POST['clientId'];	

		$records = array();
		foreach ($_POST['record'] as $record) {
			$cnmData = $record['field'];
                        if($record['type'] == 'A')
                            $cnmData = $record['field']['address'];
			//$records[] = array('line' => $record['line'],'name' => $record['name'],'type' => $record['type'],'ttl' => $record['ttl'],'class' => 'IN','data' => $cnmData);	
			$newRecordData = array('name' => $record['name'],'type' => $record['type'],'ttl' => $record['ttl'],'class' => 'IN','data' => $cnmData);
			if(isset($record['line']))
            {
                $newRecordData['line'] = $record['line'];
            }
            $records[] = $newRecordData;
		}

		$requestData = array('dnsaction' => 'updateZone','zone_id' => $zoneId,'records' => $records);

		$result = localAPI('dnsmanager',$requestData,'');

		if(substr($result['message'],0,24)=='Unable to parse response')
		{
			$result['message'] = 'Unable to parse response';
		}
		echo json_encode($result);die();
	}

	//This code use for update client credit from reseller area.
	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='getcredit'){
		$customerId = $_POST['clientid'];
		$command = 'GetCredits';
		$postData = array(
		    'clientid' => $customerId,
		);
		$adminUsername = ''; // Optional for WHMCS 7.2 and later
		$results = localAPI($command, $postData, $adminUsername);
		?>
			<div class="tablebg" style="margin-top: -20px;">
				<table class="table" width="100%" border="0" cellspacing="1" cellpadding="3" style="margin-top: 40px;">						
						<tr>
							<th>Date</th>
							<th>Description</th>
							<th>Amount</th>
							<th width="20">Action</th>
						</tr>
						<?php foreach($results['credits']['credit'] as $result){ ?>
						<tr>
							<td><?php echo $result['date']; ?></td>
							<td><?php echo $result['description']; ?></td>
							<td><?php echo $result['amount']; ?></td>
							<td width="20">								
								<a href="javascript:;" class="openDeleteClient btn-danger btn btn-inverse btn-sm only-icon" onclick="wgs_rs_deleteCredit('<?php echo $result['id']; ?>','<?php echo $customerId; ?>');"><i class="icon-in-button fa fa-trash-o"></i></a>
							</td>
						</tr>
					<?php } 
					if(empty($results['credits']['credit'])){ ?>
						<tr><td colspan="4">No Records Found</td></tr>
					<?php } ?>	
				</table>
			</div>
		<?php
		die();
	}

	//This code use for update client credit from reseller area.
	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='savecredit'){
		$customerId = $_POST['wgsclientid'];
		$currencyData = getCurrency($customerId);
		$prefix = $currencyData['prefix'];
		$cCode = $currencyData['code'];	

		$amount = $_POST['wgscreditAmount'];
		$creditType = $_POST['creditType'];
		$date = $_POST['wgscreditDate'];
		if(empty($date) || $date=='0000-00-00'){
			$date = date('H-m-d');
		}
		$description = $_POST['wgscreditDescription'];

		$count = Capsule::table("ResellersCenter_ResellersClients")->select('id')->where('reseller_id',$rsId)->where('client_id',$customerId)->count();
		if($count != '0'){
			if($creditType=='add'){
				$amount = $amount;
			}else{
				$amount = '-'.$amount;
			}
			
			$postData = array(
			    'clientid' => $customerId,
			    'description' => $description,
			    'date' => $date,
			    'amount' => $amount,
			);			
			$creditData = Capsule::table("tblclients")->where('id',$customerId)->select('credit')->first();
			$creditVal = $creditData->credit;
			$totalAmount = $creditVal + $amount;
			Capsule::table("tblclients")->where('id',$customerId)->update(array('credit'=>$totalAmount));
			Capsule::table("tblcredit")->insert($postData);
			$log = 'Reseller (id #'.$rsId.') has update the credit of client #'.$customerId;
			Capsule::table("ResellersCenter_Logs")->insert(array('reseller_id'=>$rsId,'client_id'=>$customerId,'type'=>'info','description'=>$log,'created_at'=>date('Y-m-d H:i:s')));
		}
		$res = Capsule::table("tblclients")->where('id',$customerId)->select('credit')->first();
		$res = (array) $res;
		$res['credit'] = $prefix.$res['credit'].' '.$cCode;		
		$result = array('type'=>'success','message'=>'','data'=>$res);
		echo json_encode($result);die();
	}

	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='deletecredit'){
		$customerId = $_POST['clientid'];
		$creditId = $_POST['creditId'];
		$currencyData = getCurrency($customerId);
		$prefix = $currencyData['prefix'];
		$cCode = $currencyData['code'];		
		$count = Capsule::table("ResellersCenter_ResellersClients")->select('id')->where('reseller_id',$rsId)->where('client_id',$customerId)->count();
		if($count != '0'){						
			$creditData = Capsule::table("tblclients")->where('id',$customerId)->select('credit')->first();
			$creditVal = $creditData->credit;
			$creditRow = Capsule::table("tblcredit")->where('id',$creditId)->select('amount')->first();
			$totalAmount = $creditVal - $creditRow->amount;
			Capsule::table("tblcredit")->where('id',$creditId)->delete();
			Capsule::table("tblclients")->where('id',$customerId)->update(array('credit'=>$totalAmount));			
			$log = 'Reseller (id #'.$rsId.') has update the credit of client #'.$customerId;
			Capsule::table("ResellersCenter_Logs")->insert(array('reseller_id'=>$rsId,'client_id'=>$customerId,'type'=>'info','description'=>$log,'created_at'=>date('Y-m-d H:i:s')));
		}
		$res = Capsule::table("tblclients")->where('id',$customerId)->select('credit')->first();
		$res = (array) $res;
		$res['credit'] = $prefix.$res['credit'].' '.$cCode;
		$result = array('type'=>'success','message'=>'','data'=>$res);
		echo json_encode($result);die();
	}

	//This code use for transfer domain with reseller client from reseller area.
	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='transferdomain'){
		$wgsdomainid = $_POST['wgsdomainid'];
		$newdomainuserid = $_POST['newdomainuser'];
		$wgsuDomain = $_POST['wgsuDomain'];		
		$count = Capsule::table("ResellersCenter_ResellersClients")->select('id')->where('reseller_id',$rsId)->where('client_id',$newdomainuserid)->count();
		if($count != '0' || $rsClientId==$newdomainuserid){		

			$dData = Capsule::table("tbldomains")->select('paymentmethod','userid','domain')->where('id',$wgsdomainid)->first();
			if($wgsuDomain==$dData->domain)
			{					
	            $$orderid = Capsule::table("tblorders")->insertGetId(array('status'=>'Active','userid'=>$newdomainuserid,'paymentmethod'=>$dData->paymentmethod,'date'=>date('Y-m-d H:i:s')));
	            Capsule::table('tbldomains')->where('id', $wgsdomainid)->update(array('orderid'=>$orderid,'userid'=>$newdomainuserid));
	            $log = 'Reseller (id #'.$rsId.') has transfer domain('.$dData->domain.') with his clients #'.$dData->userid.' to #'.$newdomainuserid;
				Capsule::table("ResellersCenter_Logs")->insert(array('reseller_id'=>$rsId,'client_id'=>$newdomainuserid,'type'=>'info','description'=>$log,'created_at'=>date('Y-m-d H:i:s')));	            
	        }
		}
		$res = Capsule::table("tblclients")->join('tbldomains', 'tbldomains.userid', '=', 'tblclients.id')->where('tbldomains.id',$wgsdomainid)->select('tblclients.id','tblclients.firstname','tblclients.lastname','tblclients.email')->first();
		$res = (array) $res;
		$result = array('type'=>'success','message'=>'','data'=>$res);
		echo json_encode($result);die();
	}

	//This code use for transfer domain with reseller client from reseller area.
	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='updatedomainstatus'){
		$wgsdomainid = $_POST['wgsdomainstatusid'];		
		$wgsuDomain = $_POST['wgsDomainName'];		
		$wgsdomainstatus = $_POST['wgsdomainstatus'];		
		if($wgsdomainstatus=='0'){
			$wgsdomainstatus = 'Pending';
		}else{
			$wgsdomainstatus = 'Active';
		}
        Capsule::table('tbldomains')->where('id', $wgsdomainid)->update(array('status'=>$wgsdomainstatus));
        $log = 'Reseller (id #'.$rsId.') has update the domain('.$wgsuDomain.') status('.$wgsdomainstatus.') to his client';
		Capsule::table("ResellersCenter_Logs")->insert(array('reseller_id'=>$rsId,'type'=>'info','description'=>$log,'created_at'=>date('Y-m-d H:i:s')));
		$res = Capsule::table('tbldomains')->where('id', $wgsdomainid)->select('status')->first();
		$res = (array) $res;
		$result = array('type'=>'success','message'=>'','data'=>$res);
		echo json_encode($result);die();
	}



	if(isset($_POST['wgs_reseller_custom_ajax']) && $_POST['wgs_reseller_custom_ajax']=='updatedomaininfo'){

		 

		$domainid = $_POST['domainid'];		
		$clientid = $_POST['clientid'];		
		$count = Capsule::table("ResellersCenter_ResellersClients")->select('id')->where('reseller_id',$rsId)->where('client_id',$clientid)->count();
		$message = '';	
		//echo '<pre>'; print_r($count);
		//echo '<pre>'; print_r($_POST); die('Test');	
		//echo $_SESSION['uid'].'=='.$clientid; die();
		if($count != '0' || $_SESSION['uid']==$clientid){
			if($_POST['subaction']=='updatecontactinfo')
			{					
				$data = array('type'=>'domain','relid'=> $domainid,'setting'=>'transferlock','value'=>$_POST['transferlock']);
				$chkRow = Capsule::table('ResellersCustomData')->where('type', 'domain')->where('relid', $domainid)->where('setting', 'transferlock')->count();
				if($chkRow!='0'){
						Capsule::table('ResellersCustomData')->where('type', 'domain')->where('relid', $domainid)->where('setting', 'transferlock')->update($data);
				}else{
					Capsule::table('ResellersCustomData')->insert($data);
				}

				$command = 'DomainUpdateWhoisInfo';
				$registrant = $_POST['contactdetails']['Registrant'];
				$postData = array(
				    'domainid' => $domainid,
				    'xml' => 
				    '<contactdetails>
					    <Registrant>
						    <Contact_Name>'.$registrant['firstname'].' '.$registrant['lastname'].'</Contact_Name>
						    <Email>'.$registrant['Email'].'</Email>
						    <Company_Name>'.$registrant['CompanyName'].'</Company_Name>
						    <Address_1>'.$registrant['Address1'].'</Address_1>
						    <Address_2>'.$registrant['Address2'].'</Address_2>				    
						    <City>'.$registrant['City'].'</City>
						    <State>'.$registrant['State'].'</State>
						    <Zip>'.$registrant['Postcode'].'</Zip>
						    <Country>'.$registrant['Country'].'</Country>					    
						    <Postcode>'.$registrant['Postcode'].'</Postcode>
						    <Phone>'.$registrant['Phone Country Code'].' '.$registrant['Phone'].'</Phone>
					    </Registrant>
					    <Admin>
						    <Contact_Name>'.$registrant['firstname'].' '.$registrant['lastname'].'</Contact_Name>
						    <Email>'.$registrant['Email'].'</Email>
						    <Company_Name>'.$registrant['CompanyName'].'</Company_Name>
						    <Address_1>'.$registrant['Address1'].'</Address_1>
						    <Address_2>'.$registrant['Address2'].'</Address_2>				    
						    <City>'.$registrant['City'].'</City>
						    <State>'.$registrant['State'].'</State>
						    <Zip>'.$registrant['Postcode'].'</Zip>
						    <Country>'.$registrant['Country'].'</Country>					    
						    <Postcode>'.$registrant['Postcode'].'</Postcode>
						    <Phone>'.$registrant['Phone Country Code'].' '.$registrant['Phone'].'</Phone>
					    </Admin>
					    <Billing>
						    <Contact_Name>'.$registrant['firstname'].' '.$registrant['lastname'].'</Contact_Name>
						    <Email>'.$registrant['Email'].'</Email>
						    <Company_Name>'.$registrant['CompanyName'].'</Company_Name>
						    <Address_1>'.$registrant['Address1'].'</Address_1>
						    <Address_2>'.$registrant['Address2'].'</Address_2>				    
						    <City>'.$registrant['City'].'</City>
						    <State>'.$registrant['State'].'</State>
						    <Zip>'.$registrant['Postcode'].'</Zip>
						    <Country>'.$registrant['Country'].'</Country>					    
						    <Postcode>'.$registrant['Postcode'].'</Postcode>
						    <Phone>'.$registrant['Phone Country Code'].' '.$registrant['Phone'].'</Phone>
					    </Billing>
					    <Tech>
						    <Contact_Name>'.$registrant['firstname'].' '.$registrant['lastname'].'</Contact_Name>
						    <Email>'.$registrant['Email'].'</Email>
						    <Company_Name>'.$registrant['CompanyName'].'</Company_Name>
						    <Address_1>'.$registrant['Address1'].'</Address_1>
						    <Address_2>'.$registrant['Address2'].'</Address_2>				    
						    <City>'.$registrant['City'].'</City>
						    <State>'.$registrant['State'].'</State>
						    <Zip>'.$registrant['Postcode'].'</Zip>
						    <Country>'.$registrant['Country'].'</Country>					    
						    <Postcode>'.$registrant['Postcode'].'</Postcode>
						    <Phone>'.$registrant['Phone Country Code'].' '.$registrant['Phone'].'</Phone>
					    </Tech>
				    </contactdetails>',
				    
				);


				$adminUsername = ''; // Optional for WHMCS 7.2 and later
				$results = localAPI($command, $postData, $adminUsername);				
				if($results['result']=='error'){
					$message .= '<span style="color:red;">Domain WhoisInfo not updated:'.$results['error'].'</span>';
				}			
				//echo '<pre>'; print_r($results);
				if($results['result']=='success'){
					$message .= '<span style="color:green;">Domain WhoisInfo updated successfully.</span>';
					$clientData = array(
						'firstname'=>$registrant['firstname'],
						'lastname'=>$registrant['lastname'],
						'companyname'=>$registrant['CompanyName'],
						'address1'=>$registrant['Address1'],
						'address2'=>$registrant['Address2'],	
						'city'=>$registrant['City'],
						'state'=>$registrant['State'],
						'country'=>$registrant['Country'],
						'postcode'=>$registrant['Postcode'],
						'email'=>$registrant['Email'],
						'phonenumber'=>$registrant['Phone'],
					);
					//Capsule::table('tblclients')->where('id', $clientid)->update($clientData);
				}
				echo $message;die('');
			}else if($_POST['subaction']=='updatenameserver'){
					
				$command = 'DomainUpdateNameservers';
				$postData = array(
				    'domainid' => $domainid,
				    'ns1' => $_POST['ns1'],
				    'ns2' => $_POST['ns2'],
				    'ns3' => $_POST['ns3'],
				    'ns4' => $_POST['ns4'],
				    'ns5' => $_POST['ns5']
				);
				$adminUsername = ''; // Optional for WHMCS 7.2 and later
				$results = localAPI($command, $postData, $adminUsername);
				if($results['result']=='error'){
					$message .= '<span style="color:red;">Domain Nameservers not updated:'.$results['error'].'</span>';
				}
				if($results['result']=='success'){
					$message .= '<span style="color:green;">Domain Nameservers updated successfully.</span>';
				}
				echo $message;die();
			}	
		}				
	}
	