<?php
/**
 * Created by PhpStorm.
 * User: Junaid
 * Date: 08/08/2016
 * Time: 01:16
 */

namespace App\Microsoft\Dynamics;


class crmContact
{
  private $client;
  //private $defaultTypeOverrides = array('accountid' => 'int');
  function __construct($client)
  {
    $this->client = $client;
  }
    function getType($key, $typeOverrides)
    {

        if(array_key_exists($key, $typeOverrides))
        {
            return $typeOverrides[$key];
        }
        else {
            return 'string';
        }
    }

    function buildAttributes($data, $typeOverrides)
    {
        //loop through data array and put create xml based on the keyname and the value
        $templateXml = '<b:KeyValuePairOfstringanyType>
                  <c:key>%s</c:key>
                  <c:value i:type="d:%s" xmlns:d="http://www.w3.org/2001/XMLSchema">%s</c:value>
                </b:KeyValuePairOfstringanyType>';
        $guidTemplateXml = '<b:KeyValuePairOfstringanyType>
          <c:key>%s</c:key>
          <c:value i:type="d:%s" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/">%s</c:value>
        </b:KeyValuePairOfstringanyType>';
        $lookupTemplateXml = '<b:KeyValuePairOfstringanyType>
                  <c:key>parentcustomerid</c:key>
                  <c:value i:type="b:EntityReference">
                    <b:Id>%s</b:Id>
                    <b:KeyAttributes xmlns:d="http://schemas.microsoft.com/xrm/7.1/Contracts"/>
                    <b:LogicalName>account</b:LogicalName>
                    <b:Name i:nil="true"/>
                    <b:RowVersion i:nil="true"/>
                  </c:value>
                </b:KeyValuePairOfstringanyType>';
        $builtXml = "";
        foreach ($data as $key => $value)
        {
            $value = $this->xmlEscape($value);
            //override the tempalte if its accountid. This needs tidying up..
            if($key == "contactid")
            {
              $type  = "guid";
              $attributeXml = sprintf($guidTemplateXml, $key, $type, $value);
            }
            else {
              $type  = $this->getType($key, $typeOverrides);
              if($type == "lookup") {
                  $attributeXml = sprintf($lookupTemplateXml, $value);
              }
              else {
                  $attributeXml = sprintf($templateXml, $key, $type, $value);
              }
            }
            $builtXml = $builtXml . $attributeXml;
        }
        return $builtXml;
    }

    function xmlEscape($string) {
        return str_replace(array('&', '<', '>', '\'', '"'), array('&amp;', '&lt;', '&gt;', '&apos;', '&quot;'), $string);
    }

    function createContact($data, $typeOverrides) {
        $xmlStart = '<s:Body>
    <Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services">
      <request i:type="b:CreateRequest" xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
          <b:KeyValuePairOfstringanyType>
            <c:key>Target</c:key>
            <c:value i:type="b:Entity">
              <b:Attributes>';
        $xmlContinued ='
            </b:Attributes>
              <b:EntityState i:nil="true"/>
              <b:FormattedValues/>
              <b:Id>00000000-0000-0000-0000-000000000000</b:Id>
              <b:KeyAttributes xmlns:d="http://schemas.microsoft.com/xrm/7.1/Contracts"/>
              <b:LogicalName>contact</b:LogicalName>
              <b:RelatedEntities/>
              <b:RowVersion i:nil="true"/>
            </c:value>
          </b:KeyValuePairOfstringanyType>
          <b:KeyValuePairOfstringanyType>
            <c:key>SuppressDuplicateDetection</c:key>
            <c:value i:type="d:boolean" xmlns:d="http://www.w3.org/2001/XMLSchema">true</c:value>
          </b:KeyValuePairOfstringanyType>
        </b:Parameters>
        <b:RequestId i:nil="true"/>
        <b:RequestName>Create</b:RequestName>
      </request>
    </Execute>
  </s:Body>';
        $buildXmlAttributes = $this->buildAttributes($data, $typeOverrides);
        $xml = $xmlStart . $buildXmlAttributes . $xmlContinued;
        $executeSoap = new CrmExecuteSoap ();
        //  echo "agh";
          //print_r($this->client->authHeader);
          //echo $this->client->authHeader;
          //echo $this->client->url;
        $response = $executeSoap->ExecuteSOAPRequest ($this->client->authHeader, $xml, $this->client->url );
        
        // Skip processing if Dynamics response is null/empty (not in use)
        if (!$response || empty($response)) {
            \Log::info('Skipping Dynamics contact operation - no response from authentication');
            return false;
        }
        
        $responsedom = new \DomDocument ();
        $responsedom->loadXML ( $response );

        $firstname = "";
        $lastname = "";

        $values = $responsedom->getElementsbyTagName ( "KeyValuePairOfstringanyType" );

        foreach ( $values as $value ) {
            if ($value->firstChild->textContent == "id") {
                $dynamic_id = $value->lastChild->textContent;
            }

        }

        return $dynamic_id;

    }

    function updateContact($data, $typeOverrides) {
        $xmlStart = '  <s:Body>
    <Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services">
      <request i:type="b:UpdateRequest" xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
          <b:KeyValuePairOfstringanyType>
            <c:key>Target</c:key>
            <c:value i:type="b:Entity">
              <b:Attributes>
            ';
        $xmlContinued = '  </b:Attributes>
              <b:EntityState i:nil="true"/>
              <b:FormattedValues/>
              <b:Id>00000000-0000-0000-0000-000000000000</b:Id>
              <b:KeyAttributes xmlns:d="http://schemas.microsoft.com/xrm/7.1/Contracts"/>
              <b:LogicalName>contact</b:LogicalName>
              <b:RelatedEntities/>
              <b:RowVersion i:nil="true"/>
            </c:value>
          </b:KeyValuePairOfstringanyType>
          <b:KeyValuePairOfstringanyType>
            <c:key>SuppressDuplicateDetection</c:key>
            <c:value i:type="d:boolean" xmlns:d="http://www.w3.org/2001/XMLSchema">true</c:value>
          </b:KeyValuePairOfstringanyType>
        </b:Parameters>
        <b:RequestId i:nil="true"/>
        <b:RequestName>Update</b:RequestName>
      </request>
    </Execute>
  </s:Body>';
  $buildXmlAttributes = $this->buildAttributes($data, $typeOverrides);
  $xml = $xmlStart . $buildXmlAttributes . $xmlContinued;
  $executeSoap = new CrmExecuteSoap ();

  $response = $executeSoap->ExecuteSOAPRequest ($this->client->authHeader, $xml, $this->client->url );
  
  // Skip processing if Dynamics response is null/empty (not in use)
  if (!$response || empty($response)) {
      \Log::info('Skipping Dynamics contact update operation - no response from authentication');
      return false;
  }
  
      $responsedom = new \DomDocument ();
  $responsedom->loadXML ( $response );

  $values = $responsedom->getElementsbyTagName ( "KeyValuePairOfstringanyType" );

  return true;




    }


}
