<?php

function apiDataRead()
{
	$api_file_read = fopen("./api.json", "r") or die("Unable to Open zoho api file");
	$api_data = fread($api_file_read, filesize("./api.json"));
	fclose($api_file_read);
	return $api_data;
}

function access_tokenGenerate()
{
	$api_data = apiDataRead();

	$api_data_array = json_decode($api_data, true);
	$client_id = $api_data_array['client_id'];
	$client_secret = $api_data_array['client_secret'];
	$access_token = $api_data_array['access_token'];
	$refresh_token = $api_data_array['refresh_token'];
	$access_token_time_stamp = $api_data_array['time_stamp'];
	$time_now = time();

	if ($time_now - (strtotime($access_token_time_stamp)) > 3600) {
		$access_token = '';
		//New access Token generate
		$data_input = array("refresh_token" => $refresh_token, "grant_type" => "refresh_token", "client_id" => $client_id, "client_secret" => $client_secret);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, 'https://accounts.zoho.com/oauth/v2/token');
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data_input));
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
		$response_get = curl_exec($ch);
		curl_close($ch);
		//#############################   Updating Access Token to API FILE   ###################################################
		$response_arr = json_decode($response_get, true);
		$response_data = array("refresh_token" => $refresh_token, "access_token" => $response_arr['access_token'], "client_id" => $client_id, "client_secret" => $client_secret, "time_stamp" => date("Y-m-d H:m:s", time()));
		$response_data_json = json_encode($response_data);
		$api_file_update = fopen("./api.json", "w") or die("Unable to Open zoho api file");
		fwrite($api_file_update, $response_data_json);
		fclose($api_file_update);
		//#######################################################################################################################
		$access_token = $response_arr['access_token'];
	}

	return $access_token;
}

function generateOrg_domain($access_token)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_URL, 'https://www.zohoapis.com/crm/v2/org');
	curl_setopt($ch, CURLOPT_HTTPHEADER,  array(
		"Authorization: Zoho-oauthtoken " . $access_token . ""
	));
	$response_org = curl_exec($ch);
	curl_close($ch);

	$response_org_arr = json_decode($response_org, true);

	$org_domain = $response_org_arr['org'][0]['domain_name'];
	return $org_domain;
}

function zoho_lead_search($phone_number, $access_token)
{
	$lead_search_url = "https://www.zohoapis.com/crm/v2/Leads/search?phone=$phone_number";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_URL, $lead_search_url);
	curl_setopt($ch, CURLOPT_HTTPHEADER,  array(
		"Authorization: Zoho-oauthtoken $access_token"
	));
	$response_search = curl_exec($ch);
	curl_close($ch);
	$response_array_lead = json_decode($response_search, true);
	if ($response_array_lead) {
		$response_array_data = $response_array_lead['data'];

		if (!empty($response_array_data)) {
			foreach ($response_array_data as $key => $value) {
				$zoho_LeadData = array('flag' => TRUE, 'id' => $value['id']);
			}
		} else {
			$zoho_LeadData = array('flag' => FALSE, 'id' => '');
		}
	} else {
		$zoho_LeadData = array('flag' => FALSE, 'id' => '');
	}
	return $zoho_LeadData;
}

function zoho_contact_search($phone_number, $access_token)
{
	$contact_search_url = "https://www.zohoapis.com/crm/v2/Contacts/search?phone=$phone_number";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_URL, $contact_search_url);
	curl_setopt($ch, CURLOPT_HTTPHEADER,  array(
		"Authorization: Zoho-oauthtoken $access_token"
	));
	$response_search = curl_exec($ch);
	curl_close($ch);
	$response_array_contact = json_decode($response_search, true);
	if ($response_array_contact) {
		$response_array_data = $response_array_contact['data'];
		if (!empty($response_array_data)) {
			foreach ($response_array_data as $key => $value) {
				$zoho_ContactData = array('flag' => TRUE, 'id' => $value['id']);
			}
		} else {
			$zoho_LeadData = array('flag' => FALSE, 'id' => '');
		}
	} else {
		$zoho_ContactData = array('flag' => FALSE, 'id' => '');
	}
	return $zoho_ContactData;
}

function searchForLeadOrContact($phone_number)
{
	$access_token = access_tokenGenerate();
	//Search For Lead
	$zoho_LeadData = zoho_lead_search($phone_number, $access_token);

	if ($zoho_LeadData['flag']) {
		$zoho_dataLeadOrContact['found'] = TRUE;
		$zoho_dataLeadOrContact['lead'] = $zoho_LeadData['id'];
	} else {
		$zoho_ContactData = zoho_contact_search($phone_number, $access_token);
		if ($zoho_ContactData['flag']) {
			$zoho_dataLeadOrContact['found'] = TRUE;
			$zoho_dataLeadOrContact['contact'] = $zoho_ContactData['id'];
		} else {
			$zoho_dataLeadOrContact['found'] = FALSE;
		}
	}
	return $zoho_dataLeadOrContact;
}

function checking_zohoCallLog_id_fromZoho($checking_zohoCallLog_id, $access_token)
{
	if ($checking_zohoCallLog_id) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_URL, "https://www.zohoapis.com/crm/v2/Calls/" . $checking_zohoCallLog_id);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Authorization: Zoho-oauthtoken $access_token"
		));
		$response = curl_exec($ch);
	} else {
		return array();
	}
}

function CallLog_create_forLead($recording_location, $dispo_choice, $Disposition_Name_dialer, $comments, $whatID, $current_time, $customer_sec, $checkingInboundOrOutbound, $CallBackDatETimE, $CallBackLeadStatus, $checking_zohoCallLog_id)
{
	$access_token = access_tokenGenerate();

	$post_data = [
		"data" => [
			[
				"Call_Duration" => $customer_sec,
				"What_Id" => [
					"id" => $whatID
				],
				"Call_Start_Time" => $current_time,
				"Description" => $comments,
				"Disposition_Code_dialer" => $dispo_choice . "-" . $Disposition_Name_dialer,
				"recording_file_location" => $recording_location,
				"Subject" => "Activity",
				"se_module" => "Leads",
				"Call_Type" => $checkingInboundOrOutbound,
			],
		],
	];

	if (!empty($post_data)) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_URL, "https://www.zohoapis.com/crm/v2/Calls");
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Authorization: Zoho-oauthtoken $access_token"
		));
		$response = curl_exec($ch);
		if ($response) {
			$response_arr = json_decode($response, true);
			if ($response_arr['data'][0]['code'] == 'SUCCESS') {
				if ($dispo_choice == 'CBHOLD') {
					$post_data = [
						"data" => [
							[
								"Call_Duration" => $customer_sec,
								"What_Id" => [
									"id" => $whatID
								],
								"Call_Start_Time" => $CallBackDatETimE,
								"Description" => urldecode($comments),
								"Disposition_Code_dialer" => $CallBackLeadStatus . "-" . $Disposition_Name_dialer,
								"recording_file_location" => $recording_location,
								"Subject" => "Activity",
								"se_module" => "Leads",
								"Call_Type" => $checkingInboundOrOutbound,
								"Callback_Description" => urldecode($comments),
							],
						],
					];

					$ch = curl_init();
					curl_setopt($ch, CURLOPT_POST, 1);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
					curl_setopt($ch, CURLOPT_URL, "https://www.zohoapis.com/crm/v2/Calls");
					curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(
						"Authorization: Zoho-oauthtoken $access_token"
					));
					$response = curl_exec($ch);
					if ($response) {
						$response_arr = json_decode($response, true);
						if ($response_arr['data'][0]['code'] == 'SUCCESS') {
							$callLogID = $response_arr['data'][0]['details']['id'];
							return $callLogID;
						} else {
							return FALSE;
						}
					} else {
						return FALSE;
					}
				} else {
					$callLogID = $response_arr['data'][0]['details']['id'];
					return $callLogID;
				}
			} else {
				return FALSE;
			}
		} else {
			return FALSE;
		}
	}
}

function CallLog_create_forContact($recording_location, $dispo_choice, $Disposition_Name_dialer, $comments, $whoID, $current_time, $customer_sec, $checkingInboundOrOutbound, $CallBackDatETimE, $CallBackLeadStatus)
{
	$access_token = access_tokenGenerate();

	$post_data = [
		"data" => [
			[
				"Call_Duration" => $customer_sec,
				"Who_Id" => [
					"id" => $whoID
				],
				"Call_Start_Time" => $current_time,
				"Description" => urldecode($comments),
				"Disposition_Code_dialer" => $dispo_choice . "-" . $Disposition_Name_dialer,
				"recording_file_location" => $recording_location,
				"Subject" => "Activity",
				"se_module" => "Leads",
				"Call_Type" => $checkingInboundOrOutbound,
			],
		],
	];

	if (!empty($post_data)) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_URL, "https://www.zohoapis.com/crm/v2/Calls");
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Authorization: Zoho-oauthtoken $access_token"
		));
		$response = curl_exec($ch);
		if ($response) {
			$response;
			$response_arr = json_decode($response, true);
			if ($response_arr['data'][0]['code'] == 'SUCCESS') {
				if ($dispo_choice == 'CBHOLD') {
					$post_data = [
						"data" => [
							[
								"Call_Duration" => $customer_sec,
								"Who_Id" => [
									"id" => $whoID
								],
								"Call_Start_Time" => $CallBackDatETimE,
								"Description" => urldecode($comments),
								"Disposition_Code_dialer" => $CallBackLeadStatus . "-" . $Disposition_Name_dialer,
								"recording_file_location" => $recording_location,
								"Subject" => "Activity",
								"se_module" => "Leads",
								"Call_Type" => $checkingInboundOrOutbound,
								"Callback_Description" => urldecode($comments),
							],
						],
					];

					$ch = curl_init();
					curl_setopt($ch, CURLOPT_POST, 1);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
					curl_setopt($ch, CURLOPT_URL, "https://www.zohoapis.com/crm/v2/Calls");
					curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(
						"Authorization: Zoho-oauthtoken $access_token"
					));
					$response = curl_exec($ch);

					if ($response) {
						$response_arr = json_decode($response, true);
						if ($response_arr['data'][0]['code'] == 'SUCCESS') {
							$callLogID = $response_arr['data'][0]['details']['id'];
							return $callLogID;
						}
					} else {
						return FALSE;
					}
				} else {
					$callLogID = $response_arr['data'][0]['details']['id'];
					return $callLogID;
				}
			} else {
				return FALSE;
			}
		} else {
			return FALSE;
		}
	}
}

function updateCallBackToCompleted($id, $callLogID, $module, $current_time)
{
	$access_token = access_tokenGenerate();

	if ($module == 'Leads') {
		$id_type = "What_Id";
	} elseif ($module == 'Contacts') {
		$id_type = "Who_Id";
	}

	$put_data = [
		"data" => [
			[
				$id_type => [
					"id" => $id
				],
				"Call_Start_Time" => $current_time,
				"se_module" => $module,
			],
		],
	];

	if (!empty($put_data)) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_URL, "https://www.zohoapis.com/crm/v2/Calls/" . $callLogID);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($put_data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Authorization: Zoho-oauthtoken $access_token"
		));
		$response = curl_exec($ch);

		if ($response) {
			$response_arr = json_decode($response, true);
			if ($response_arr['data'][0]['code'] == 'SUCCESS') {
				$callLogID = $response_arr['data'][0]['details']['id'];
				return $callLogID;
			} else {
				return FALSE;
			}
		} else {
			return FALSE;
		}
	} else {
		return FALSE;
	}
}
