<?php
    /* -- version 3.1.6 - october 2021 --*/
	require_once "./shared/classes.php";
	if (checkSource()==false) {return;}

	/* -- Get POST variables --*/
	if (isset($_POST['email'])) { $email=trim(htmlspecialchars($_POST['email'])); } else {$email='';}
	if (isset($_POST['password'])) { $password=trim(htmlspecialchars($_POST['password'])); } else {$password='';}
	if (strlen(trim($email))==0) {$email=null;}
	if (strlen(trim($password))==0) {$password=null;}
	
	/*-- Get Settings --*/
	$delay=0;
	if (isset($GLOBALS['settings']['delay'])) {
		$delay=$GLOBALS['settings']['delay'];
	}

	/*-- Sql Connection --*/
	$dbCo = phpPdoConnect();
	if ($dbCo===false) {return; } //Error message is handled in function

	/* -- Result Object declaration --*/
	$obj = new stdClass();

	sleep($delay); //Prevent Saturation by waiting n seconds
	$id = 0;
	$enabled=false;
	$storedPIN="";
	$sql = "select * from _auth where auth_email=:email";
	try {
		$stmt = $dbCo->prepare($sql);
		$stmt->bindParam(':email', $email);
		$stmt->execute();
		if ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
			if (!(password_verify($password, $row->auth_password))) {
				returnError(-1007, "Invalid Credential");
				return;
			}
			if (($adminonly==true) && ($row->auth_admin!=1)) {
				returnError(-1022, "You don't have Administrator privileges");
				return;
			}
			$storedPIN=$row->auth_pin;
		} else {
			returnError(-1012, "Invalid Token or Credential");
			return;
		}
	} catch (PDOException $e) {
		returnError(-1011, $e->getMessage());
		return;
	}

	$appname=$GLOBALS['settings']['appname'];
	$emailContents="<h1>".$storedPIN."</h1>";
	if (sendmail($email,"PIN CODE [".$appname."]",$emailContents)==true) {
		$obj->code=1;
		$obj->message="PIN Sent by email to ".$email;
		echo safe_json_encode($obj);
		return;
	} else {
		returnError(-1099, "Unable to send mail to ".$email);
		return;
	}
?>

