<?php
ini_set('max_execution_time', 60000);
ini_set("memory_limit", "900M");
//$t_php_name = "Pacific/Auckland";

//date_default_timezone_set($t_php_name);
  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 = "rsoWTBdTReefaCQcotpUs_ge9tvci7qAHy3glpCyHKRB0Jyz-";
  
  $callback_url = "https://app.phoenixcrm.co.nz/crm/xero/callback.php";
  
 // $callback_url = "http://localhost/app.phoenixcrm.co.nz/crm/xero/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
  );
  

  
  function get_contactid($name, $config, $xeroTenantId ){
	//    $config = XeroAPI\XeroPHP\Configuration::getDefaultConfiguration()->setAccessToken( (string)$storage->getSession()['token'] );
  $apiInstance = new XeroAPI\XeroPHP\Api\AccountingApi(
      new GuzzleHttp\Client(),
      $config
  );
  

  
  	 //       $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 = 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;
	//	$name_search = urlencode("Export Meat Warehouse - Taupo");
		
	//	$where = "Name=".$name_search;
		
		$where = 'Name=="'.$name.'"';
        $order = null; // string
        $ids = null; // string[] | Filter by a comma-separated list of Invoice Ids.
        $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
		
		$contacts_found = 0;
		$contact_id 	= "";

        try {
            $apiResponse = $apiInstance->getContacts($xeroTenantId, $if_modified_since, $where, $order, $ids, $page, $include_archived);
            if (  count($apiResponse->getContacts()) > 0 ) {
				
                $message = 'Total contacts found: ' . count($apiResponse->getContacts());
				
				$contacts_found = count($apiResponse->getContacts());
				
				$contact_id = $apiResponse->getContacts()[0]["contact_id"];
				
						//	echo "<pre>";
							
						//	echo $message;

				
			//	print_r($apiResponse->getContacts());
				
			}
			        } catch (Exception $e) {
            echo 'Exception when calling AccountingApi->getContacts: ', $e->getMessage(), PHP_EOL;
        }
		
//		echo "<br>";
		
		return  $contact_id;
		
//		echo "<br>";
	
//		echo "func".$name;
	  
	  
  }

  $message = "no API calls";
$message = "";

  if (isset($_GET['action'])) {
    if ($_GET["action"] == 1) {
        // Get Organisation details
		

		
//		echo "ready for ".$date_from.$sel_region;
		
		
	//	echo "Connected to Xero . error with http interface configuration pruhnoCuSlMAW5Jwsep3W2HV";
		
	//	exit;
		
	//	$querytoprocess = "SELECT * from ".$_COOKIE['phxcrmclient_id']."_client INNER JOIN ".$_COOKIE['phxcrmclient_id']."_st ON ".$_COOKIE['phxcrmclient_id']."_client.uid_client = ".$_COOKIE['phxcrmclient_id']."_st.uid_client WHERE c_region = '".$sel_region."' and (((".$_COOKIE['phxcrmclient_id']."_st.sales_date)='".$date_from."')) and ".$_COOKIE['phxcrmclient_id']."_st.status = 'Ready to Invoice'   order by c_status asc, c_region_sub_sort, comp_name Asc";
		$querytoprocess = "SELECT * from ".$_COOKIE['phxcrmclient_id']."_client where c_status = 'Active' and uid_client <> 1 order by comp_name";
			
	 	echo "d22".$querytoprocess;
		
	//	echo "33 no exit";
		
		$i = 0;
		
	//	exit;
		
		$resulttoprocess=mysqli_query($conn, $querytoprocess);
	


		while($rowtoprocess=mysqli_fetch_array($resulttoprocess)) { 

				$uid_client						= $rowtoprocess['uid_client'];
				$comp_name						= $rowtoprocess['comp_name'];
				$client_accounting_no			= $rowtoprocess['client_accounting_no'];				
				
				
				echo "<br>";
				echo "Processing match for ".$comp_name;
				
				
		//		echo "returned".$contact_id;
				
			//	exit;
				
				
			//	echo "<br>";
			//	echo "process invoice for Job " . $st_id . "Customer ". $comp_name . $contact_id ;
			//	echo "<br>";
			
			
				if ($client_accounting_no == ""){
					
					echo "tis blank";
					
					$contact_id =  get_contactid($comp_name, $config, $xeroTenantId);
					
				//	print_r($contact_id );
					
					echo $i."found".$contact_id;
					
					
					if ($contact_id == ""){
						
					}else{
					
						$contact_id2 						= 	GetSQLValueString($contact_id, "text");
								
						$uclia="update ".$_COOKIE['phxcrmclient_id']."_client set client_accounting_no = ".$contact_id2." where uid_client = ".$uid_client;

						$resultclia=mysqli_query($conn, $uclia);	

					
					}

					
				}
			//	echo $dave;
			
			$i = $i + 1;
				
			sleep(1);

			
			}
		

		
		echo "<br>";

		
		
	
		echo "<br>";
		
		

	}
  }
?>
<html>
    <body>
        <ul>
            <li><a href="matchcust.php?action=1">Match Cust </a></li>
			
			<?php
		// <li><a href="authorizedResource.php?action=6">Create Invoice</a></li>
        ?>
		
		</ul>
        <div>
        <?php
            echo($message );
        ?>
        </div>
    </body>
</html>