<?php
/**
 * class password_form
 *
 * Description for class password_form
 *
 * @author:
*/
namespace area\presenter\form;

use core\form;
use core\password;
use core\user;

class password_form extends form {
	public $currentPassword = "";
	public $password = "";
	public $rePassword = "";

	public function init() {
		$this->addElement("currentPassword", array("required"));
		$this->addElement("password", array("required"));
		$this->addElement("rePassword", array("required"));
	}

	public function valid() {
		global $__database;

		if(!$this->send) {
			return false;
		}

		$valid = true;
		$userId = user::identifier();

		$this->currentPassword = $this->getElement("currentPassword")->getValue();
		if(empty($this->currentPassword)) {
			$this->elements["currentPassword"]->setError("Pole wymagane");
			$valid = false;
		} else {
			$query = $__database->prepare("SELECT `password` FROM `users` WHERE `user_id`=:user_id");
			$query->bindParam(":user_id", $userId);
			$query->execute();
			if($record = $query->fetch()) {
				if(!password::verify($this->currentPassword, $record["password"])) {
					$this->elements["currentPassword"]->setError("Obecne hasło jest błędne");
					$valid = false;
				}
			} else {
				$this->elements["currentPassword"]->setError("Brak użytkownika");
				$valid = false;
			}
		}

		$this->password = $this->getElement("password")->getValue();
		if(empty($this->password)) {
			$this->elements["password"]->setError("Pole wymagane");
			$valid = false;
		} elseif($this->currentPassword == $this->password) {
			$this->elements["password"]->setError("Nowe hasło musi być różne od obecnego");
			$valid = false;
		} elseif(strlen($this->password) < 6) {
			$this->elements["password"]->setError("Minimalna długość hasła to 6 znaków");
			$valid = false;
		}

		$this->rePassword = $this->getElement("rePassword")->getValue();
		if(empty($this->rePassword)) {
			$this->elements["rePassword"]->setError("Pole wymagane");
			$valid = false;
		} elseif($this->rePassword != $this->password) {
			$this->elements["rePassword"]->setError("Powtórz poprawnie nowe hasło");
			$valid = false;
		}
		
		return $valid;
	}

	public function save() {
		return user::updatePassword($this->password);
	}
}
?>