<?php
require_once __DIR__ . '/helpers.php';
date_default_timezone_set('Asia/Kolkata');
header('Content-Type: application/json');

$spamDomain = file_get_contents('../assets/spam_domain.json');
$spamDomainData = json_decode($spamDomain, true);

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
	
	$responseData = googleCaptcha($_POST["g-recaptcha-response"]);

	$ip_address = $_SERVER['REMOTE_ADDR'];

	$full_name = trim($_POST['full_name']);
	$email = trim($_POST['email']);
	$phone = trim($_POST['mobile']);
	$avocado_oil = trim($_POST['avocado_oil']);
	$description = trim($_POST['message']);

	// ✅ First Name
	if (isset($full_name) && empty($full_name)) {
		$response = ['success' => false, 'msg' => "Enter your full name", 'errorType' => "firstNameErr"];
		echo json_encode($response);
		exit;
	}
	if (strlen($full_name) > 100) {
		$response = ['success' => false, 'msg' => "Full name allowed maximum 100 characters", 'errorType' => "firstNameErr"];
		echo json_encode($response);
		exit;
	}
	if (!preg_match('/^[A-Za-z\s]+$/', $full_name)) {
		$response = ['success' => false, 'msg' => "Only alphabetic characters are allowed", 'errorType' => "firstNameErr"];
		echo json_encode($response);
		exit;
	}
	if (preg_match('/<[^>]*>/', $full_name)) {
		$response = ['success' => false, 'msg' => "HTML tags are not allowed", 'errorType' => "firstNameErr"];
		echo json_encode($response);
		exit;
	}

	// ✅ Email
	if (isset($email) && empty($email)) {
		$response = ['success' => false, 'msg' => "Enter your email address", 'errorType' => "emailErr"];
		echo json_encode($response);
		exit;
	}
	if (!preg_match("/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-]{2,})\.([a-zA-Z]{2,5})$/", $email)) {
		$response = ['success' => false, 'msg' => "Enter a valid email address", 'errorType' => "emailErr"];
		echo json_encode($response);
		exit;
	}
	$checkemail = explode('@', $email);
	$emailhost = $checkemail[1];
	if (in_array($emailhost, $spamDomainData)) {
		$response = ['success' => false, 'msg' => "Invalid Domain", 'errorType' => "emailErr"];
		echo json_encode($response);
		exit;
	}


	if (isset($avocado_oil) && empty($avocado_oil)) {
		$response = ['success' => false, 'msg' => "Select your product", 'errorType' => "phoneErr"];
		echo json_encode($response);
		exit;
	}

	// ✅ Phone
	if (isset($phone) && empty($phone)) {
		$response = ['success' => false, 'msg' => "Enter your mobile number", 'errorType' => "phoneErr"];
		echo json_encode($response);
		exit;
	}
	if (!is_numeric($phone)) {
		$response = ['success' => false, 'msg' => "Enter only numeric values", 'errorType' => "phoneErr"];
		echo json_encode($response);
		exit;
	}
	if (strlen($phone) != 10) {
		$response = ['success' => false, 'msg' => "Mobile number must be 10 digits", 'errorType' => "phoneErr"];
		echo json_encode($response);
		exit;
	}

	// ✅ Description
	if (strlen($description) > 600) {
		$response = ['success' => false, 'msg' => "Message allowed maximum 600 characters", 'errorType' => "descErr"];
		echo json_encode($response);
		exit;
	}
	if (preg_match('/<[^>]*>/', $description)) {
		$response = ['success' => false, 'msg' => "HTML tags are not allowed", 'errorType' => "descErr"];
		echo json_encode($response);
		exit;
	}

	if($responseData['success']) {

		// Send Email to Admin AND Store Data

		$data = array(
			'From' => 'Enquiry Form',
			'Full Name' => $full_name,
			'Email' => $email,
			'Phone' => $phone,
			'Product' => $avocado_oil,
			'Message' => $description,
		);

		// $params = http_build_query($data);

		// $curl = curl_init();

		// curl_setopt_array($curl, array(
		// 	CURLOPT_URL => "https://script.google.com/macros/s/AKfycbwYsa579PFUQV9LEncAP_8yw79q9EMmxw-0grBvU5OlXHh0Jb_qdj-E-8qub5taQoeQ/exec?" . $params,
		// 	CURLOPT_RETURNTRANSFER => true,
		// 	CURLOPT_ENCODING => "",
		// 	CURLOPT_MAXREDIRS => 10,
		// 	CURLOPT_TIMEOUT => 30,
		// 	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		// 	CURLOPT_CUSTOMREQUEST => "GET",
		// 	CURLOPT_HTTPHEADER => array(
		// 		"cache-control: no-cache"
		// 	),
		// ));

		// $response = curl_exec($curl);
		// $error = curl_error($curl);
		// curl_close($curl);

		$enquiryDate = date('d-m-Y h:i A');

		$subjectOFP = $full_name  . " submitted an enquiry on " . $enquiryDate . " via Greenava Foods";

		$messageToP = '
		<div style="width:90%; margin:auto; font-family:Arial, sans-serif; color:#333; line-height:1.6;">

			<div style="margin-bottom:20px;">
				<img style="width:160px;" src="../assets/images/home/header-logo.png" alt="Greenava Foods Logo" />
			</div>

			<p style="font-size:16px;">Hello Admin,</p>
			<p style="font-size:15px;">You have received a new <strong>enquiry</strong> from <strong>' . $full_name . '</strong>. Below are the submitted details:</p>

			<table border="1" cellpadding="8" cellspacing="0" style="border-collapse:collapse; font-size:14px; width:100%;">
				<tr><td><strong>Name</strong></td><td>' . $full_name  . '</td></tr>
				<tr><td><strong>Email</strong></td><td>' . $email . '</td></tr>
				<tr><td><strong>Mobile</strong></td><td>' . $phone . '</td></tr>
				<tr><td><strong>Product</strong></td><td>' . $avocado_oil . '</td></tr>
				<tr><td><strong>Message / Enquiry</strong></td><td>' . $description . '</td></tr>
				<tr><td><strong>Submitted On</strong></td><td>' . $enquiryDate . '</td></tr>
			</table>

			<br/>
			<p style="font-size:15px;">Please reach out to the customer at your earliest convenience.</p>

			<p style="margin-top:30px; font-size:14px; color:#555;">
				Regards,<br/>
				<strong>Team Greenava Foods</strong><br/>
			</p>
		</div>';

		// $toadmin[] = "rs@greenavainternational.com";
		// $toadmin[] = "esther.wangari@greenavafoods.ke";
		// $toadmin[] = "avocado@greenavafoods.ke";

		if($avocado_oil == "Avocado_Oil") {
			$toadmin[] = "shubham.rajyaguru@bcreative.in";
		}
		else {
			$toadmin[] = "chandrakant.dabhi@bcreative.in";
		}

		$mail_sent_top = sMail($toadmin, $subjectOFP, $messageToP);

		// $subjectOFP1 = "Thank you " . $full_name . " for enquiring with Greenava Foods";

		// $messageToP1 = '
		// <div style="width:90%; margin:auto; font-family:Arial, sans-serif; color:#333; line-height:1.6;">

		// 	<div style="margin-bottom:20px;">
		// 		<img style="width:160px;" src="../assets/images/home/header-logo.png" alt="Eterno Logo" />
		// 	</div>

		// 	<p style="font-size:16px;">Dear ' . $full_name . ',</p>

		// 	<p style="font-size:15px;">
		// 		Thank you for reaching out to <strong>Greenava Foods</strong>. We have received your enquiry and our team will get in touch with you shortly to provide the information you requested.
		// 	</p>

		// 	<p style="margin-top:25px; font-size:14px; color:#555;">
		// 		Best Regards,<br/>
		// 		<strong>Team Greenava Foods</strong><br/>
		// 	</p>
		// </div>';

		// $touser[] = $email;
		// sMail($touser, $subjectOFP1, $messageToP1);

		$response = [];
		if($mail_sent_top == "sent")
		{
			$response['success']    =   true;
			$response['msg']        =   "Success";
		}else{
			$response['success']    =   false;
			$response['msg']        =   "Error";
		}

	}else{
		$response['success']    =   false;
		$response['msg']        =   "Invalid captcha!";
		$response['errorType']  =   "recaptchaErr";
	}

	echo json_encode($response);
	exit;

}
else
{
	$response['success']    =   false;
	$response['msg']        =   "please click on recaptcha.!";
	$response['errorType']  =   "recaptchaErr";
	echo json_encode($response);
	exit;
}



// function googleCaptche($postData)
// {
// 	$response = $postData;
// 	$remote_ip = $_SERVER["REMOTE_ADDR"];
// 	$secret_key = '6LdpWzYqAAAAABSTtWui8GS56z3dzfqvr2jhLSi-';
// 	$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret_key."&response=".$response."&remoteip=".$remote_ip;
// 	$curl = curl_init();
// 	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
// 	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// 	curl_setopt($curl, CURLOPT_URL, $url);
// 	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 	$output = curl_exec($curl);
// 	curl_close($curl);
// 	$result = json_decode($output, true);
// 	return $result;
// }	

// function sMail($to = array(), $subject, $messageBody) {
//     $headers  = "MIME-Version: 1.0" . "\r\n";
//     $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

//     // Sender info
//     $headers .= "From: Pitch Perfect Presentation <pitchperfectsocial@gmail.com>" . "\r\n";
//     $headers .= "Reply-To: pitchperfectsocial@gmail.com" . "\r\n";

//     // Additional headers if needed
//     // $headers .= "Cc: someone@yourdomain.com" . "\r\n";
//     // $headers .= "Bcc: another@yourdomain.com" . "\r\n";
// 	$to =   implode(',',$to);
//     //$to =  'shahrukh@bcreative.in';
//     if(mail($to, $subject, $messageBody, $headers)){
// 		return "sent";
// 	}
    
// 	return 'failed';
    
// }

?>