<?php
/*
WHMCS MachPanel Integration Package: v 4.4
Supported MachPanel version: 6.3.30 Or Later
Last modified: 01-Jun-2023

Caution: any changes in this file except for those mentioned in corresponding MachPanel integration guide 
may result in failure in server module commands.

Developed and maintained by: MachSol, Inc.
web url: https://www.machsol.com
Machsol support: support@machsol.com
*/

//Add reference to Client Handler
if(!class_exists('MachPanelClientHandler'))
{
  require_once('MachPanelClientHandler.php');
}

if(!class_exists('MachPanelClientHandler'))
{
  require_once(dirname(__FILE__)."/MachPanelClientHandler.php");
}

if(!class_exists('MachPanelClientHandler'))
{
	die("Module handler file not found: \'".dirname(__FILE__)."/MachPanelClientHandler.php\'");
}

function machpanel_ConfigOptions() {

	# Should return an array of the module options for each product - maximum of 24

    // $configarray = array(
	 // "Package Name" => array( "Type" => "text", "Size" => "25", ),
	 // "Web Space Quota" => array( "Type" => "text", "Size" => "5", "Description" => "MB" ),
	 // "FTP Access" => array( "Type" => "yesno", "Description" => "Tick to grant access" ),
     // "Subdomains" => array( "Type" => "dropdown", "Options" => "1,2,5,10,25,50,Unlimited"),
	// );
	
    //$configarray = array("MachPanel Prod.Id" => array( "Type" => "text", "Size" => "8"));
	//return $configarray;

}

function machpanel_CreateAccount($params) {

    # ** The variables listed below are passed into all module functions **

    //$serviceid = $params["serviceid"]; # Unique ID of the product/service in the WHMCS Database
    //$pid = $params["pid"]; # Product/Service ID
    //$producttype = $params["producttype"]; # Product Type: hostingaccount, reselleraccount, server or other
    //$domain = $params["domain"];
	  //$username = $params["username"];
	  //$password = $params["password"];
    //$clientsdetails = $params["clientsdetails"]; # Array of clients details - firstname, lastname, email, country, etc...
    //$customfields = $params["customfields"]; # Array of custom field values for the product
    //$configoptions = $params["configoptions"]; # Array of configurable option values for the product

    # Product module option settings from ConfigOptions array above
    //$mp_prodid = $params["configoption1"];
    //$configoption2 = $params["configoption2"];
    //$configoption3 = $params["configoption3"];
    //$configoption4 = $params["configoption4"];

    # Additional variables if the product/service is linked to a server
    //$server = $params["server"]; # True if linked to a server
    //$serverid = $params["serverid"];
    //$serverip = $params["serverip"];
    //$serverusername = $params["serverusername"];
    //$serverpassword = $params["serverpassword"];
    //$serveraccesshash = $params["serveraccesshash"];
    //$serversecure = $params["serversecure"]; # If set, SSL Mode is enabled in the server config

	# Code to perform action goes here...
	
	//initialize client handler 
	$clientObj = new MachPanelClientHandler();
	
	//set function paramters array for soap client submit.
	$paramArray = array();
	$paramArray['WServiceId'] = $params["serviceid"];
	$paramArray['WProductId'] = $params["pid"];
	$paramArray['domainName'] = $params["domain"];
	
	$customerObject = $clientObj->createCustomerObject($params);
	
	$customerSoapObject = new SoapVar($customerObject, // the object to wrap
									SOAP_ENC_OBJECT,
									get_class($customerObject), // the concrete class name
									'http://machsol.com/' // namespace that proxy classes belong to (in WSDL)
									);	
									
	$paramArray['C'] = $customerSoapObject;
	$paramArray['customfields'] = $params["customfields"];
	$paramArray['configoptions'] = $params['configoptions'];
	//custom fields format: array('organizationname'=> 'myfirstorg', 'adminusername'=> 'admin.user', 'adminuserpassword'=> 'P@ssw0rd123#');
	
	try
	{
		$RespArgs = $clientObj->SvcClient->SubmitWHMCSOrder($paramArray)->SubmitWHMCSOrderResult;
		if(!$RespArgs->ResponseStatus)
		{
			return "Submit order to machpanel module request ended with message: ".$RespArgs->ResponseMessage;
		}
		else
		{
			return "success";
		}
	}
	catch(Exception $sf)
	{
		$errMsg = 'Error: '.$sf->getMessage();
		$errMsg = $errMsg.'<br /><b>Request:</b> '.$clientObj->SvcClient->__getLastRequest();
		$errMsg = $errMsg.'<br /><b>Response:</b> '.$clientObj->SvcClient->__getLastResponse();
		$errMsg = $errMsg.'<br /><b>Request Header:</b> '.$clientObj->SvcClient->__getLastRequestHeaders();
		$errMsg = $errMsg.'<br /><b>Response Header:</b> '.$clientObj->SvcClient->__getLastResponseHeaders();
		throw new Exception('Soap Fault in submitting the order. Details: '.$errMsg);
	}
}


function machpanel_TerminateAccount($params) {

	# Code to perform action goes here...

  try
  {
	  $paramArray = array();
	  $paramArray['WServiceId'] = $params["serviceid"];
	  $paramArray['action'] = "Cancel"; 
      $paramArray['customfields'] = $params["customfields"]; 
      $paramArray['domain'] = $params["domain"]; 
	  $clientObj = new MachPanelClientHandler();
	  $RespArgs = $clientObj->SvcClient->UpdateWHMCSAccount($paramArray)->UpdateWHMCSAccountResult;
	  if(!$RespArgs->ResponseStatus)
	  {
		  return "Cancel account request ended with message: ".$RespArgs->ResponseMessage;
	  }
	  else
	  {
		  return "success";
	  }
  }
  catch(Exception $sf)
	{
		$errMsg = 'Error: '.$sf->getMessage();
		$errMsg = $errMsg.'<br /><b>Request:</b> '.$clientObj->SvcClient->__getLastRequest();
		$errMsg = $errMsg.'<br /><b>Response:</b> '.$clientObj->SvcClient->__getLastResponse();
		$errMsg = $errMsg.'<br /><b>Request Header:</b> '.$clientObj->SvcClient->__getLastRequestHeaders();
		$errMsg = $errMsg.'<br /><b>Response Header:</b> '.$clientObj->SvcClient->__getLastResponseHeaders();
		throw new Exception('Soap Fault in submitting the order. Details: '.$errMsg);
	}
}

function machpanel_SuspendAccount($params) {

	# Code to perform action goes here...
	try
  {
	  $paramArray = array();
	  $paramArray['WServiceId'] = $params["serviceid"];
	  $paramArray['action'] = "Suspend"; 
	  $clientObj = new MachPanelClientHandler();
	  $RespArgs = $clientObj->SvcClient->UpdateWHMCSAccount($paramArray)->UpdateWHMCSAccountResult;
	  if(!$RespArgs->ResponseStatus)
	  {
		  return "Suspend account request ended with message: ".$RespArgs->ResponseMessage;
	  }
	  else
	  {
		  return "success";
	  }
  }
  catch(Exception $sf)
	{
		$errMsg = 'Error: '.$sf->getMessage();
		$errMsg = $errMsg.'<br /><b>Request:</b> '.$clientObj->SvcClient->__getLastRequest();
		$errMsg = $errMsg.'<br /><b>Response:</b> '.$clientObj->SvcClient->__getLastResponse();
		$errMsg = $errMsg.'<br /><b>Request Header:</b> '.$clientObj->SvcClient->__getLastRequestHeaders();
		$errMsg = $errMsg.'<br /><b>Response Header:</b> '.$clientObj->SvcClient->__getLastResponseHeaders();
		throw new Exception('Soap Fault in submitting the order. Details: '.$errMsg);
	}
}

function machpanel_UnsuspendAccount($params) {

	# Code to perform action goes here...

  try
  {
	  $paramArray = array();
	  $paramArray['WServiceId'] = $params["serviceid"];
	  $paramArray['action'] = "Resume"; 
	  $clientObj = new MachPanelClientHandler();
	  $RespArgs = $clientObj->SvcClient->UpdateWHMCSAccount($paramArray)->UpdateWHMCSAccountResult;
	  if(!$RespArgs->ResponseStatus)
	  {
		  return "Resume account request ended with message: ".$RespArgs->ResponseMessage;
	  }
	  else
	  {
		  return "success";
	  }
  }
  catch(Exception $sf)
	{
		$errMsg = 'Error: '.$sf->getMessage();
		$errMsg = $errMsg.'<br /><b>Request:</b> '.$clientObj->SvcClient->__getLastRequest();
		$errMsg = $errMsg.'<br /><b>Response:</b> '.$clientObj->SvcClient->__getLastResponse();
		$errMsg = $errMsg.'<br /><b>Request Header:</b> '.$clientObj->SvcClient->__getLastRequestHeaders();
		$errMsg = $errMsg.'<br /><b>Response Header:</b> '.$clientObj->SvcClient->__getLastResponseHeaders();
		throw new Exception('Soap Fault in submitting the order. Details: '.$errMsg);
	}
}

function machpanel_ChangePassword($params) {

	# Code to perform action goes here...

    if ($successful) {
		$result = "success";
	} else {
		$result = "Error Message Goes Here...";
	}
	return $result;

}

function machpanel_ChangePackage($params) {
	# Code to perform action goes here...
  try
  {
	  $clientObj = new MachPanelClientHandler();
    
	  $paramArray = array();
	  $paramArray['WServiceId'] = $params["serviceid"];
	  $paramArray['WProductId'] = $params["pid"]; 
	  $RespArgs = $clientObj->SvcClient->SwitchWHMCSSubscriptionPackage($paramArray)->SwitchWHMCSSubscriptionPackageResult;
    
    if ($RespArgs->ResponseStatus) 
    {
		  $result = "success";
	  } 
    else 
    {
		  $result = "Change package server module request ended with message: ". $RespArgs->ResponseMessage;
	  }
    
    if(isset($params['configoptions']))
    {
      $result = $clientObj->submitConfigOptions($params);
    }
    
	  return $result;
  }
  catch(Exception $sf)
	{
		$errMsg = 'Error: '.$sf->getMessage();
		$errMsg = $errMsg.'<br /><b>Request:</b> '.$clientObj->SvcClient->__getLastRequest();
		$errMsg = $errMsg.'<br /><b>Response:</b> '.$clientObj->SvcClient->__getLastResponse();
		$errMsg = $errMsg.'<br /><b>Request Header:</b> '.$clientObj->SvcClient->__getLastRequestHeaders();
		$errMsg = $errMsg.'<br /><b>Response Header:</b> '.$clientObj->SvcClient->__getLastResponseHeaders();
		throw new Exception('Soap Fault in submitting the order. Details: '.$errMsg);
	}
}

 function machpanel_ClientArea($params) 
 {
    // # Output can be returned like this, or defined via a clientarea.tpl template file (see docs for more info)
	$clientObj = new MachPanelClientHandler();
	 $code = '<form action="'.$clientObj->BaseUrl.'/auth/login.aspx" method="post" target="_blank">
	<input type="hidden" name="uid" value="'.$clientObj->encrypt($params["clientsdetails"]["userid"]).'" />
	<input type="hidden" name="svcid" value="'.$clientObj->encrypt($params["serviceid"]).'" />
	<input type="hidden" name="scode" value="'.$clientObj->securityCode.'" />
	<input type="submit" value="Login to Control Panel" />';
	
  try
  {
	  $clientObj = new MachPanelClientHandler();
    
	  $paramArray = array();
	  $paramArray['WServiceId'] = $params["serviceid"];
	  $paramArray['WProductId'] = $params["pid"]; 
	  $paramArray['WUserId'] = $params["clientsdetails"]['userid'];
	  $paramArray['WUserPass'] = $clientObj->getClientCustomField('ServerPassword', $params["clientsdetails"]['userid']);
	  
	  $serviceData = $clientObj->SvcClient->GetWHMCSServiceData($paramArray)->GetWHMCSServiceDataResult;

	  $serviceData = json_decode($serviceData,true);
	  $code = $code . "<br />";
	  foreach($serviceData as $x => $x_value) {
		  $code = $code . "<div><span>" . $x . "</span>:<span>" . $x_value . "</span></div>";
	  }
  }
  catch(Exception $sf)
	{
		$errMsg = 'Error: '.$sf->getMessage();
		$errMsg = $errMsg.'<br /><b>Request:</b> '.$clientObj->SvcClient->__getLastRequest();
		$errMsg = $errMsg.'<br /><b>Response:</b> '.$clientObj->SvcClient->__getLastResponse();
		$errMsg = $errMsg.'<br /><b>Request Header:</b> '.$clientObj->SvcClient->__getLastRequestHeaders();
		$errMsg = $errMsg.'<br /><b>Response Header:</b> '.$clientObj->SvcClient->__getLastResponseHeaders();
		logModuleCall(
            'machpanel',
            __FUNCTION__,
            $params,
            $errMsg,
            $sf->getTraceAsString()
        );
	}
	$code = $code .'</form>';
	return $code;
 }

function machpanel_AdminLink($params) 
{
	$clientObj = new MachPanelClientHandler();
	$code = '<form action="'.$clientObj->BaseUrl.'/auth/login.aspx" method="post" target="_blank">
	<input type="hidden" name="aid" value="'.$clientObj->encrypt($clientObj->getAdminEmail($_SESSION['adminid'])).'" />
	<input type="hidden" name="svcid" value="'.$clientObj->encrypt($params["serviceid"]).'" />
	<input type="hidden" name="scode" value="'.$clientObj->securityCode.'" />
	<input type="submit" value="Login to Control Panel" />
	</form>';
	 return $code;
 }

 function machpanel_LoginLink($params) 
 {
	$clientObj = new MachPanelClientHandler();
	echo "<a href=\"".(string)$clientObj->BaseUrl."/auth/login.aspx?"
	."aid=".urlencode($clientObj->encrypt($clientObj->getAdminEmail($_SESSION['adminid'])))
	."&svcid=".urlencode($clientObj->encrypt($params["serviceid"]))
	."&scode=".$clientObj->securityCode
	."\" target=\"_blank\" style=\"color:#cc7700\">login to control panel</a><br />";
 }

// function machpanel_reboot($params) {

	// # Code to perform reboot action goes here...

    // if ($successful) {
		// $result = "success";
	// } else {
		// $result = "Error Message Goes Here...";
	// }
	// return $result;

// }

// function machpanel_shutdown($params) {

	// # Code to perform shutdown action goes here...

    // if ($successful) {
		// $result = "success";
	// } else {
		// $result = "Error Message Goes Here...";
	// }
	// return $result;

// }

// function machpanel_ClientAreaCustomButtonArray() {
    // $buttonarray = array(
	 // "Reboot Server" => "reboot",
	// );
	// return $buttonarray;
// }

// function machpanel_AdminCustomButtonArray() {
    // $buttonarray = array(
	 // "Reboot Server" => "reboot",
	 // "Shutdown Server" => "shutdown",
	// );
	// return $buttonarray;
// }

// function machpanel_extrapage($params) {
    // $pagearray = array(
     // 'templatefile' => 'example',
     // 'breadcrumb' => ' > <a href="#">Example Page</a>',
     // 'vars' => array(
        // 'var1' => 'demo1',
        // 'var2' => 'demo2',
     // ),
    // );
	// return $pagearray;
// }

// function machpanel_UsageUpdate($params) {

	// $serverid = $params['serverid'];
	// $serverhostname = $params['serverhostname'];
	// $serverip = $params['serverip'];
	// $serverusername = $params['serverusername'];
	// $serverpassword = $params['serverpassword'];
	// $serveraccesshash = $params['serveraccesshash'];
	// $serversecure = $params['serversecure'];

	// # Run connection to retrieve usage for all domains/accounts on $serverid

	// # Now loop through results and update DB

	// foreach ($results AS $domain=>$values) {
        // update_query("tblhosting",array(
         // "diskused"=>$values['diskusage'],
         // "dislimit"=>$values['disklimit'],
         // "bwused"=>$values['bwusage'],
         // "bwlimit"=>$values['bwlimit'],
         // "lastupdate"=>"now()",
        // ),array("server"=>$serverid,"domain"=>$values['domain']));
    // }

// }

 function machpanel_AdminServicesTabFields($params) {

    // $result = select_query("mod_customtable","",array("serviceid"=>$params['serviceid']));
    // $data = mysql_fetch_array($result);
    // $var1 = $data['var1'];
    // $var2 = $data['var2'];
    // $var3 = $data['var3'];
    // $var4 = $data['var4'];

    // $fieldsarray = array(
     // 'Field 1' => '<input type="text" name="modulefields[0]" size="30" value="'.$var1.'" />',
     // 'Field 2' => '<select name="modulefields[1]"><option>Val1</option</select>',
     // 'Field 3' => '<textarea name="modulefields[2]" rows="2" cols="80">'.$var3.'</textarea>',
     // 'Field 4' => $var4, # Info Output Only
    // );
    // return $fieldsarray;

  try
  {
	  $clientObj = new MachPanelClientHandler();
    
	  $paramArray = array();
	  $paramArray['WServiceId'] = $params["serviceid"];
	  $paramArray['WProductId'] = $params["pid"]; 
	  $paramArray['WUserId'] = $params["clientsdetails"]['userid'];
	  $paramArray['WUserPass'] = $clientObj->getClientCustomField('ServerPassword', $params["clientsdetails"]['userid']);
	  
	  $serviceData = $clientObj->SvcClient->GetWHMCSServiceData($paramArray)->GetWHMCSServiceDataResult;

	  return json_decode($serviceData,true);
  }
  catch(Exception $sf)
	{
		$errMsg = 'Error: '.$sf->getMessage();
		$errMsg = $errMsg.'<br /><b>Request:</b> '.$clientObj->SvcClient->__getLastRequest();
		$errMsg = $errMsg.'<br /><b>Response:</b> '.$clientObj->SvcClient->__getLastResponse();
		$errMsg = $errMsg.'<br /><b>Request Header:</b> '.$clientObj->SvcClient->__getLastRequestHeaders();
		$errMsg = $errMsg.'<br /><b>Response Header:</b> '.$clientObj->SvcClient->__getLastResponseHeaders();
		logModuleCall(
            'machpanel',
            __FUNCTION__,
            $params,
            $errMsg,
            $sf->getTraceAsString()
        );
	}
}

// function machpanel_AdminServicesTabFieldsSave($params) {
    // update_query("mod_customtable",array(
        // "var1"=>$_POST['modulefields'][0],
        // "var2"=>$_POST['modulefields'][1],
        // "var3"=>$_POST['modulefields'][2],
    // ),array("serviceid"=>$params['serviceid']));
// }

?>