<?php

use Vn\Web;

class RecoverPassword extends Vn\Web\JsonRequest {
	const PARAMS = ['recoverUser'];

	function run($db) {
		$user = $db->getRow(
			'SELECT email, active FROM account.user WHERE name = #',
			[$_REQUEST['recoverUser']]
		);

		if (!($user['active'] && $user['email']))
			return TRUE;

		$service = $this->service;
		$token = $service->createToken($_REQUEST['recoverUser'], FALSE, TRUE);
		$url = $service->getUrl() ."#!form=account/conf&token=$token";

		$report = new Vn\Web\Report($db, 'recover-password', ['url' => $url]);
		$report->sendMail($user['email']);

		return \Vn\Lib\Locale::get();
		return TRUE;
	}

	const LOWERS = 'abcdefghijklmnopqrstuvwxyz';
	const UPPERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	const DIGITS = '1234567890';
	const SYMBOLS = '!$%&()=.';

	function genPassword($db) {
		$restrictions = $db->getRow(
			'SELECT length, nUpper, nDigits, nPunct FROM account.userPassword');
		
		$pass = [];
		$newPass = '';
		
		$nAlpha = $restrictions['length'] -(
			$restrictions['nUpper'] +
			$restrictions['nDigits'] +
			$restrictions['nPunct']);

		$this->genRands($pass, self::LOWERS, $nAlpha);
		$this->genRands($pass, self::UPPERS, $restrictions['nUpper']);
		$this->genRands($pass, self::DIGITS, $restrictions['nDigits']);
		$this->genRands($pass, self::SYMBOLS, $restrictions['nPunct']);
		
		for ($i = count($pass) - 1; $i >= 0; $i--) {
			$rand = rand(0, $i);
			$newPass .= $pass[$rand];
			array_splice($pass, $rand, 1);
		}

		return $newPass;
	}
	
	function genRands(&$pass, $chars, $max) {
		$len = strlen($chars) - 1;
	
		for ($i = 0; $i < $max; $i++)
			$pass[] = $chars[rand(0, $len)];
	}
}