<?php

###############################################################################
# domainers.de.php
#
# @author Anil Kumar <akumar@codepunch.com>
# @link   https://codepunch.com
#
############################################################################### 

namespace CodePunch\LU\Registrars;

use Exception;
use CodePunch\Base\Util as UTIL;

###############################################################################

class DomainersDE extends RegistrarAPI {
	
	private $api_url_base  		= 'https://www.domain-bestellsystem.de/soapstatus/wsdl/soap.wsdl';
	private $api_user			= null;
	private $api_password       = null;
	private $contact_info 		= array();
	private $soap_client		= null;
	
	###########################################################################
	
	public function __construct($cm, $user, $password)
	{ 
		parent::__construct($cm);
		$this->api_user = $user;
		$this->api_password = $password;
		$this->do_login();
	}
	
	###########################################################################
	
	public static function getKeyNames()
	{
		return array('API User', 'API Password');
	}
	
	###########################################################################
	
	public function supported() {
		return array('domainlist', 'whois');
	}
	
	###########################################################################
	
	public function do_login()
	{
		if(class_exists("SoapClient")) {
			$params = array('login' => $this->api_user, 'password'=> $this->api_password);
			try {
				$this->soap_client = new \SoapClient($this->api_url_base, $params);
				return $this->soap_client;
			}
			catch (\SoapFault $fault) {
				$this->soap_client = null;
				throw new Exception("SOAP Fault: (faultcode: {$fault->faultcode} {$fault->faultstring})");
			}
		}
	}
	
	###########################################################################

	private function get_contact_info($handle)
	{
		if(isset($this->contact_info[$handle]))
			return $this->contact_info[$handle];
		
		if(!$this->soap_client)
			throw new Exception("Soap client is not initialized");
		else
		{
			try {
				$cinfo = $this->soap_client->handleInfo(array('handle'=>$handle,'clientTRID' => '', 'forReseller' => ''));
				$cinfo = json_decode(json_encode($cinfo), TRUE);
				$cinfo = UTIL::array_flatten($cinfo);
				$this->cleanup_keys($cinfo);
				$fullname = "";
				if(isset($cinfo['First Name']))
					$fullname = $cinfo['First Name'] . " ";
				if(isset($cinfo['Last Name']))
					$fullname .= $cinfo['Last Name'];
				$cinfo['Full Name'] = trim($fullname);
				$contactdata = UTIL::array_to_text($cinfo);
				$this->contact_info[$handle] = $contactdata;
				return $contactdata;
			}
			catch (\SoapFault $fault) {
				$this->soap_client = null;
				throw new Exception("SOAP Fault: (faultcode: {$fault->faultcode} {$fault->faultstring})");
			}
		}
		return false;
	}
	
	###########################################################################
	
	private function cleanup_keys(&$info)
	{
		$xlate = array(
		'domainName' => 'Domain',
		'tld' => 'TLD',
		'primaryNameserver' => 'Primary Name Server',
		'secondaryNameserveritem' => 'Secondary Name Server',
		'nameserversitem0ns' => 'Name Server 0',
		'nameserversitem0ipv4' => 'Name Server 0 IPV4',
		'nameserversitem0ipv6' => 'Name Server 0 IPV6',
		'nameserversitem1ns' => 'Name Server 1',
		'nameserversitem1ipv4' => 'Name Server 1 IPV4',
		'nameserversitem1ipv6' => 'Name Server 1 IPV6',
		'reseller' => 'Reseller',
		'orderDate' => '1491261560',
		'executionDate' => 'Execution Date',
		'systemInDate' => '1491261646',
		'paidUntilDate' => 'Paid Until',
		'toBeDeletedDate' => 'To Deleted On',
		'status' => 'Status',
		'domainStatus' => 'Domain Status',
		'orderNumber' => 'Order No',
		'regType' => 'Registration Type',
		'remarks' => 'Remarks',
		'notifyEmail' => 'Notify Email',
		'tags' => 'Tags',
		'firstname'=> 'First Name',
		'lastname'=> 'Last Name',
		'company'=> 'Organization',
		'street'=> 'Street',
		'pcode'=> 'Postal Code',
		'city'=> 'City',
		'country'=> 'Country',
		'phone'=> 'Phone',
		'fax'=> 'Fax',
		'email'=> 'Email',
		'handle'=> 'Handle',
		'reseller'=> 'reseller',
		'extension'=> 'Extension',
		'returnCode'=> 'Return Code',
		'returnSubCode'=> 'return Subcode',
		'returnMessage'=> 'Return Message',
		'clientTRID'=> 'Client TRID',
		'serverTRID'=> 'Server TRID',
		'extensionvatId' => 'Ext VAT ID',
		'extensioncompanyId' => 'Ext Company ID',
		'extensionpersonId' => 'Ext Person ID',
		'extensiontrademarkId' => 'Ext Tm ID',
		'extensionbirthplace' => 'Ext Birth Place',
		'extensionbirthdate' => 'Ext Birth Date',
		'extensionstate' => 'Ext State',
		'extensionatDiscloseVoice' => 'Ext Voice',
		'extensionatDiscloseFax' => 'Ext Fax',
		'extensionatDiscloseMail' => 'Ext Mail',
		'extensionidAuthority' => 'Ext Authority',
		'extensioncompanyUrl' => 'Ext Company URL',
		'extensioncompanyType' => 'Ext Company Type',
		'extensionpersonJobTitle' => 'Ext Job Title',
		'extensiondunsId' => 'Ext Uns ID',
		'extensionxxxId' => 'Ext XXX ID',
		);
		UTIL::array_xlate_keys($info, $xlate);
	}
	
	###########################################################################
	
	public function whois($domain)
	{
		$responce = array('status'=>false,'error'=>'','data'=>'');
		try {
			if(!$this->soap_client)
				throw new Exception("Soap client is not initialized");
			else {
				try {
					$result = $this->soap_client->domainInfo(array('domainName' => $domain, 'clientTRID' => '', 'forReseller' => ''));
					$result = json_decode(json_encode($result), TRUE);
					if(isset($result['domainsList']['item'])) {
						$result = $result['domainsList']['item'];
						$result = UTIL::array_flatten($result);
						
						if(isset($result['orderDate'])) {
							$result['orderDate'] = trim($result['orderDate']);
							if($result['orderDate'] != "" && $result['orderDate'] != null) 
								$result["Creation Date"] = date("Y-M-d", $result['orderDate']);
							unset($result['orderDate']);
						}
						if(isset($result['systemInDate'])) {
							$result['systemInDate'] = trim($result['systemInDate']);
							if($result['systemInDate'] != "" && $result['systemInDate'] != null) 
								$result["System In Date"] = date("Y-M-d", $result['systemInDate']);
							unset($result['systemInDate']);
						}
						if(isset($result['paidUntilDate'])) {
							$result['paidUntilDate'] = trim($result['paidUntilDate']);
							if($result['paidUntilDate'] != "" && $result['paidUntilDate'] != null) 
								$result["Registrar Registration Expiration Date"] = date("Y-M-d", $result['paidUntilDate']);
							unset($result['paidUntilDate']);
						}
						if(isset($result['toBeDeletedDate'])) {
							$result['toBeDeletedDate'] = trim($result['toBeDeletedDate']);
							if($result['toBeDeletedDate'] != "" && $result['toBeDeletedDate'] != null) 
								$result["Deletion Date"] = date("Y-M-d", $result['toBeDeletedDate']);
							unset($result['toBeDeletedDate']);
						}
						if(!isset($result['registrar']))
							$result['Registrar'] = "DomainerDE";
						
						$allcontacts = "";
						$contactinfo = array();
						$handles = array('ownerC' => 'Owner-C', 'adminC' => 'Admin-C', 'techC' => 'Tech-C', 'zoneC' => 'Zone-C');
						foreach($handles as $h => $v)
						{
							if(isset($result[$h]))
							{
								$contactinfo[$h] = $this->get_contact_info($result[$h]);
								$allcontacts .= "\n\n[{$v}]\n" . $contactinfo[$h];
								unset($result[$h]);
							}
						}
						$unsetkeys = array('nameserversitem0ipv4', 'nameserversitem0ipv6', 'nameserversitem1ipv4', 'nameserversitem1ipv6', /*'nameserversitem0ns', 'nameserversitem1ns'*/);
						foreach($unsetkeys as $key)
							unset($result[$key]);
						$this->cleanup_keys($result);
						$whois = UTIL::array_to_text($result);
						$whois .= $allcontacts;
						$responce['data'] = $whois;
						$responce['status'] = true;
					}
					else
					{
						if(isset($result['returnMessage'])) {
							if($result['returnMessage'] == $this->notfound_token)
								throw new Exception("Domain is not present in your profile");
						}
						else
							throw new Exception("Unable to connect to DomainersDE SOAP server");
					}
				}
				catch (\SoapFault $fault) {
					$this->soap_client = null;
					throw new Exception("SOAP Fault: (faultcode: {$fault->faultcode} {$fault->faultstring})");
				}
			}
		}
		catch (Exception $e) {
			$responce['error'] = $e->getMessage();
		}
		return $responce;
	}
	
	###########################################################################

	public function isWorking()
	{
		if($this->soap_client) {
			try {
				$result = $this->soap_client->domainCheck(array('domainName' =>"example.org",'domainNameAce' => "",'clientTRID' => '','forReseller' => ''));
				return true;
			}
			catch (\SoapFault $fault) {
				return "[{$fault->faultcode}]: {$fault->faultstring}";
			}
		}
		else
			return "Soap client is not initialized";
		return "Unable to connect";
	}

	###########################################################################
	
	public function domainlist(?callable $callback=null)
	{
		$domains = array();
		if(!$this->soap_client)
			throw new Exception("Soap client is not initialized");
		else {
			try {
				$limit = 1000;
				$offset = 0;
				while(1) {
					$thisdata = array();
					$added = 0;
					$result = $this->soap_client->domainList(array('limit'=>$limit,'offset'=>$offset, 'clientTRID' => '', 'forReseller' => ''));
					$result = json_decode(json_encode($result), TRUE);
					if(isset($result['domainsList']['item']))
					{
						$dlist = $result['domainsList']['item'];
						if(is_array($dlist))
						{
							foreach($dlist as $di)
							{
								$thisdata[] = $di['domainName'];
								$added++;
							}
						}
					}
					else {
						if(isset($result['returnMessage']) == "No matches found.") {
							break;
						}
					}
					if($added == 0)
						break;
					if($callback != null) {
						$status = call_user_func($callback, "", count($domains), $thisdata);
						if($status == self::REGAPI_STOP)
							break;
					}
					if(count($thisdata))
						$domains = array_merge($domains, $thisdata);
					$offset += $added;
				}
			}
			catch (\SoapFault $fault) {
				$this->soap_client = null;
				throw new Exception("SOAP Fault: (faultcode: {$fault->faultcode} {$fault->faultstring})");
			}
		}
		return $domains;
	}
}

###############################################################################

?>