<?php
  ini_set('display_errors', 'On');
  require __DIR__ . '/vendor/autoload.php';
  require_once('storage.php');
  
  
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }
  
  	include("../php/configi.php");


  $theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($conn, $theValue) : mysqli_escape_string($conn, $theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

	 include '../php/configi.php';

  // Use this class to deserialize error caught
  use XeroAPI\XeroPHP\AccountingObjectSerializer;

  // Storage Classe uses sessions for storing token > extend to your DB of choice
  $storage = new StorageClass();
  $xeroTenantId = (string)$storage->getSession()['tenant_id'];
  
          $client_id = "27027BE7EFE34FE49F5D123C0F35AD58";
  $client_secret = "7H4ZDXOWBpBiJZEvExAmS9liKiBp1ShIl7g7-uxxCFc8U-wH";
  
  $callback_url = "https://app.phoenixcrm.co.nz/crm/xero/callback.php";
  
    $callback_url = "http://localhost/app.phoenixcrm.co.nz/crm/xero/callback.php";
	
	    $callback_url = "http://localhost/app.phoenixcrm.co.nz/crm/xeroadmin/callback.php";


  if ($storage->getHasExpired()) {
    $provider = new \League\OAuth2\Client\Provider\GenericProvider([
      'clientId'                => $client_id,
      'clientSecret'            => $client_secret,
      'redirectUri'             => $callback_url,
      'urlAuthorize'            => 'https://login.xero.com/identity/connect/authorize',
      'urlAccessToken'          => 'https://identity.xero.com/connect/token',
      'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation'
    ]);

    $newAccessToken = $provider->getAccessToken('refresh_token', [
      'refresh_token' => $storage->getRefreshToken()
    ]);

    // Save my token, expiration and refresh token
    $storage->setToken(
        $newAccessToken->getToken(),
        $newAccessToken->getExpires(),
        $xeroTenantId,
        $newAccessToken->getRefreshToken(),
        $newAccessToken->getValues()["id_token"] );
  }

  $config = XeroAPI\XeroPHP\Configuration::getDefaultConfiguration()->setAccessToken( (string)$storage->getSession()['token'] );
  $apiInstance = new XeroAPI\XeroPHP\Api\AccountingApi(
      new GuzzleHttp\Client(),
      $config
  );
  
  $message = "no API calls";
  if (isset($_GET['action'])) {
    if ($_GET["action"] == 1) {
        // Get Organisation details
		
		
		print_r($xeroTenantId);
		
		echo "<br>";
		
		
		print_r($apiInstance->getOrganisations($xeroTenantId));
		
		
        $apiResponse = $apiInstance->getOrganisations($xeroTenantId);
        $message = 'Organisation Name: ' . $apiResponse->getOrganisations()[0]->getName();
    } else if ($_GET["action"] == 2) {
        // Create Contact
        try {
            $person = new XeroAPI\XeroPHP\Models\Accounting\ContactPerson;
            $person->setFirstName("John")
                ->setLastName("Smith")
                ->setEmailAddress("john.smith@24locks.com")
                ->setIncludeInEmails(true);

            $arr_persons = [];
            array_push($arr_persons, $person);

            $contact = new XeroAPI\XeroPHP\Models\Accounting\Contact;
            $contact->setName('FooBar')
                ->setFirstName("Foo")
                ->setLastName("Bar")
                ->setEmailAddress("ben.bowden@24locks.com")
                ->setContactPersons($arr_persons);
            
            $arr_contacts = [];
            array_push($arr_contacts, $contact);
            $contacts = new XeroAPI\XeroPHP\Models\Accounting\Contacts;
            $contacts->setContacts($arr_contacts);

            $apiResponse = $apiInstance->createContacts($xeroTenantId,$contacts);
            $message = 'New Contact Name: ' . $apiResponse->getContacts()[0]->getName();
        } catch (\XeroAPI\XeroPHP\ApiException $e) {
            $error = AccountingObjectSerializer::deserialize(
                $e->getResponseBody(),
                '\XeroAPI\XeroPHP\Models\Accounting\Error',
                []
            );
            $message = "ApiException - " . $error->getElements()[0]["validation_errors"][0]["message"];
        }

    } else if ($_GET["action"] == 3) {
        $if_modified_since = new \DateTime("2023-07-01T00:00:00+01:00"); // \DateTime | Only records created or modified since this timestamp will be returned
    //    $if_modified_since = null;
        $where = 'Type=="ACCREC"'; // string
        $where = null;
        $order = null; // string
        $ids = null; // string[] | Filter by a comma-separated list of Invoice Ids.
        $invoice_numbers = null; // string[] |  Filter by a comma-separated list of Invoice Numbers.
        $contact_ids = null; // string[] | Filter by a comma-separated list of ContactIDs.
     //   $statuses = array("DRAFT", "SUBMITTED");
	  $statuses = array();
        $page = 1; // int | e.g. page=1 – Up to  invoices will be returned in a single API call with line items
        $include_archived = null; // bool | e.g. includeArchived=true - Contacts with a status of ARCHIVED will be included
        $created_by_my_app = null; // bool | When set to true you'll only retrieve Invoices created by your app
        $unitdp = null; // int | e.g. unitdp=4 – You can opt in to use four decimal places for unit amounts

        try {
            $apiResponse = $apiInstance->getInvoices($xeroTenantId, $if_modified_since, $where, $order, $ids, $invoice_numbers, $contact_ids, $statuses, $page, $include_archived, $created_by_my_app, $unitdp);
            if (  count($apiResponse->getInvoices()) > 0 ) {
				
                $message = 'Total invoices found: ' . count($apiResponse->getInvoices());
							echo "<pre>";
							
							echo $message;

				
				print_r($apiResponse->getInvoices());
				
				$x = 1;
				
				do {
					
				
					
				//	echo "in loop";
				
					$contact_id = $apiResponse->getInvoices()[$x]["contact"]["contact_id"];
					$line_items = count($apiResponse->getInvoices()[$x]["line_items"]);
					
					echo $contact_id." " . $line_items."<br>";

					
					$xli = 0;
				
					do {
						  
						$line_item_id		=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["line_item_id"];
						$description		=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["description"];
						$quantity			=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["quantity"];
						$unit_amount		=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["unit_amount"];
						$item_code			=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["item_code"];
						$account_code		=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["account_code"];
						$tax_type			=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["tax_type"];
						$tax_amount			=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["tax_amount"];
						$line_amount		=	$apiResponse->getInvoices()[$x]["line_items"][$xli]["line_amount"];
						
						$contact_id2 						= 	GetSQLValueString($contact_id, "text");
						
						$line_item_id 						= 	GetSQLValueString($line_item_id, "text");
						$description 						= 	GetSQLValueString($description, "text");
						$quantity 						= 	GetSQLValueString($quantity, "double");
						$unit_amount 						= 	GetSQLValueString($unit_amount, "text");
						$item_code 						= 	GetSQLValueString($item_code, "text");
						$account_code 						= 	GetSQLValueString($account_code, "text");
						$tax_type 						= 	GetSQLValueString($tax_type, "text");
						$tax_amount 						= 	GetSQLValueString($tax_amount, "double");
						$line_amount 						= 	GetSQLValueString($line_amount, "double");
						
						echo $item_code;
							
						$phxcrmclient_id = 100;


		$queryinsertli = "insert into ".$phxcrmclient_id."_client_recurr (uid_xero, r_descr, r_qty, r_unit, r_item_code,r_line_amt) values(".$contact_id2.",".$description.",".$quantity.",".$unit_amount.",".$item_code.",".$line_amount.")";
	
		echo $queryinsertli;		

		$resultli=mysqli_query($conn, $queryinsertli);		
					
					
						$xli = $xli + 1;
					
					} while ($xli+1 <=  count($apiResponse->getInvoices()[$x]["line_items"]));
				
					$x = $x + 1;
			
				} while ($x+1 <=  count($apiResponse->getInvoices()));
				
            } else {
                $message = "No invoices found matching filter criteria";
            }
        } catch (Exception $e) {
            echo 'Exception when calling AccountingApi->getInvoices: ', $e->getMessage(), PHP_EOL;
        }
    } else if ($_GET["action"] == 4) {
        // Create Multiple Contacts
        try {
            $contact = new XeroAPI\XeroPHP\Models\Accounting\Contact;
            $contact->setName('George Jetson')
                ->setFirstName("George")
                ->setLastName("Jetson")
                ->setEmailAddress("george.jetson@aol.com");

            // Add the same contact twice - the first one will succeed, but the
            // second contact will throw a validation error which we'll catch.
            $arr_contacts = [];
            array_push($arr_contacts, $contact);
            array_push($arr_contacts, $contact);
            $contacts = new XeroAPI\XeroPHP\Models\Accounting\Contacts;
            $contacts->setContacts($arr_contacts);

            $apiResponse = $apiInstance->createContacts($xeroTenantId,$contacts,false);
            $message = 'First contacts created: ' . $apiResponse->getContacts()[0]->getName();

            if ($apiResponse->getContacts()[1]->getHasValidationErrors()) {
                $message = $message . '<br> Second contact validation error : ' . $apiResponse->getContacts()[1]->getValidationErrors()[0]["message"];
            }

        } catch (\XeroAPI\XeroPHP\ApiException $e) {
            $error = AccountingObjectSerializer::deserialize(
                $e->getResponseBody(),
                '\XeroAPI\XeroPHP\Models\Accounting\Error',
                []
            );
            $message = "ApiException - " . $error->getElements()[0]["validation_errors"][0]["message"];
        }
    } else if ($_GET["action"] == 5) {
		
	  //	include("../php/configi.php");

		echo "tis 5";

        $if_modified_since = new \DateTime("2019-01-02T19:20:30+01:00"); // \DateTime | Only records created or modified since this timestamp will be returned
		
		$if_modified_since = null;
        $where = null;
        $order = null; // string
        $ids = null; // string[] | Filter by a comma-separated list of Invoice Ids.
        $page = 19; // int | e.g. page=1 – Up to  invoices will be returned in a single API call with line items
        $include_archived = null; // bool | e.g. includeArchived=true - Contacts with a status of ARCHIVED will be included
   
        try {
			
			
            $apiResponse = $apiInstance->getContacts($xeroTenantId, $if_modified_since, $where, $order, $ids, $page, $include_archived);
		//	print_r($apiResponse->getContacts());
            if (  count($apiResponse->getContacts()) > 0 ) {
                $message = 'Total contacts found: ' . count($apiResponse->getContacts());
				
				$x = 1;
				

			//	$keys = array_keys($apiResponse->getContacts());

//$obj = json_encode($apiResponse->getContacts(),true);

//print_r($apiResponse->getContacts());

			


	//	exit;

			//	echo "<pre>";
			//	print_r($apiResponse->getContacts());
			//	echo "</pre>";
				
			//	exit;
				
				
            } else {
                $message = "No contacts found matching filter criteria";
            }
			
			  	include("../php/configi.php");
				
				
	//	$queryinsert2 = "truncate ".$phxcrmclient_id."_client_accounting";
	
	//	echo $queryinsert2;

	//	$result2=mysqli_query($conn, $queryinsert2);
				
				$x = 0;
				
				do {
					//	print $x;
					//		print_r($apiResponse->getContacts()[$x]["contact_id"]);
					//	print_r($apiResponse->getContacts()[$x]["name"]);
					//	print_r($apiResponse->getContacts()[$x]["contact_status"]);
					//	echo "<br>";
						
						$contact_id = $apiResponse->getContacts()[$x]["contact_id"];
						$account_number = $apiResponse->getContacts()[$x]["account_number"];
						$contact_name = $apiResponse->getContacts()[$x]["name"];
						$email_address = $apiResponse->getContacts()[$x]["email_address"];
						$c_status = $apiResponse->getContacts()[$x]["contact_status"];
						$cont_name = $apiResponse->getContacts()[$x]["first_name"] . " " . $apiResponse->getContacts()[$x]["last_name"];
						
						$cont_name = trim($cont_name);
						
						
						
						echo "dave";
						
						print_r($apiResponse->getContacts()[$x]["phones"]);
						
						
					//	exit;
						
						
				//		print_r($apiResponse->getContacts()[$x]["phones"][0]["phone_type"]);
				//		print_r($apiResponse->getContacts()[$x]["phones"][0]["phone_number"]);
						
				//		exit;
						
						//	print_r($apiResponse->getContacts()[$x]["addresses"]);

//exit;
													$c_physaddr1 = "";
							$c_physaddr2 = "";
							$c_physaddr3 = "";
							$c_physaddr4 = "";
							$c_physaddr5 = "";
							
							$c_acctaddr1 = "";
							$c_acctaddr2 = "";
							$c_acctaddr3 = "";
							$c_acctaddr4 = "";
							$c_acctaddr5 = "";
						
						$ax = 0;
							
						$count_addresses = count($apiResponse->getContacts()[$x]["addresses"]);
						
						echo "count addresses is ".$count_addresses;
						
						do {
							
							echo "ax is". $ax;
							


							
							if ($apiResponse->getContacts()[$x]["addresses"][$ax]["address_type"] == "STREET"){
								
								echo "tis street";
								
							

								$c_physaddr1 = $apiResponse->getContacts()[$x]["addresses"][$ax]["address_line1"];
								$c_physaddr2 = $apiResponse->getContacts()[$x]["addresses"][$ax]["address_line2"];
								$c_physaddr3 = $apiResponse->getContacts()[$x]["addresses"][$ax]["address_line3"];
								$c_physaddr4 = $apiResponse->getContacts()[$x]["addresses"][$ax]["address_line4"];
								$c_physaddr5 = $apiResponse->getContacts()[$x]["addresses"][$ax]["attention_to"];
							
							
					//		print_r($apiResponse->getContacts()[$x]["addresses"][$ax]["city"]);
					//		print_r($apiResponse->getContacts()[$x]["addresses"][$ax]["region"]);
					//		print_r($apiResponse->getContacts()[$x]["addresses"][$ax]["postcode"]);
					//		print_r($apiResponse->getContacts()[$x]["addresses"][$ax]["country"]);
					//		print_r($apiResponse->getContacts()[$x]["addresses"][$ax]["attention_to"]);
							
							}else if ($apiResponse->getContacts()[$x]["addresses"][$ax]["address_type"] == "POBOX"){

								$c_acctaddr1 = $apiResponse->getContacts()[$x]["addresses"][$ax]["address_line1"];
								$c_acctaddr2 = $apiResponse->getContacts()[$x]["addresses"][$ax]["address_line2"];
								$c_acctaddr3 = $apiResponse->getContacts()[$x]["addresses"][$ax]["address_line3"];
								$c_acctaddr4 = $apiResponse->getContacts()[$x]["addresses"][$ax]["address_line4"];
								$c_acctaddr5 = $apiResponse->getContacts()[$x]["addresses"][$ax]["attention_to"];
															
								
							}
							
								$ax++;
						
						} while ($ax+1 <=  $count_addresses);
						
						
						
						
						$pax = 0;
						
						$fax_phone 		= "";
						$work_phone 	= "";
						$cell_phone		= "";
							
						$count_phones = count($apiResponse->getContacts()[$x]["phones"]);
						
						echo "count_phones is ".$count_phones;
						
						do {
							
							echo "pax is". $pax;
							
							
							if ($apiResponse->getContacts()[$x]["phones"][$pax]["phone_type"] == "DDI"){
								

								$work_phone = $apiResponse->getContacts()[$x]["phones"][$pax]["phone_country_code"] . $apiResponse->getContacts()[$x]["phones"][$pax]["phone_area_code"] . $apiResponse->getContacts()[$x]["phones"][$pax]["phone_number"];
	
							}else if ($apiResponse->getContacts()[$x]["phones"][$pax]["phone_type"] == "MOBILE"){

								$cell_phone = $apiResponse->getContacts()[$x]["phones"][$pax]["phone_country_code"] . $apiResponse->getContacts()[$x]["phones"][$pax]["phone_area_code"] . $apiResponse->getContacts()[$x]["phones"][$pax]["phone_number"];
	
							}else if ($apiResponse->getContacts()[$x]["phones"][$pax]["phone_type"] == "DEFAULT"){

								$work_phone = $apiResponse->getContacts()[$x]["phones"][$pax]["phone_country_code"] . $apiResponse->getContacts()[$x]["phones"][$pax]["phone_area_code"] . $apiResponse->getContacts()[$x]["phones"][$pax]["phone_number"];															
	
							}else if ($apiResponse->getContacts()[$x]["phones"][$pax]["phone_type"] == "FAX"){

								$fax_phone = $apiResponse->getContacts()[$x]["phones"][$pax]["phone_country_code"] . $apiResponse->getContacts()[$x]["phones"][$pax]["phone_area_code"] . $apiResponse->getContacts()[$x]["phones"][$pax]["phone_number"];			
							}
							
								$pax++;
						
						} while ($pax+1 <=  $count_phones);

				//		exit;
						
						// insert
						
						$contact_id 						= 	GetSQLValueString($contact_id, "text");
						$contact_name 						= 	GetSQLValueString($contact_name, "text");
						$cont_name 							= 	GetSQLValueString($cont_name, "text");
						
						$c_physaddr1 						= 	GetSQLValueString($c_physaddr1, "text");
						$c_physaddr2 						= 	GetSQLValueString($c_physaddr2, "text");
						$c_physaddr3 						= 	GetSQLValueString($c_physaddr3, "text");
						$c_physaddr4 						= 	GetSQLValueString($c_physaddr4, "text");
						$c_physaddr5 						= 	GetSQLValueString($c_physaddr5, "text");
						
						$c_acctaddr1 						= 	GetSQLValueString($c_acctaddr1, "text");
						$c_acctaddr2 						= 	GetSQLValueString($c_acctaddr2, "text");
						$c_acctaddr3 						= 	GetSQLValueString($c_acctaddr3, "text");
						$c_acctaddr4 						= 	GetSQLValueString($c_acctaddr4, "text");
						$c_acctaddr5 						= 	GetSQLValueString($c_acctaddr5, "text");

						$fax_phone 							= 	GetSQLValueString($fax_phone, "text");
						$work_phone 						= 	GetSQLValueString($work_phone, "text");			
						$cell_phone 						= 	GetSQLValueString($cell_phone, "text");	
						$email_address 						= 	GetSQLValueString($email_address, "text");
						
						$c_status	 						= 	GetSQLValueString($c_status, "text");
						$account_number						= 	GetSQLValueString($account_number, "text");
			  	include("../php/configi.php");
						
						$phxcrmclient_id = 100;


		$queryinsert = "insert into ".$phxcrmclient_id."_client_accounting (client_tenant_code, comp_name, cont_name, email, client_accounting_no, fax_phone,work_phone,cell_phone, c_physaddr1, c_physaddr2, c_physaddr3, c_physaddr4, c_physaddr5, c_acctaddr1, c_acctaddr2, c_acctaddr3, c_acctaddr4, c_acctaddr5, c_status) values(".$account_number.",".$contact_name.",".$cont_name.",".$email_address.",".$contact_id.",".$fax_phone.",".$work_phone.",".$cell_phone.",".$c_physaddr1.",".$c_physaddr2.",".$c_physaddr3.",".$c_physaddr4.",".$c_physaddr5.",".$c_acctaddr1.",".$c_acctaddr2.",".$c_acctaddr3.",".$c_acctaddr4.",".$c_acctaddr5.",".$c_status.")";
	
		echo $queryinsert . "<br>";
		
	//	exit;

		$result=mysqli_query($conn, $queryinsert);
				mysqli_commit($conn);
			
//exit;			
						
						$x++;

				} while ($x+1 <=  count($apiResponse->getContacts()));
        } catch (Exception $e) {
            echo 'Exception when calling AccountingApi->getContacts: ', $e->getMessage(), PHP_EOL;
        }
		
//		mysqli_close($conn);
    } else if ($_GET["action"] == 6) {

        $jwt = new XeroAPI\XeroPHP\JWTClaims();
        $jwt->setTokenId((string)$storage->getIdToken() );
        // Set access token in order to get authentication event id
        $jwt->setTokenAccess( (string)$storage->getAccessToken() );
        $jwt->decode();

        echo("sub:" . $jwt->getSub() . "<br>");
        echo("sid:" . $jwt->getSid() . "<br>");
        echo("iss:" . $jwt->getIss() . "<br>");
        echo("exp:" . $jwt->getExp() . "<br>");
        echo("given name:" . $jwt->getGivenName() . "<br>");
        echo("family name:" . $jwt->getFamilyName() . "<br>");
        echo("email:" . $jwt->getEmail() . "<br>");
        echo("user id:" . $jwt->getXeroUserId() . "<br>");
        echo("username:" . $jwt->getPreferredUsername() . "<br>");
        echo("session id:" . $jwt->getGlobalSessionId() . "<br>");
        echo("authentication_event_id:" . $jwt->getAuthenticationEventId() . "<br>");

    }
  }
?>
<html>
    <body>
        <ul>
            <li><a href="dave.php?action=1">Get Organisation Name</a></li>
            <li><a href="dave.php?action=3">Get Invoice with Filters</a></li>
            <li><a href="dave.php?action=5">Get Contact with Filters</a></li>
            <li><a href="dave.php?action=6">Get JWT Claims</a></li>
        </ul>
        <div>
        <?php
            echo($message );
        ?>
        </div>
    </body>
</html>