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

	class Loginctrl extends CI_Controller {
		public $Loginmdl;
		public $excel;
		public function __construct(){

			parent::__construct();

			$this->load->model('Loginmdl');
			$this->load->library('session');
			$this->load->library('form_validation');
			$this->load->library('db_operations');
			$this->load->helper('cookie');
		}

		public function index()
		{

			$record['year_range'] = $this->get_year_range();

			$this->load->view('login', $record);
		}

		public function get_year_range()
		{
			if (date('m') > 3)
			{
			    $years = range('2000', date('Y')+1);
			}
			else
			{
			    $years = range('2000', date('Y'));
			}
			$range = array();
			$size = sizeOf($years);

			foreach ($years as $key => $value)
			{
				if($key != $size - 1)
					$range[$key] = $value."-".$years[$key+1];
			}
			return array_reverse($range);
		}


		public function login_action() {

			$form_data = $this->input->post();

			// echo "<pre>";print_r($form_data);exit();

            $cnt = $this->Loginmdl->get_cnt('user_master', array('user_name' => $form_data['user_name']));

            if($cnt != 0){

            	$record = $this->Loginmdl->get_user($form_data['user_name']);
        		if($record[0]['user_password'] == md5($form_data['user_password'])){

        			$year_arr 	= explode("-", $form_data['year']);
        			$start_date = $year_arr[0]."-04-01";
        			$end_date 	= $year_arr[1]."-03-31";
                    $month = date('M');
        			$session_data = array(

						'user_id' 			=> $record[0]['user_id'],
						'user_role_id' 		=> $record[0]['user_role_id'],
						'user_name' 		=> $record[0]['user_name'],
						'user_full_name' 	=> $record[0]['user_full_name'],
						'fin_year' 			=> $form_data['year'],
						'start_date' 		=> $start_date,
						'end_date' 			=> $end_date,
						'fin_month'         => $month
					);

					$this->session->set_userdata($session_data);

					$arr = array(
							'user_log_status' => 1,
							'user_ip' => $_SERVER["REMOTE_ADDR"]
						);

					$this->db_operations->data_update("user_master", $arr, 'user_id', $record[0]['user_id']);

					echo 1;

        		}
        		else
        		{
					echo 2;
        		}
            }
        	else
        	{
        		echo 3;
        	}
		}

		public function logout(){

			$arr = array(
				'user_log_status' => 0,
				'user_ip' => $_SERVER["REMOTE_ADDR"]
			);

			$user_id = $this->session->userdata('user_id');
			$this->db_operations->data_update("user_master", $arr, 'user_id', $user_id);

			$this->session->sess_destroy();

			redirect(base_url());
		}

		public function check_session_status(){

			echo get_cookie('session_user_id');
		}
	}
?>