<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller
{
	public function __construct()
	{ 
		parent:: __construct();
		session_start();
		$this->load->model('common_model');
	}
	public function index()
	{
		if($this->session->userdata('admin_id') || get_cookie('admin_id'))
		{
			redirect('admin/dashboard');
		}
		$this->load->view('admin/login');
	}

	public function doLogin()
	{
		if($this->input->post())
		{
			if($this->utility->getSecurity()!=$this->input->post('frmSecurity'))
			{
				$this->utility->setMsg('Session expired.. Please try again..','ERROR');
				redirect(base_url().'admin/login');
			}
			$this->form_validation->set_rules('email','Email','trim|required|valid_email');
			$this->form_validation->set_rules('password','Password','required');
			if($this->form_validation->run())
			{
				$emailExist = $this->common_model->getAllRow('usr_users',array('email'=>$this->utility->info_cleanQuery($this->input->post('email'))));
				if(!empty($emailExist))
				{
					$inputPassword  = $this->common_model->generateHash($this->utility->info_cleanQuery($this->input->post('password')));
					$password  = $emailExist['password'];
					
					if($inputPassword == $password )
					{
						$isAdmin = $this->common_model->getAllRow('usr_roles_users',array('user_id'=>$emailExist['id']));
						if(!empty($isAdmin))
						{
							$this->session->set_userdata('admin_id',$emailExist['id']);
							$_SESSION['ad_id'] = $emailExist['id']; 
							$cookie = array(
							        'name'   => 'admin_id',
							        'value'  => $emailExist['id'],
							        'expire' => time()+86500,
							        );
							 
							set_cookie($cookie);
							redirect(base_url().'admin/dashboard');
						}
						else
						{
							$this->utility->setMsg('You are not an Admin','ERROR');
							redirect(base_url().'admin/login');
						}
					}
					else
					{
						$this->utility->setMsg('Invalid password','ERROR');
						redirect(base_url().'admin/login');
					}
				}
				else
				{
					$this->utility->setMsg('Invalid email','ERROR');
					redirect(base_url().'admin/login');
				}
			}
			else{
				$this->utility->setMsg(validation_errors(),'ERROR');
				redirect(base_url().'admin/login');
			}
		}
		else
		{
			redirect(base_url().'admin/login');
		}
	}

	public function logout()
	{
		$this->session->unset_userdata('admin_id');
		$cookie = array(
		        'name'   => 'admin_id',
		        'value'  => '',
		        'expire' => 0,
		        );
		 
		delete_cookie($cookie);
        $this->utility->setMsg('Successfully Logged out','SUCCESS');
		redirect(base_url().'admin/login');
	}
}
