<?
/*
@set_time_limit(0);
@ignore_user_abort(true);
$path_parts = pathinfo($_SERVER['SCRIPT_FILENAME']);
chdir($path_parts['dirname']);
require_once (__DIR__.'/include/crest.php');
require_once(__DIR__."/include/stripe/init.php");
require_once(__DIR__.'/PHPWord/autoload.php');

$_REQUEST['DATE TIME'] = date('d.m.Y H:i:s');

file_put_contents(
	$path_parts['dirname']."/onInvoiceAdd_all.log", 
	print_r($_REQUEST, true), 
	FILE_APPEND
);

if($_REQUEST['event'] == 'ONCRMDYNAMICITEMADD' && $_REQUEST['data']['FIELDS']['ID'] !== '' && $_REQUEST['data']['FIELDS']['ENTITY_TYPE_ID'] == '31'){
	$invoice_id = $_REQUEST['data']['FIELDS']['ID'];

	$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;
	
	$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_live_xoCDPoRNL6OGNR9Q78hfOBb6",
			"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'] && $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'];
			}
		}
		
		if($invoice_data['opportunity'] < 15000){
			// 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 && $invoice_data['opportunity'] < 15000){
			try {
				if($invoice_data['opportunity'] < 15000){
					$create_link = $stripe->paymentLinks->create([
						'line_items' => $prices_for_link,
						'metadata' => ["invoice_id" => $invoice_id],
					]);
				}
			} 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>';
		if($invoice_data['opportunity'] < 15000){
			$stripe_link = 'Also, you can pay for this invoice online: ${StripeLink}';
		}else{
			$stripe_link = '';
		}
		/////// 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;
		}
	}
	
	file_put_contents(
		$path_parts['dirname']."/onInvoiceAdd.log", 
		print_r($arTests, true), 
		FILE_APPEND
	);
}
*/
?>