<?php
defined('PRODUCT_NAME') or die;
class RegistrationModule 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()
	{
		$title                 = $this->setting("title");
		$title_heading_level   = $this->setting("title_heading_level");
		$module_class          = $this->setting("module_class");
		$redirect              = $this->setting("redirect");
		$recaptcha_public_key  = $this->setting("recaptcha_public_key");
		$recaptcha_private_key = $this->setting("recaptcha_private_key");
		$submitted             = ($this->input->post("email") != "");
		$site                  = Mainframe::site();
		$sendit                = false;
		$challenge             = "";
		$message               = "";
		$user                  = new User();

		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);
					$message = "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.";
				}
			}
			else if($recaptcha_public_key && $recaptcha_private_key)
			{
				$sendit = verify_recaptcha_v2($this->input->post("g-recaptcha-response"), $recaptcha_private_key);
			}
			else
			{
				// No captcha.
				$sendit = true;
			}
		}

		if($sendit)
		{
			$this->load->model("acl_user_role");

			if($this->input->post("password") != $this->input->post("password2"))
			{
				$message = "Passwords don't match!";
			}
			else if($user->LoadByUsername($this->input->post("email")) ||
			        $user->LoadByEmail($this->input->post("email")))
			{
				$message = "E-mail address already exists!";
			}

			//no message set yet - this means no errors
			if(!$message)
			{
				$this->load->helper("password");

				$site = Mainframe::site();

				$user = new User();
				$user->ReadPostVars();
				$user->username 		= $this->input->post("email");
				$user->joined 			= date("Y-m-d H:i:s");
				$user->joined_site_id 	= $site->site_id;
				$user->last_login 		= date("Y-m-d H:i:s");
				$user->password 		= password_hash($this->input->post("password"), PASSWORD_BCRYPT);
				$user->active 			= 1;
				$user->save();

				$this->acl_user_role->add_link($user->user_id, 2); // Registered Users

				if($user->user_id)
				{
					// Reload for ACL reasons.
					$user->load($user->user_id);

					$message = '<p>An account was created for you on ' . $site->name . '. Your username and password are below.</p>';
					$message .= '<table><tr><td>Website:</td><td>' . $site->name . '</td></tr>';
					$message .= '<tr><td>Username:</td><td>' . $user->username . '</td></tr>';
					$message .= '<tr><td>Password:</td><td>' . $this->input->post("password") . '</td></tr></table>';

					send_notification(array($user), "Account Details For " . $site->name, $message);

					$this->load->library("encryption");

					if($user->has(ACTION_LOGIN))
					{
						//auto login the new user
						setcookie("user_id", $this->encryption->encrypt($user->user_id), time() + $this->config->item("sess_expiration"), $this->config->item("cookie_path"), $this->config->item("cookie_domain"), $this->config->item("cookie_secure"), $this->config->item("cookie_httponly"));
					}

					FeralRedirect(($this->input->post("redirect") ? html_escape(urldecode($this->input->post("redirect"))) : ($redirect ? $redirect : "index.php")));
				}
				else
				{
					$message = "An error occurred while joining the site.";
				}
			}
		}
		else if($submitted && !$sendit)
		{
			if(!$site->recaptcha && $recaptcha_public_key && $recaptcha_private_key)
			{
				$message = "Invalid Captcha Response";
			}
		}
		?>
		<div id="module_<?php echo($this->module_instance_id); ?>" class="module registration-module <?php echo($module_class); ?>">
			<?php
			if($title && $title_heading_level)
			{
				?><<?php echo($title_heading_level); ?> class="module-title"><?php echo($title); ?></<?php echo($title_heading_level); ?>><?php
			}
			?>
			<form name="registration_<?php echo $this->module_instance_id?>" id="registration_<?php echo $this->module_instance_id?>" method="post" action="">
				<?php
				csrf();
				FeralHidden("redirect", ($this->input->post("redirect") ? html_escape(urldecode($this->input->post("redirect"))) : ($redirect ? $redirect : "index.php")));
				FeralHidden("joined_site_id", Mainframe::site()->site_id);
				FeralHidden("shopper_group_id", "1");
				?>
				<div class="row">
					<?php
					if($message)
					{
						?>
						<div class="col-12"><p class="alert alert-danger"><?php echo $message?></p></div>
						<?php
					}
					?>
					<div class="<?php echo(TWO_COL); ?>">
						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="fname">First Name: <sup class="required">*</sup></label></div>

							<div class="<?php echo(FIELD_COL); ?>">
								<?php
								$wgt = new FeralTextWidget("fname", html_escape($this->input->post("fname")));
								$wgt->SetAttribute("required", "required");
								$wgt->Create();
								?>
							</div>
						</div>
					</div>

					<div class="<?php echo(TWO_COL); ?>">
						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="lname">Last Name: <sup class="required">*</sup></label></div>

							<div class="<?php echo(FIELD_COL); ?>">
								<?php
								$wgt = new FeralTextWidget("lname", html_escape($this->input->post("lname")));
								$wgt->SetAttribute("required", "required");
								$wgt->Create();
								?>
							</div>
						</div>
					</div>

					<div class="<?php echo(TWO_COL); ?>">
						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="company">Company:</label></div>

							<div class="<?php echo(FIELD_COL); ?>">
								<?php
								$wgt = new FeralTextWidget("company", html_escape($this->input->post("company")));
								$wgt->Create();
								?>
							</div>
						</div>
					</div>

					<div class="<?php echo(TWO_COL); ?>">
						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="email">E-mail Address: <sup class="required">*</sup></label></div>

							<div class="<?php echo(FIELD_COL); ?>">
								<?php
								$wgt = new FeralTextWidget("email", html_escape($this->input->post("email")));
								$wgt->SetAttribute("required", "required");
								$wgt->Create();
								?>
							</div>
						</div>
					</div>

					<div class="<?php echo(TWO_COL); ?>">
						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="password">Password: <sup class="required">*</sup></label></div>

							<div class="<?php echo(FIELD_COL); ?>">
								<?php
								$wgt = new FeralPasswordWidget("password", html_escape($this->input->post("password")));
								$wgt->SetAttribute("required", "required");
								$wgt->SetAttribute("autocomplete", "off");
								$wgt->Create();
								?>
							</div>
						</div>
					</div>

					<div class="<?php echo(TWO_COL); ?>">
						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="password2">Retype Password: <sup class="required">*</sup></label></div>

							<div class="<?php echo(FIELD_COL); ?>">
								<?php
								$wgt = new FeralPasswordWidget("password2", html_escape($this->input->post("password2")));
								$wgt->SetAttribute("required", "required");
								$wgt->SetAttribute("autocomplete", "off");
								$wgt->Create();
								?>
							</div>
						</div>
					</div>

					<?php
					if(!Mainframe::site()->recaptcha && $recaptcha_public_key && $recaptcha_private_key)
					{
						?>
						<div class="col-12 text-center">
							<div class="g-recaptcha" style="display: inline-block;" data-sitekey="<?php echo($recaptcha_public_key); ?>"></div>
						</div>
						<?php
					}
					?>
					<div class="col-12 text-center"><button type="submit" class="btn btn-primary" id="send_<?php echo($this->module_instance_id); ?>">Register</button></div>

					<?php
					if(Mainframe::site()->recaptcha)
					{
						?>
						<input type="hidden" name="token_<?php echo($this->module_instance_id); ?>" id="token_<?php echo($this->module_instance_id); ?>" value="" />
						<input type="hidden" name="verification_<?php echo($this->module_instance_id); ?>" id="verification_<?php echo($this->module_instance_id); ?>" value="" />

						<script>
							<?php // Change the submit button to a regular button and attach our custom handler to it. ?>
							var send_<?php echo($this->module_instance_id); ?> = document.getElementById("send_<?php echo($this->module_instance_id); ?>")
							send_<?php echo($this->module_instance_id); ?>.type = "button";
							send_<?php echo($this->module_instance_id); ?>.onclick = function()
							{
								<?php // Get a bot token from Google. ?>
								botToken("contact_<?php echo($this->module_instance_id); ?>", function(token)
								{
									<?php
									/**
									 * Now that we have a token:
									 * - Remove the custom click handler.
									 * - Change the submit button back to a submit button.
									 * - Click the submit button to submit the form normally.
									 */
									?>
									document.getElementById("token_<?php echo($this->module_instance_id); ?>").value = token;
									send_<?php echo($this->module_instance_id); ?>.type = "submit";
									send_<?php echo($this->module_instance_id); ?>.onclick = null;
									send_<?php echo($this->module_instance_id); ?>.click();
								});
							}

							function verify_<?php echo($this->module_instance_id); ?>(e)
							{
								e.preventDefault();
								document.getElementById("verification_<?php echo($this->module_instance_id); ?>").value = "<?php echo($challenge); ?>";
								send_<?php echo($this->module_instance_id); ?>.click();
							}
						</script>
						<?php
					}
					?>
				</div>
			</form>
		</div>
		<?php
	}
}
