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

class Login extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->helper('form');
		$this->load->library('form_validation');
		$this->load->helper('url');
		$this->load->database();
		$this->load->model('Process');
	}
	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->view('login');
	}
	public function process()
	{
		//get the posted values
		$username = $this->input->post('username');
		$password = $this->input->post('pass');
		
		//form validation
		$this->form_validation->set_rules('username','Username','required');
		$this->form_validation->set_rules('pass','Password','required');
		$this->form_validation->set_error_delimiters('<span class="textfieldRequiredMsg">', '</span>');
		if ($this->form_validation->run() == FALSE)
		{
			$this->index();
		}
		else
		{
			$result = $this->Process->loginauth($username, $password);
			if($result)
			{
				$adminid = $result['admin_id'];;
				$this->session->set_userdata('adminid', $adminid);
				$loginname = $result['name'];
				$this->session->set_userdata('loginname', $loginname);
				redirect('Administrator/dashboard/');
			}
			else
			{
				$this->session->set_flashdata('flsh_msg', 'Invalid username or password');
				redirect('Login/');
			}
		}
	}
	public function changpass()
	{
		$adminid = $this->session->userdata('adminid');
		$oldpass = MD5($this->input->post('oldpass'));
		$newpass = MD5($this->input->post('newpass'));
		$data['query'] = $this->Process->ChangePassword($adminid);
		$old_password = $data['query']['password'];
		//echo $old_password;
		//die();
		if($old_password==$oldpass)
		{
			$query = $this->db->query("UPDATE tbl_admin set password='".$newpass."' where admin_id='".$adminid."' and password ='".$oldpass."'");	
			if($query)
			{
				echo '<p class="sucess">Password has been sucessfully changed.</p>';
			}
		}
		else
		{
			echo '<p class="red">Your old password is not correct.</p>';
		}
		
	}
}
