<?php
class ControllerAccountForgotten extends Controller {
	var $error = array();

	function index() {
		$config   =& $this->locator->get('config');
		$customer =& $this->locator->get('customer');
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');
		$module   =& $this->locator->get('module');
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$session  =& $this->locator->get('session');
		$template =& $this->locator->get('template');
		$url      =& $this->locator->get('url');
		
		if ($customer->isLogged()) {
			$response->redirect($url->ssl('account'));
		}

		$language->load('controller/account_forgotten.php');

		$template->set('title', $language->get('heading_title'));

		if (($request->isPost()) && ($this->validate())) {
			$password = substr(md5(rand()), 0, 7);
			
			$mail = $this->locator->create('mail');
			
			$mail->setTo($request->get('email', 'post'));
			$mail->setFrom($config->get('config_email'));
			$mail->setSender($config->get('config_store'));
			$mail->setSubject($language->get('email_subject', $config->get('config_store')));
			$mail->setText($language->get('email_message', $config->get('config_store'), $config->get('config_store'), $password));
			$mail->send();

			$database->query($database->parse("update customer set password = '?' where email = '?'", md5($password), $request->get('email', 'post')));

			$session->set('message', $language->get('text_message'));

			$response->redirect($url->ssl('account_login'));
		}

		$view = $this->locator->create('template');

		$view->set('heading_title', $language->get('heading_title'));

		$view->set('text_your_email', $language->get('text_your_email'));
		$view->set('text_email', $language->get('text_email'));

		$view->set('entry_email', $language->get('entry_email'));

		$view->set('button_continue', $language->get('button_continue'));
		$view->set('button_back', $language->get('button_back'));

		$view->set('error', @$this->error['message']);

		$view->set('action', $url->ssl('account_forgotten'));
 
		$view->set('back', $url->ssl('account'));

		$template->set('content', $view->fetch('content/account_forgotten.tpl'));

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function validate() {
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');		
		$request  =& $this->locator->get('request');
		
		if (!$request->get('email', 'post')) {
			$this->error['message'] = $language->get('error_email');
		}  elseif (!$database->getRow($database->parse("select * from customer where email = '?'", $request->get('email', 'post')))) {
			$this->error['message'] = $language->get('error_email');
		}

		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
?>