<?php
	use PHPMailer\PHPMailer\PHPMailer;
	use PHPMailer\PHPMailer\SMTP;
	use PHPMailer\PHPMailer\Exception;

	require_once __DIR__ . '/phpmailer/src/Exception.php';
	require_once __DIR__ . '/phpmailer/src/PHPMailer.php';
	require_once __DIR__ . '/phpmailer/src/SMTP.php';

	$mail = new PHPMailer(true);
	$mail->SMTPDebug = 0;
	$mail->isSMTP();
	$mail->Host = 'mail.bravonet.ai';
	$mail->SMTPSecure = false;
    $mail->SMTPAutoTLS = false;
	$mail->SMTPAuth = true;
	$mail->Username = "no-reply@bravonet.ai";
	$mail->Password = "S#i344L@gQe4";
	$mail->Port = 25;

	$mail->From = "no-reply@bravonet.ai";
	$mail->FromName = "Bravo Net AI";

	$mail->addAddress("wazeer@bravonet.my", "Hello Bravo Net AI");

	$mail->isHTML(true);

	// message that will be displayed when everything is OK :)
	$okMessage = 'Successfully submitted. Thank you!';

	// If something goes wrong, we will display this message.
	$errorMessage = 'There was an error while submitting the form. Please try again later';

	try {
		$params = json_decode(file_get_contents('php://input'), true);
		if(count($params) != 0) {
			$emailText = "----------------------------- <br> Message Details <br> ----------------------------- <br>";
			
			$fields = array('name' => 'Name', 'email' => 'Email', 'companyName' => 'Company Name', 'remark' => 'Remark');

			foreach ($params as $key => $value) {
				// If the field exists in the $fields array, include it in the email
				if (isset($fields[$key])) {
					$emailText .= "$fields[$key]: $value<br>";
				}
			}
			
			$mail->Subject = "Message from Bravo Net AI Website";
			$mail->Body = $emailText;

			$mail->send();
			$responseArray = array('type' => 'success', 'message' => $okMessage);
		} else {
			$responseArray = array('type' => 'danger', 'message' => 'Your form is empty!');
		}
	} catch (Exception $e) {
		$responseArray = array('type' => 'danger', 'message' =>  $errorMessage);
	}

	if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
		$encoded = json_encode($responseArray);

		header('Content-Type: application/json');

		echo $encoded;
	}
	else {
		echo $responseArray['message'];
	}
?>