<?php
require_once(__DIR__."/include/crest.php");
require_once(__DIR__."/include/header.php");
require_once(__DIR__."/include/stripe/init.php");
require_once (__DIR__.'/phpexcel-1.9/Classes/PHPExcel.php');
require_once(__DIR__.'/PHPWord/autoload.php');
/*
use PhpOffice\PhpWord\Element\TextRun;
use PhpOffice\PhpWord\Element\Link;
use PhpOffice\PhpWord\Exception\Exception as PhpWordException;
use PhpOffice\PhpWord\TemplateProcessor;
*/
$rand = rand(0,500);
?>
<ul>
	<li><a href="/export_to_excel_app/index.php?test=user.current&rand=<?=$rand?>">User Info</a></li>
	<li>---</li>
	<li>---</li>
	<li><a href="/export_to_excel_app/index.php?test=event.bind.placement&rand=<?=$rand?>">Add app's Quote buttons</a></li>
	<li><a href="/export_to_excel_app/index.php?test=event.unbind.placement&rand=<?=$rand?>">Remove app's Quote buttons</a></li>
	<li>---</li>
	<li>---</li>
	<li><a href="/export_to_excel_app/index.php?test=event.bind.invoice.placement&rand=<?=$rand?>">Add app's Invoice buttons</a></li>
	<li><a href="/export_to_excel_app/index.php?test=event.unbind.invoice.placement&rand=<?=$rand?>">Remove app's Invoice buttons</a></li>
	<li>---</li>
	<li>***</li>

	<li>DEAL NEW BUTTONS</li>
	<li>---</li>
	<li><a href="/export_to_excel_app/index.php?test=event.bind.deal.quote.placement&rand=<?=$rand?>">Add app's Deal "create quote" buttons</a></li>
	<li><a href="/export_to_excel_app/index.php?test=event.unbind.deal.quote.placement&rand=<?=$rand?>">Remove app's Deal "create quote" buttons</a></li>
	<li>---</li>
	<li>---</li>
	<li><a href="/export_to_excel_app/index.php?test=event.bind.deal.invoice.placement&rand=<?=$rand?>">Add app's Deal "create invoice" buttons</a></li>
	<li><a href="/export_to_excel_app/index.php?test=event.unbind.deal.invoice.placement&rand=<?=$rand?>">Remove app's Deal "create invoice" buttons</a></li>
	<li>---</li>
	<li>***</li>

	<li>---</li>
	<li><a href="/export_to_excel_app/index.php?test=event.bind.onCrmDynamicItemAdd&rand=<?=$rand?>">Add event handler "ON QUOTE ADD"</a></li>
	<li><a href="/export_to_excel_app/index.php?test=event.unbind.onCrmDynamicItemAdd&rand=<?=$rand?>">Remove event handler "ON QUOTE ADD"</a></li>
	<li>---</li>
	<li>---</li>
	<li><a href="/export_to_excel_app/index.php?test=event.bind.onCrmInvoiceAdd&rand=<?=$rand?>">Add event handler "ON INVOICE ADD"</a></li>
	<li><a href="/export_to_excel_app/index.php?test=event.unbind.onCrmInvoiceAdd&rand=<?=$rand?>">Remove event handler "ON INVOICE ADD"</a></li>
	<li>---</li>
	<li>---</li>
	<li><a href="/export_to_excel_app/index.php?test=event.bind.onCrmCompanyAdd&rand=<?=$rand?>">Add event handler "ON COMPANY ADD" (address fix)</a></li>
	<li><a href="/export_to_excel_app/index.php?test=event.unbind.onCrmCompanyAdd&rand=<?=$rand?>">Remove event handler "ON COMPANY ADD" (address fix)</a></li>
	<li>---</li>
	<li>---</li>
	<li><a href="/export_to_excel_app/index.php?test=event.get&rand=<?=$rand?>">Show all binded events</a></li>
	<li>---</li>
</ul>
<?
$dtime = DateTime::createFromFormat("d/m/Y H:i:s", date("d/m/Y H:i:s"));
$current_call_timestamp = $dtime->getTimestamp();
echo date('c', $current_call_timestamp);

$test = isset($_REQUEST["test"]) ? $_REQUEST["test"] : "";
switch($test)
{
	case 'user.current':
		$data = CRest::call('profile');
	break;

	case 'event.bind.placement':
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_QUOTE_DETAIL_TOOLBAR',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Export to Excel',
					'DESCRIPTION' => 'Export to Excel'
				]
			],
		));
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_QUOTE_DETAIL_ACTIVITY',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Export to Excel',
					'DESCRIPTION' => 'Export to Excel'
				]
			],
		));
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_QUOTE_LIST_MENU',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Export to Excel',
					'DESCRIPTION' => 'Export to Excel'
				]
			],
		));
	break;

	case 'event.unbind.placement':
		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_QUOTE_DETAIL_TOOLBAR',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app.php',
		));

		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_QUOTE_DETAIL_ACTIVITY',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app.php',
		));
		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_QUOTE_LIST_MENU',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app.php',
		));
	break;

	case 'event.bind.invoice.placement':
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_SMART_INVOICE_DETAIL_TOOLBAR',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_invoice.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Create .docx invoice',
					'DESCRIPTION' => 'Create .docx invoice'
				]
			],
		));
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_SMART_INVOICE_DETAIL_ACTIVITY',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_invoice.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Create .docx invoice',
					'DESCRIPTION' => 'Create .docx invoice'
				]
			],
		));
	break;

	case 'event.unbind.invoice.placement':
		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_SMART_INVOICE_DETAIL_TOOLBAR',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_invoice.php',
		));
		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_SMART_INVOICE_DETAIL_ACTIVITY',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_invoice.php',
		));
	break;

		
	case 'event.bind.deal.quote.placement':
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_DEAL_DETAIL_TOOLBAR',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_quote.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Create Quote',
					'DESCRIPTION' => 'Create Quote'
				]
			],
		));
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_DEAL_DETAIL_ACTIVITY',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_quote.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Create Quote',
					'DESCRIPTION' => 'Create Quote'
				]
			],
		));
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_DEAL_LIST_MENU',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_quote.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Create Quote',
					'DESCRIPTION' => 'Create Quote'
				]
			],
		));
	break;

	case 'event.unbind.deal.quote.placement':
		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_DEAL_DETAIL_TOOLBAR',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_quote.php',
		));

		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_DEAL_DETAIL_ACTIVITY',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_quote.php',
		));
		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_DEAL_LIST_MENU',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_quote.php',
		));
	break;

	case 'event.bind.deal.invoice.placement':
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_DEAL_DETAIL_TOOLBAR',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_invoice.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Create Invoice',
					'DESCRIPTION' => 'Create Invoice'
				]
			],
		));
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_DEAL_DETAIL_ACTIVITY',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_invoice.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Create Invoice',
					'DESCRIPTION' => 'Create Invoice'
				]
			],
		));
		$data = CRest::call("placement.bind", array(
			'PLACEMENT' => 'CRM_DEAL_LIST_MENU',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_invoice.php',
			'LANG_ALL' => [
				'en' => [
					'TITLE' => 'Create Invoice',
					'DESCRIPTION' => 'Create Invoice'
				]
			],
		));
	break;

	case 'event.unbind.deal.invoice.placement':
		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_DEAL_DETAIL_TOOLBAR',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_invoice.php',
		));

		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_DEAL_DETAIL_ACTIVITY',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_invoice.php',
		));
		$data = CRest::call("placement.unbind", array(
			'PLACEMENT' => 'CRM_DEAL_LIST_MENU',
			'HANDLER' => 'https://app.appliedphysicsinc.com/export_to_excel_app/app_deal_create_invoice.php',
		));
	break;

	case 'event.bind.onCrmDynamicItemAdd':
		$data = CRest::call("event.bind", array(
			"EVENT" => "onCrmQuoteAdd",
			"HANDLER" => "https://app.appliedphysicsinc.com/export_to_excel_app/event_quote_create.php",
		));
	break;

	case 'event.unbind.onCrmDynamicItemAdd':
		$data = CRest::call("event.unbind", array(
			"EVENT" => "onCrmQuoteAdd",
			"HANDLER" => "https://app.appliedphysicsinc.com/export_to_excel_app/event_quote_create.php",
		));
	break;

	case 'event.bind.onCrmInvoiceAdd':
		$data = CRest::call("event.bind", array(
			"EVENT" => "onCrmDynamicItemAdd",
			"HANDLER" => "https://app.appliedphysicsinc.com/export_to_excel_app/event_invoice_add.php",
		));
	break;

	case 'event.unbind.onCrmInvoiceAdd':
		$data = CRest::call("event.unbind", array(
			"EVENT" => "onCrmDynamicItemAdd",
			"HANDLER" => "https://app.appliedphysicsinc.com/export_to_excel_app/event_invoice_add.php",
		));
	break;

	case 'event.bind.onCrmCompanyAdd':
		$data = CRest::call("event.bind", array(
			"EVENT" => "onCrmCompanyAdd",
			"HANDLER" => "https://app.appliedphysicsinc.com/export_to_excel_app/event_company_add.php",
		));
	break;

	case 'event.unbind.onCrmCompanyAdd':
		$data = CRest::call("event.unbind", array(
			"EVENT" => "onCrmCompanyAdd",
			"HANDLER" => "https://app.appliedphysicsinc.com/export_to_excel_app/event_company_add.php",
		));
	break;
		
	case 'event.get':
		$data = CRest::call("event.get");
	break;
	
	default:
		$data = $_SESSION["query_data"];
	break;
}

echo '<pre>';
// $arDocsList_data = CRest::call("crm.documentgenerator.template.list", array());
// print_r($arDocsList_data);
echo '<br>';
echo '<br>';
/*
$arDocsList_data = CRest::call("crm.documentgenerator.template.getfields", array(
	"id" => 10,
	"entityTypeId" => 31,
));
print_r($arDocsList_data);
*/
/*
$arDocsList_data = CRest::call("placement.list", array());
print_r($arDocsList_data);
/*
/*
$arNewInvoice_data = CRest::call("crm.deal.update", array(
	"id" => 458,
	"fields" => [
		'CLOSEDATE' => '07/14/2022'
	],
));
print_r($arNewInvoice_data);
*/
echo '<br>';
echo '<br>';
//$company_id = 2806;
//$company_id = 10022;
/*
$invoice_fields = CRest::call("crm.item.fields", array(
	"entityTypeId" => 31
));
print_r($invoice_fields);
*/
/*
$invoice_fields = CRest::call("crm.item.productrow.fields", []);
print_r($invoice_fields);


$deal_id = "690";
$deal = CRest::call("crm.deal.get", array(
	"id" => $deal_id,
));
$deal_data = $deal['result'];
$contact_id = $deal_data['CONTACT_ID'];
$company_id = $deal_data['COMPANY_ID'];
print_r($deal);
*/
/*
$newInvoice = CRest::call("crm.item.add", array(
	"entityTypeId" => 31,
	"fields" => [
		"title" => $deal_data['TITLE'], 
		"stageId" => "DT31_2:N",
		"opened" => "Y", 
		"assignedById" => $deal_data['ASSIGNED_BY_ID'],
		"currencyId" => "USD", 
		"opportunity" => $deal_data['OPPORTUNITY'],
		"contactId" => $contact_id,
		"companyId" => $company_id,
		"parentId2" => $deal_id,
	]
));
print_r($newInvoice);
*/
/*
$products = CRest::call("crm.item.productrow.list", array(
	"order" => [],
	"filter" => [
		"=ownerType" => "D",
		"=ownerId" => $deal_id
	],
	"start" => "-1",
));
print_r($products);
*/
/*
$newQuote = CRest::call("crm.quote.add", array(
	"fields" => [
		"TITLE" => $deal_data['TITLE'], 
		"STATUS_ID" => "DRAFT",
		"OPENED" => "Y", 
		"ASSIGNED_BY_ID" => $deal_data['ASSIGNED_BY_ID'],
		"CREATED_DY_ID" => $deal_data['ASSIGNED_BY_ID'],
		"CURRENCY_ID" => "USD", 
		"OPPORTUNITY" => $deal_data['OPPORTUNITY'],
		"CONTACT_ID" => $contact_id,
		"COMPANY_ID" => $company_id,
		"DEAL_ID" => $deal_id,
		
	]
));
print_r($newQuote);
*/
/*
$company['UF_CRM_COMPANY_1657288466255'] => USA
$company['UF_CRM_COMPANY_1657534877352'] => Test state
$company['UF_CRM_COMPANY_1657534903298'] => 
$company['UF_CRM_COMPANY_1657534926084'] => Test city
$company['UF_CRM_COMPANY_1657534985446'] => Test address1
$company['UF_CRM_COMPANY_1657535002882'] => Test address2
$company['UF_CRM_1660281609'] => 123456 // zip
*/

/*
$invoice_id = 30;

$arTests = array();
$arTests['DATE TIME'] = date('d.m.Y H:i:s');
$arTests['invoice_id'] = $invoice_id;
//$arTests['entityTypeId'] = $_REQUEST['data']['FIELDS']['ENTITY_TYPE_ID'];

$arNewInvoice_data = CRest::call("crm.item.get", array(
	"entityTypeId" => 31,
	"id" => $invoice_id
));
$invoice_data = $arNewInvoice_data['result']['item'];
$accountNumber = $invoice_data['accountNumber'];
$arTests['invoice_data'] = $invoice_data;
if($invoice_data['opportunity'] < 15000){
	$products = CRest::call("crm.item.productrow.list", array(
		"order" => [],
		"filter" => [
			"=ownerType" => "SI",
			"=ownerId" => $invoice_id
		],
		"start" => "-1",
	));
	$products_list = $products['result']['productRows'];
	$cur_processing_fee = 0;
	if($products_list){
		foreach($products_list as $k => &$product){
			sleep(1);
			$resGoodsList[$k] = CRest::call(
				'catalog.product.get',
				[
					"id" => $product['productId'],
				]
			);
			$cur_processing_fee += $product['price'] * 0.03;
			$new_products_list[$k] = $product;
			$new_products_list[$k]['CATALOG'] = $resGoodsList[$k]['result']['product'];
		}
		$arTests['products_list'] = $new_products_list;
		
		//{APTotalSum}
		$total_sum = number_format($invoice_data['opportunity'], 2, '.', ',');
		$total_sum = '$'.$total_sum; 
		$arTests['total_sum'] = $total_sum;

		//{APTotalSumPlus2P}
		$total_sum_2p = number_format($invoice_data['opportunity'] * 1.02, 2, '.', ',');
		$total_sum_2p = '$'.$total_sum_2p; 
		$arTests['total_sum_2p'] = $total_sum_2p;

		//{APTotalSumPlus3P}
		$total_sum_3p = number_format($invoice_data['opportunity'] * 1.03, 2, '.', ',');
		$total_sum_3p = '$'.$total_sum_3p; 
		$arTests['total_sum_3p'] = $total_sum_3p;

		//{APTotalSumPlus4P}
		$total_sum_4p = number_format($invoice_data['opportunity'] * 1.04, 2, '.', ',');
		$total_sum_4p = '$'.$total_sum_4p; 
		$arTests['total_sum_4p'] = $total_sum_4p;

		//{APTotalSumPlus6P}
		$total_sum_6p = number_format($invoice_data['opportunity'] * 1.06, 2, '.', ',');
		$total_sum_6p = '$'.$total_sum_6p; 
		$arTests['total_sum_6p'] = $total_sum_6p;

		$products = [];
		foreach($new_products_list as $k => $product){
			//{TableItemIndex}
			//{TableItemName}
			//{TableItemPartNumber}
			//{TableItemPriceNetto}
			//{TableItemQuantity}
			//{TableItemPriceExclusiveSum}
			$cur_product = [];
			$cur_product['I'] = $k + 1;
			$cur_product['N'] = $product['productName'];
			$cur_product['P'] = $product['CATALOG']['property98']['value'];
			$cur_product['Price'] = '$'.number_format($product['price'], 2, '.', ',');
			$cur_product['Q'] = $product['quantity'];
			$cur_product['PriceS'] = '$'.number_format($product['price'] * $product['quantity'], 2, '.', ',');
			$products[] = $cur_product;
			$cur_product = [];
		}
		$arTests['products'] = $products;
		/////// STRIPE ///////
			//{APStripeLink}
			$stripe = new \Stripe\StripeClient([
				"api_key" => "sk_test_bwtpXM36hOMSGcFv0nZHJGUf",
				"stripe_version" => "2022-08-01"
			]);
			$prices_for_link = [];
			foreach($new_products_list as $k => $product){
				$new_id = 'site_'.$product['id'];
				$cent_price = (float) $product['price'] * 100;
				try {
					$cur_search[$k] = $stripe->prices->search([
						'query' => "active:'true' AND metadata['site_id']:'".$new_id."'",
					]);
				} catch (\Stripe\Exception\RateLimitException $e) {
					$arTests['cur_search errors'][$k] = 'RateLimitException'. '<br>
					Status is:' . $e->getHttpStatus() . '<br>
					Type is:' . $e->getError()->type . '<br>
					Code is:' . $e->getError()->code . '<br>
					Param is:' . $e->getError()->param . '<br>
					Message is:' . $e->getError()->message . '<br>';
				} catch (\Stripe\Exception\InvalidRequestException $e) {
					$arTests['cur_search errors'][$k] = 'InvalidRequestException'. '<br>
					Status is:' . $e->getHttpStatus() . '<br>
					Type is:' . $e->getError()->type . '<br>
					Code is:' . $e->getError()->code . '<br>
					Param is:' . $e->getError()->param . '<br>
					Message is:' . $e->getError()->message . '<br>';
				} catch (\Stripe\Exception\AuthenticationException $e) {
				} catch (\Stripe\Exception\ApiConnectionException $e) {
					$arTests['cur_search errors'][$k] = 'ApiConnectionException'. '<br>
					Status is:' . $e->getHttpStatus() . '<br>
					Type is:' . $e->getError()->type . '<br>
					Code is:' . $e->getError()->code . '<br>
					Param is:' . $e->getError()->param . '<br>
					Message is:' . $e->getError()->message . '<br>';
				} catch (\Stripe\Exception\ApiErrorException $e) {
					$arTests['cur_search errors'][$k] = 'ApiErrorException'. '<br>
					Status is:' . $e->getHttpStatus() . '<br>
					Type is:' . $e->getError()->type . '<br>
					Code is:' . $e->getError()->code . '<br>
					Param is:' . $e->getError()->param . '<br>
					Message is:' . $e->getError()->message . '<br>';
				}
				$arTests['cur_search'][$k] = $cur_search[$k];
				if(!$cur_search[$k]['data'][0]['id']){
					echo 'NOT FOUND $k';
					echo '<br>';
				}	
				if($cur_search[$k]['data'][0]['id'] == ''){
					echo 'NOT FOUND 2 $k';
					echo '<br>';
				}
				echo '<br>';
				echo '<br>';
				echo '<br>';
				
				if($cur_search[$k]['data'][0]['id'] && $cur_search[$k]['data'][0]['id'] !== ''){
					try {
						$create_price[$k] = $stripe->prices->create([
							'unit_amount_decimal' => $cent_price,
							'currency' => 'usd',
							'product_data' => ['name' => $product['productName']],
							'metadata' => ["site_id" => $new_id],
						]);
					} catch (\Stripe\Exception\RateLimitException $e) {
						$arTests['cur_search errors'][$k] = 'RateLimitException'. '<br>
						Status is:' . $e->getHttpStatus() . '<br>
						Type is:' . $e->getError()->type . '<br>
						Code is:' . $e->getError()->code . '<br>
						Param is:' . $e->getError()->param . '<br>
						Message is:' . $e->getError()->message . '<br>';
					} catch (\Stripe\Exception\InvalidRequestException $e) {
						$arTests['cur_search errors'][$k] = 'InvalidRequestException'. '<br>
						Status is:' . $e->getHttpStatus() . '<br>
						Type is:' . $e->getError()->type . '<br>
						Code is:' . $e->getError()->code . '<br>
						Param is:' . $e->getError()->param . '<br>
						Message is:' . $e->getError()->message . '<br>';
					} catch (\Stripe\Exception\AuthenticationException $e) {
					} catch (\Stripe\Exception\ApiConnectionException $e) {
						$arTests['cur_search errors'][$k] = 'ApiConnectionException'. '<br>
						Status is:' . $e->getHttpStatus() . '<br>
						Type is:' . $e->getError()->type . '<br>
						Code is:' . $e->getError()->code . '<br>
						Param is:' . $e->getError()->param . '<br>
						Message is:' . $e->getError()->message . '<br>';
					} catch (\Stripe\Exception\ApiErrorException $e) {
						$arTests['cur_search errors'][$k] = 'ApiErrorException'. '<br>
						Status is:' . $e->getHttpStatus() . '<br>
						Type is:' . $e->getError()->type . '<br>
						Code is:' . $e->getError()->code . '<br>
						Param is:' . $e->getError()->param . '<br>
						Message is:' . $e->getError()->message . '<br>';
					}
					if($create_price[$k]['id']){
						$prices_for_link[$k]['price'] = $create_price[$k]['id'];
						$prices_for_link[$k]['quantity'] = $product['quantity'];
					}
				}else{
					$prices_for_link[$k]['price'] = $cur_search[$k]['data'][0]['id'];
					$prices_for_link[$k]['quantity'] = $product['quantity'];
				}
				
			}
			
			
			// Adding cur_processing fee
			$cent_cur_processing_fee = (float) $cur_processing_fee * 100;
			$name_cur_processing_fee = "Processing Fee for Invoice #".$accountNumber;
			$new_id_proc_fee = 'processing_fee_invoice_'.$accountNumber.'_'.date('d_m_Y_H_i_s');
			try {
				$create_price_fee = $stripe->prices->create([
					'unit_amount_decimal' => $cent_cur_processing_fee,
					'currency' => 'usd',
					'product_data' => ['name' => $name_cur_processing_fee],
					'metadata' => ["site_id" => $new_id_proc_fee],
				]);
			} catch (\Stripe\Exception\RateLimitException $e) {
				$arTests['cur_search errors'][$k] = 'RateLimitException'. '<br>
				Status is:' . $e->getHttpStatus() . '<br>
				Type is:' . $e->getError()->type . '<br>
				Code is:' . $e->getError()->code . '<br>
				Param is:' . $e->getError()->param . '<br>
				Message is:' . $e->getError()->message . '<br>';
			} catch (\Stripe\Exception\InvalidRequestException $e) {
				$arTests['cur_search errors'][$k] = 'InvalidRequestException'. '<br>
				Status is:' . $e->getHttpStatus() . '<br>
				Type is:' . $e->getError()->type . '<br>
				Code is:' . $e->getError()->code . '<br>
				Param is:' . $e->getError()->param . '<br>
				Message is:' . $e->getError()->message . '<br>';
			} catch (\Stripe\Exception\AuthenticationException $e) {
			} catch (\Stripe\Exception\ApiConnectionException $e) {
				$arTests['cur_search errors'][$k] = 'ApiConnectionException'. '<br>
				Status is:' . $e->getHttpStatus() . '<br>
				Type is:' . $e->getError()->type . '<br>
				Code is:' . $e->getError()->code . '<br>
				Param is:' . $e->getError()->param . '<br>
				Message is:' . $e->getError()->message . '<br>';
			} catch (\Stripe\Exception\ApiErrorException $e) {
				$arTests['cur_search errors'][$k] = 'ApiErrorException'. '<br>
				Status is:' . $e->getHttpStatus() . '<br>
				Type is:' . $e->getError()->type . '<br>
				Code is:' . $e->getError()->code . '<br>
				Param is:' . $e->getError()->param . '<br>
				Message is:' . $e->getError()->message . '<br>';
			}
			if($create_price_fee['id']){
				$prices_for_link[count($new_products_list)]['price'] = $create_price_fee['id'];
				$prices_for_link[count($new_products_list)]['quantity'] = 1;
			}
			$arTests['new_products_list'] = $new_products_list;
			$arTests['prices_for_link'] = $prices_for_link;

			$create_link = [];
			sleep(2);
			if($prices_for_link && count($prices_for_link)>0){
				try {
					$create_link = $stripe->paymentLinks->create([
						'line_items' => $prices_for_link,
						'metadata' => ["invoice_id" => $invoice_id],
						//'application_fee_percent' => 3,
						//'transfer_data' => ['destination' => 'acct_1Bpj5sA9eEkk1Wdq']
					]);
				} catch (\Stripe\Exception\RateLimitException $e) {
					$arTests['create_link errors'] = 'RateLimitException'. '<br>
					Status is:' . $e->getHttpStatus() . '<br>
					Type is:' . $e->getError()->type . '<br>
					Code is:' . $e->getError()->code . '<br>
					Param is:' . $e->getError()->param . '<br>
					Message is:' . $e->getError()->message . '<br>';
				} catch (\Stripe\Exception\InvalidRequestException $e) {
					$arTests['create_link errors'] = 'InvalidRequestException'. '<br>
					Status is:' . $e->getHttpStatus() . '<br>
					Type is:' . $e->getError()->type . '<br>
					Code is:' . $e->getError()->code . '<br>
					Param is:' . $e->getError()->param . '<br>
					Message is:' . $e->getError()->message . '<br>';
				} catch (\Stripe\Exception\AuthenticationException $e) {
				} catch (\Stripe\Exception\ApiConnectionException $e) {
					$arTests['create_link errors'] = 'ApiConnectionException'. '<br>
					Status is:' . $e->getHttpStatus() . '<br>
					Type is:' . $e->getError()->type . '<br>
					Code is:' . $e->getError()->code . '<br>
					Param is:' . $e->getError()->param . '<br>
					Message is:' . $e->getError()->message . '<br>';
				} catch (\Stripe\Exception\ApiErrorException $e) {
					$arTests['create_link errors'] = 'ApiErrorException'. '<br>
					Status is:' . $e->getHttpStatus() . '<br>
					Type is:' . $e->getError()->type . '<br>
					Code is:' . $e->getError()->code . '<br>
					Param is:' . $e->getError()->param . '<br>
					Message is:' . $e->getError()->message . '<br>';
				}
				$arTests['create_link'] = $create_link;
			}
			//$stripe_link = 'Also, you can pay for this invoice online: <a href="'.$create_link['url'].'">'.$create_link['url'].'</a>';
			$stripe_link = 'Also, you can pay for this invoice online: ${StripeLink}';
		/////// STRIPE ///////
		sleep(2);
		$document_fields = [
			'entityId' => $invoice_id,
			"entityTypeId" => '31',
			'templateId' => '10',
			'providerClassName' => '\\Bitrix\\DocumentGenerator\\DataProvider\\Rest',
			'value' => 1,
			'values' => [
				'Table' => $products,
				'TableItemN' => 'Table.Item.N',
				'TableItemP' => 'Table.Item.P',
				'TableItemPrice' => 'Table.Item.Price',
				'TableItemQ' => 'Table.Item.Q',
				'TableItemPriceS' => 'Table.Item.PriceS',
				'TableItemI' => 'Table.Item.I',
				'StripeLink' => $stripe_link,
				'TotalSum' => $total_sum,
				'TotalSumPlus2P' => $total_sum_2p,
				'TotalSumPlus3P' => $total_sum_3p,
				'TotalSumPlus4P' => $total_sum_4p,
				'TotalSumPlus6P' => $total_sum_6p,
			],
			'fields' => [
				'Table' => [
					'PROVIDER' => 'Bitrix\\DocumentGenerator\\DataProvider\\ArrayDataProvider',
					'OPTIONS' => [
						'ITEM_NAME' => 'Item',
						'ITEM_PROVIDER' => 'Bitrix\\DocumentGenerator\\DataProvider\\HashDataProvider',
					],
				],
				//'StripeLink' => ['TYPE' => 'TEXT']
			],
		];
		$arTests['document_fields'] = $document_fields;
		$arNewDocument_data = CRest::call("crm.documentgenerator.document.add", $document_fields);
		$arTests['arNewDocument_data'] = $arNewDocument_data;
		
		if($create_link['url']){
			sleep(2);
			
			$arInvoiceUpdate_data = CRest::call("crm.item.update", array(
				"entityTypeId" => 31,
				"id" => $invoice_id,
				"fields" => ["ufCrmSmartInvoice1659456663414" => $create_link['url']]
			));
			$arTests['arInvoiceUpdate_data'] = $arInvoiceUpdate_data;


			$template_path = 'upload_invoice/invoice_'.$accountNumber.'_raw.docx';

			$fh = fopen($template_path, 'w');
			$options = array(
				CURLOPT_FILE    => $fh,
				CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
				CURLOPT_URL     => $arNewDocument_data['result']['document']['downloadUrlMachine'],
			);

			$ch = curl_init();
			curl_setopt_array($ch, $options);
			curl_exec($ch);
			curl_close($ch);
			fclose($fh);

			$link_href = $create_link['url'];
			$link_name = $create_link['url'];
			$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template_path);

			$link = new \PhpOffice\PhpWord\Element\Link($link_href, $link_name, array('underline' => 'single', 'color' => '0000FF', 'size' => '10'));
			$templateProcessor->setHyperLink('StripeLink', $link);

			$edited_invoice_name = 'invoice_'.$accountNumber.'.docx';
			$edited_invoice_path = 'upload_invoice/invoice_'.$accountNumber.'.docx';
			$templateProcessor->saveAs($edited_invoice_path);

			$arMessage = 'Export to Word has been finished.';
			$msg_data = CRest::call("crm.timeline.comment.add", array(
				"fields" => array(
					"COMMENT" => $arMessage,
					"ENTITY_TYPE" => "dynamic_31",
					"ENTITY_ID"  => $invoice_id,
					"FILES" => [
						[$edited_invoice_name, base64_encode(file_get_contents($edited_invoice_path))]
					],
				)
			));
			$arTests['crm.livefeedmessage.add'] = $msg_data;
			$delete_old_document = CRest::call(
				'crm.documentgenerator.document.delete',
				[
					"id" => $arNewDocument_data['result']['document']['id'],
				]
			);
			$arTests['delete_old_document'] = $delete_old_document;
		}
		
	}
}
print_r($arTests);
*/

/*
$template_path = '(TEST) AP Stripe Template (TEST) 20.docx';
$link_href = 'https://stripe.com/';
$link_name = 'PAY HERE';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template_path);

$link = new \PhpOffice\PhpWord\Element\Link($link_href, $link_name, array('underline' => 'single', 'color' => '0000FF'));
$templateProcessor->setHyperLink('StripeLink', $link);
$templateProcessor->saveAs('result.docx');
*/
/*
$resGoodsList = CRest::call(
	'crm.documentgenerator.document.delete',
	[
		"id" => 50,
	]
);
*/
/*
$company_id = '13454';
$address = CRest::call("crm.address.list", array(
	"order" => [],
	"filter" => [
		"ENTITY_TYPE_ID" => 4,
		"ENTITY_ID" => $company_id
	],
	'select' => ["ADDRESS_1", "ADDRESS_2", "CITY", "POSTAL_CODE", "REGION", "PROVINCE", "COUNTRY", "COUNTRY_CODE"]
));

print_r($address);
*/
/*
$deal_id = 6694;

$products = CRest::call("crm.item.productrow.list", array(
	"order" => [],
	"filter" => [
		"=ownerType" => "D",
		"=ownerId" => $deal_id
	],
	"start" => "-1",
));
if($products['result'] && $products['result']['productRows']){
	$products_list = $products['result']['productRows'];
	$quote_products = [];

	$commands = [];
	$get_products_batch = [];
	$arProducts = [];

	$commands_per_page = 50;
	foreach($products_list as &$product){
		$commands[$product['productId']] = 'catalog.product.get?'.http_build_query(["id" => $product['productId']]);
	}
	if(count($commands) > $commands_per_page){
		$cpp = 0;
		$temp_commands = [];
		$temp_res = [];

		foreach($commands as $k => $command){
			++$cpp;
			$temp_commands[$k] = $command;
			if($cpp == $commands_per_page){
				$temp_res = CRest::call('batch', [
					'halt' => 0,
					'cmd' => $temp_commands
				])['result']['result'];

				$get_products_batch = array_merge($get_products_batch, $temp_res);
				$cpp = 0;
				$temp_commands = [];
			}
		}
	}else{
		$get_products_batch = CRest::call('batch', [
			'halt' => 0,
			'cmd' => $commands
		])['result']['result'];
	}
	foreach($get_products_batch as $temp_product){
		$arProducts[$temp_product['product']['id']] = $temp_product['product'];
	}
	print_r($commands);
	print_r($arProducts);
	print_r($products_list);
	
}
*/
var_export($data);
echo '<br>';
echo '<br>';
echo '</pre>';
/******************************************************************/
require_once("include/footer.php");
?>