<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends MY_Controller {

	public function index()
	{
		if( ! $this->session->userdata('user_type')) {
			$this->lang->load('account_general', get_language());
				
			$data['page_title'] = $this->lang->line('hf_login') . ' - ' . $this->lang->line('website_name');
			
			$this->load->view('login', $data);
		}
		else {
			$this->session->unset_userdata(array('user_id' => '', 'user_name' => '', 'username' => '', 'user_login_datetime' => '', 'user_type' => ''));
			redirect('home', 'refresh');
		}		
	}
	
	public function submit()
	{
		if( ! $this->session->userdata('user_type')) {
			$this->lang->load('account_general', get_language());
			
			$use_captcha = true;
			
			if(!$_POST) exit;
			
			$username = trim($this->input->post('username', TRUE));
			$password = trim($this->input->post('password', TRUE));

			if ($username == '') {
				echo $this->lang->line('login_enter_username_message');
				exit();
			} else if ($password == '') {
				echo $this->lang->line('login_enter_password_message');
				exit();
			}
			
			session_start();

			if (isset($_SESSION['captcha'])) {
				$captcha_code = $this->input->post('captcha', TRUE);

				if ($_SESSION['captcha'] != $captcha_code) {
					echo $this->lang->line('login_invalid_captcha_message');
					exit();
				}
				else {
					unset($_SESSION['captcha']);
				}

			} else if($use_captcha) {
				echo $this->lang->line('login_enter_captcha_message');
				exit();
			}
			
			#Check for username availbility
			$query = $this->db->query("SELECT user_id, real_name, username, password, status, user_type FROM sw_users WHERE username = ? LIMIT 1", array($username));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$verify_password = sha1(md5(sha1(md5($password)) . sha1(md5($this->config->item('encryption_key')))));
				
				if($row->password == $verify_password) {
					$this->session->set_userdata(array('user_id' => $row->user_id, 'user_name' => $row->real_name, 'username' => $row->username, 'user_login_datetime' => date('Y-m-d H:i'), 'user_type' => $row->user_type));
					
					$this->db->trans_start();
					
					$this->db->query("UPDATE sw_users SET last_login_date = ? WHERE user_id = ? AND username = ? LIMIT 1", array(time(), $row->user_id, $row->username));
						
					$this->load->model('user_model');
					$this->user_model->insert_user_log($row->user_id, LOG_LOGIN);
					
					$this->db->trans_complete();
					
					if ($this->db->trans_status() === TRUE) {
						echo 'success';
					}
					else {
						echo $this->lang->line('login_failed');
					}
				}
				else {
					echo $this->lang->line('login_invalid_username_or_password');
				}
			}
			else {
				echo $this->lang->line('login_invalid_username_or_password');
			}
		}
		else {
			redirect('home', 'refresh');
		}		
	}
}

/* End of file login.php */
/* Location: ./application/controllers/login.php */