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

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

file_put_contents(
	$path_parts['dirname']."/onCrmDynamicItemAdd_all.log", 
	print_r($_REQUEST, true), 
	FILE_APPEND
);
if($_REQUEST['event'] == 'ONCRMQUOTEADD' && $_REQUEST['data']['FIELDS']['ID'] !== ''){
	$quote_id = $_REQUEST['data']['FIELDS']['ID'];

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


	$url = "https://app.appliedphysicsinc.com/export_to_excel_app/handler.php?event=ONCRMQUOTEADD&form_submit=true&quote_id=".$quote_id;
	$ch = curl_init($url);
	//curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$content = curl_exec($ch);
	$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	if ($content === false) {
		$error = curl_error($ch);
		$content = '';
	} elseif ($code != 200) {
		$error = 'Status: ' . $code;
		$content = '';
	} else {
		$error = false;
	}
	
	curl_close($ch);
	//print_r($error);
	//echo '<br>';echo '<br>';
	//$arOrders = json_decode($content);
	$arTests['curl_answer'] = $content;
	$arTests['curl_error'] = $error;
	$arFile = explode("*|*|*|*", $content);
	$file_name = $arFile[0];
	$xlsFilePath = $arFile[1];


	$quote = CRest::call("crm.item.get", array(
		"entityTypeId" => 7,
		"id" => $quote_id,
	));
	$quote_data = $quote['result']['item'];
	$deal_id = $quote_data['dealId'];

	$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'];


	$products = CRest::call("crm.item.productrow.list", array(
		"order" => [],
		"filter" => [
			"=ownerType" => "D",
			"=ownerId" => $deal_id
		],
		"start" => "-1",
	));
	$products_list = $products['result']['productRows'];
	sleep(1);
	$contact = CRest::call("crm.contact.get", array(
		"id" => $contact_id
	));
	$contact_data = $contact['result'];
	
	sleep(1);
	$company = CRest::call("crm.company.get", array(
		"id" => $company_id
	));
	$company_data = $company['result'];
	$company_name = $company_data['TITLE'];
	sleep(1);
	if(count($contact_data['PHONE'])>0){
		$contact_phone = $contact_data['PHONE'][0]['VALUE'];
	}
	if(count($contact_data['EMAIL'])>0){
		$contact_email = $contact_data['EMAIL'][0]['VALUE'];
	}
	$contact_full_name = $contact_data['NAME'].' '.$contact_data['LAST_NAME'];
	sleep(1);
	$address = CRest::call("crm.address.list", array(
		"order" => [],
		"filter" => [
			"ENTITY_TYPE_ID" => 3,
			"ENTITY_ID" => $contact_id
		],
		'select' => ["ADDRESS_1", "ADDRESS_2", "CITY", "POSTAL_CODE", "REGION", "PROVINCE", "COUNTRY", "COUNTRY_CODE"]
	));
	$address_data = $address['result'][0];
	if(is_array($address_data)){
		$contact_state = $address_data['PROVINCE'];
		$contact_country = $address_data['COUNTRY'];
	}
	sleep(3);
	$mailTitle = '';
	$mailText = '';
	$dtime = DateTime::createFromFormat("d/m/Y H:i:s", date("d/m/Y H:i:s"));
	$current_call_timestamp = $dtime->getTimestamp();
	$cur_time = date('c', $current_call_timestamp);
	
	$quote_create_date = date('m/d/Y H:i:s', strtotime($deal_data['DATE_CREATE']));
	$email_products_str = '';
	foreach($products_list as $k => &$product){
		$email_products_str .= "<br><a href='https://appliedphysics.bitrix24.com/crm/catalog/24/product/".$product['productId']."/' target='_blank'>".$product['productName']."</a>";
	}

	$arStaff_data = CRest::call("user.get", array(
		"ID" => $deal_data['ASSIGNED_BY_ID']
	));

	$mailTitle = "New Quote ".$quote_data['quoteNumber'];
	$mailText = "Attached is a New Quote For ".$contact_full_name." at ".$company_name." created at ".$quote_create_date."<br />
	<br />
	<br />
	<br />
	Contact Name:  <a href='https://appliedphysics.bitrix24.com/crm/contact/details/".$contact_id."/' target='_blank'>".$contact_full_name."</a> <br />
	Company: <a href='https://appliedphysics.bitrix24.com/crm/company/details/".$company_id."/' target='_blank'>".$company_name."</a> <br />
	Phone Number: ".$contact_phone." <br />
	State: ".$contact_state." <br />
	Country: ".$contact_country." <br />
	Email: ".$contact_email." <br />
	Products: ".$email_products_str ."<br />
	<br />
	<br />
	<br />
	Questions and Comments: ".$deal_data['COMMENTS']."<br />
	<br />
	<br />
	CRM Detail View URL- <a href='https://appliedphysics.bitrix24.com/crm/deal/details/".$deal_id."/' target='_blank'>".$deal_data['TITLE']."</a>
	<br />
	<br />
	<br />
	<br />";

	//	CRM Detail View URL- <a href='https://appliedphysics.bitrix24.com/crm/type/7/details/".$quote_id."/' target='_blank'>".$quote_data['title']."</a>
	
	$staff['ID'] = $arStaff_data['result'][0]['ID'];
	$staff['NAME'] = $arStaff_data['result'][0]['NAME'];
	$staff['LAST_NAME'] = $arStaff_data['result'][0]['LAST_NAME'];
	$staff['EMAIL'] = $arStaff_data['result'][0]['EMAIL'];
	
	$deal_id = '';
	if($quote_data['dealId'] !== '' && $quote_data['dealId'] !== '0' && $quote_data['dealId'] !== 0){
		$deal_id = $quote_data['dealId'];
	}

	$mail_comm_entity_id = '';
	$mail_comm_entity_type_id = '';
	if($deal_id !== '' && $deal_id !== '0' && $deal_id !== 0){
		$mail_comm_entity_id = $deal_id;
		$mail_comm_entity_type_id = 2;
	}elseif($contact_id !== '' && $contact_id !== '0' && $contact_id !== 0){
		$mail_comm_entity_id = $contact_id;
		$mail_comm_entity_type_id = 3;
	}elseif($company_id !== '' && $company_id !== '0' && $company_id !== 0){
		$mail_comm_entity_id = $company_id;
		$mail_comm_entity_type_id = 4;
	}
	if($mail_comm_entity_id !== '' && $mail_comm_entity_type_id !== ''){
		$mail_fields = [
			"OWNER_TYPE_ID" => $mail_comm_entity_type_id,
			"OWNER_ID" => $mail_comm_entity_id,
			"TYPE_ID" => 4,
			"COMMUNICATIONS" => [
				[
					"VALUE" => 'sales@appliedphysicsusa.com',
					"ENTITY_ID" => 6830,
					"ENTITY_TYPE_ID" => 3
				]
			], 
			"SUBJECT" => $mailTitle,
			"START_TIME" => $cur_time,
			"END_TIME" => $cur_time,
			"COMPLETED" => "Y",  
			"RESPONSIBLE_ID" => $staff['ID'],
			"AUTHOR_ID" => $staff['ID'],
			"EDITOR_ID" => $staff['ID'],
			"DESCRIPTION" => $mailText,
			"DESCRIPTION_TYPE" => 3, //из метода crm.enum.contenttype - HTML
			"DIRECTION" => 2,
			'SETTINGS' => [
				'MESSAGE_FROM' => implode(
					' ',
					[$staff['NAME'], $staff['LAST_NAME'], '<' . $staff['EMAIL'] . '>']
				),
				'DISABLE_SENDING_MESSAGE_COPY' => 'Y'
			],
			"WEBDAV_ELEMENTS" => [
				'fileData' => [$file_name, base64_encode(file_get_contents($xlsFilePath))]
			]
		];
		sleep(5);
		$arQuoteMail_data = CRest::call("crm.activity.add", array(
			"fields" => $mail_fields
		));
		$arTests['mail_fields'] = $mail_fields;
		$arTests['arQuoteMail_data'] = $arQuoteMail_data;
		if($arQuoteMail_data['result']){
			$quoteData = CRest::call("crm.item.get", array(
				"entityTypeId" => 7,
				"id" => $quote_id,
			));
			if($quoteData['result']['item']['stageId'] == "DRAFT"){
				$arQuoteUpdate_data = CRest::call("crm.item.update", array(
					"entityTypeId" => 7,
					"id" => $quote_id,
					"fields" => ["stageId" => 'SENT']
				));
				$arTests['arQuoteUpdate_data'] = $arQuoteUpdate_data;
			}
		}
	}

	file_put_contents(
		$path_parts['dirname']."/onCrmDynamicItemAdd.log", 
		print_r($arTests, true), 
		FILE_APPEND
	);
}
*/
?>