import axios from 'axios';

if(process.browser)
{
	FormData.prototype.appendObject = function(obj, namespace) 
	{
		let keyName;
		for (var key in obj) 
		{
			if (obj.hasOwnProperty(key)) 
			{
				keyName = [namespace, '[', key, ']'].join('');
				this.append(keyName, obj[key]);
			}
		}
	};	
}

export const sendLeasingOrder = ({ name, phone, email, company }) => 
{
	return new Promise((resolve, reject) => 
	{
		var formData = new FormData();
		formData.append("form", "FORM_LEASING_REQUESTS");
		formData.append("FORM_FIELD_FIO", name);
		formData.append("FORM_FIELD_PHONE", phone);
		formData.append("FORM_FIELD_EMAIL", email);
		formData.append("FORM_FIELD_COMPANY", company);
		formData.append("FORM_FIELD_PAGE_NAME", document.title);
		formData.append("FORM_FIELD_PAGE_URL", window.location.href);

		axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/forms/`, formData)
		.then((response) => 
		{
			if(response.data.status === "complete")
			{
				resolve();
			}
			else
			{
				reject();
			}
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});		
	});
}