<?php
defined('PRODUCT_NAME') or die;
class ContactForm extends ModuleInstance
{
	public function __construct()
	{
		parent::__construct();

		if(!Mainframe::site()->recaptcha)
		{
			$this->scripts = array("<script async src='https://www.google.com/recaptcha/api.js'></script>");
		}
		$this->cache_config->enabled = false;
	}

	function render()
	{
		$message = "";
		$sent = false;

		$title               = $this->setting("title");
		$title_heading_level = $this->setting("title_heading_level");
		$module_class        = $this->setting("module_class");
		$recipients          = ($this->setting("recipients") != "" ? explode(";", $this->setting("recipients")) : "");
		$publickey           = $this->setting("recaptcha_public_key");
		$privatekey          = $this->setting("recaptcha_private_key");
		$departments         = ($this->setting("departments") != "" ? explode(";", $this->setting("departments")) : "");
		$addresses           = ($this->setting("addresses") != "" ? explode(";", $this->setting("addresses")) : "");
		$success_message     = $this->setting("success_message");
		$error_message       = $this->setting("error_message");
		$redirect            = $this->setting("redirect");
		$show_subject        = $this->setting("show_subject");
		$show_phone          = $this->setting("show_phone");
		$show_name           = $this->setting("show_name");
		$show_email          = $this->setting("show_email");
		$show_message        = $this->setting("show_message");
		$default_subject     = $this->setting("default_subject");
		$extra_fields        = array();
		$fields              = $this->setting("extra_fields");
		$site                = Mainframe::site();
		$submitted           = ($this->input->post("sendmail") == "1");
		$sendit              = false;
		$challenge           = "";

		if($fields)
		{
			$lines = explode("\n", $fields);
			foreach($lines as $line)
			{
				$extra_fields[] = explode("|", $line);
			}
		}

		if($submitted)
		{
			csrf_verify();
			$this->load->helper("captcha");
			$this->load->library("encryption");

			if($site->recaptcha)
			{
				if($this->input->post("verification_" . $this->module_instance_id))
				{
					// The challenge was nothing more than an encrypted copy of our module instance ID.
					// If we're able to decrypt the answer and it matches, we're pretty certain that a
					// user performed the verification by clicking the provided link.
					$answer = $this->encryption->decrypt($this->input->post("verification_" . $this->module_instance_id));
					$sendit = ($answer == $this->module_instance_id);
				}
				else
				{
					$data = verify_recaptcha_v3($this->input->post("token_" . $this->module_instance_id), "contact_" . $this->module_instance_id);

					if($data->passed == true)
					{
						$sendit = true;
					}
				}

				// If anything here is invalid, generate a challenge.
				if(!$sendit)
				{
					// The challenge was nothing more than an encrypted copy of our module instance ID.
					$challenge = $this->encryption->encrypt($this->module_instance_id);
					$this->errors[] = "<p>If you're a real person, please <a href='' onclick='verify_" . $this->module_instance_id . "(event);return false;'>click here</a> to submit your request.</p>";
				}
			}
			else if($publickey && $privatekey)
			{
				$sendit = verify_recaptcha_v2($this->input->post("g-recaptcha-response"), $privatekey);
			}
			else
			{
				// No captcha.
				$sendit = true;
			}
		}

		if($sendit)
		{
			//send email
			$mail = get_mailer();
			$mail->SetFrom($site->mail_username, ($this->input->post("name") ? $this->input->post("name") : ($site->mail_from ? $site->mail_from : COMPANY_NAME)));
			$mail->ClearReplyTos();
			$mail->AddReplyTo(($this->input->post("email") ? $this->input->post("email") : ($site->mail_replyto ? $site->mail_replyto : COMPANY_EMAIL)), ($this->input->post("name") ? $this->input->post("name") : ($site->mail_from ? $site->mail_from : COMPANY_NAME)));

			if(count($recipients))
			{
				foreach($recipients as $recipient)
				{
					$recipient = trim($recipient);

					if($recipient)
					{
						$mail->AddAddress("$recipient");
					}
				}
			}

			if($this->input->post("department"))
			{
				$mail->AddAddress($this->input->post("department"));
			}

			$this->load->model("contact_response");
		    $response = new Contact_response();
		    $response->module_instance_id = $this->module_instance_id;

			$mail->Subject = ($this->input->post("subject") ? $this->input->post("subject") : $default_subject);
			$response->subject = ($this->input->post("subject") ? $this->input->post("subject") : $default_subject);

			$mail->Body = "Name: \t\t" . $this->input->post("name") . "\n";
			$response->name = $this->input->post("name");

			if($show_phone)
			{
				$mail->Body .= "Phone: \t\t" . $this->input->post("phone") . "\n";
				$response->phone = $this->input->post("phone");
			}
			$mail->Body .= "E-mail: \t\t" . $this->input->post("email") . "\n";
			$response->email = $this->input->post("email");

			foreach($extra_fields as $field)
			{
				$mail->Body .= $field[0] . ": \t\t" . $this->input->post($field[1]) . "\n";
				$response->extra_fields .= $field[0] . ": " . $this->input->post($field[1]) . "; ";
			}
			$mail->Body .= $this->input->post("message");
			$response->message = $this->input->post("message");

			if($mail->Send())
			{
				$this->messages[] = $success_message;
				$_POST = "";
				$sent = true;

				$response->save();

				if($redirect)
				{
					redirect($redirect);
				}
			}
			else
			{
				$this->errors[] = $error_message;
			}
		}
		else if($submitted && !$sendit)
		{
			if(!$site->recaptcha && $publickey && $privatekey)
			{
				$this->errors[] = "<p>Invalid Captcha Response</p>";
			}
		}

		$data = array("module_instance_id" 	=> $this->module_instance_id,
					  "title" 				=> $title,
					  "title_heading_level" => $title_heading_level,
		              "module_class" 		=> $module_class,
					  "messages" 			=> $this->messages,
		              "errors" 				=> $this->errors,
					  "departments" 		=> $departments,
					  "addresses" 			=> $addresses,
					  "publickey" 			=> $publickey,
					  "privatekey" 			=> $privatekey,
					  "show_name" 			=> $show_name,
					  "show_phone" 			=> $show_phone,
					  "show_email" 			=> $show_email,
					  "show_subject" 		=> $show_subject,
					  "show_message" 		=> $show_message,
					  "default_subject" 	=> $default_subject,
					  "extra_fields" 		=> $extra_fields,
					  "challenge" 			=> $challenge,
					  "sent" 				=> $sent);

		$this->load->view("modules/contact/module", $data);

	    if($sent)
	    {
	        if($redirect != "")
	        {
	            ?>
	            <script>
	                window.location = '<?php echo $redirect?>';
	            </script>
	            <?php
	        }
	    }
	}
}
