<?php
require_once ("person_controller.php");
class Employees extends Person_controller
{
	function __construct()
	{
		parent::__construct('employees');
	}

	function index()
	{
		$config['base_url'] = site_url('/employees/index');
		$config['total_rows'] = $this->Employee->count_all();
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$this->pagination->initialize($config);

		$data['controller_name']=strtolower(get_class());
		$data['form_width']=$this->get_form_width();
		$data['manage_table']=get_people_manage_table( $this->Employee->get_all( $config['per_page'], $this->uri->segment( $config['uri_segment'] ) ), $this );
		$this->load->view('people/manage',$data);
	}

	/*
	Returns employee table data rows. This will be called with AJAX.
	*/
	function search()
	{
		$search=$this->input->post('search');
		$data_rows=get_people_manage_table_data_rows($this->Employee->search($search),$this);
		echo $data_rows;
	}

	/*
	Gives search suggestions based on what is being searched for
	*/
	function suggest()
	{
		$suggestions = $this->Employee->get_search_suggestions($this->input->post('q'),$this->input->post('limit'));
		echo implode("\n",$suggestions);
	}

	/*
	Loads the employee edit form
	*/
	function view($employee_id=-1)
	{
		$data['person_info']=$this->Employee->get_info($employee_id);
		$data['all_modules']=$this->Module->get_all_modules();
		$this->load->view("employees/form",$data);
	}

	function change_password($employee_id=-1)
	{
		$data['person_info']=$this->Employee->get_info($employee_id);
		$data['all_modules']=$this->Module->get_all_modules();
		$this->load->view("employees/change_password_form",$data);
	}

	function report_password($employee_id=-1)
	{

		$data['person_info']=$this->Employee->get_info($employee_id);
		$data['all_modules']=$this->Module->get_all_modules();
		$this->load->view("employees/report_password_form",$data);
	}

	function sales_details($employee_id=-1)
	{
		$data['person_info']=$this->Employee->get_info($employee_id);

		$data['all_modules']=$this->Module->get_all_modules();
		$current_date=date("Y-m-d");

		$path_to_root=getcwd();
		include($path_to_root . "/application/config/database.php");
		$conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
		mysql_select_db($db['default']['database'], $conn);

		$sales_details = array();
		$result = mysql_query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND location='".LOCATION_CODE."' AND is_sync=0 AND is_permission=0 AND clr_sync=0) AND quantity_purchased>0 ORDER BY sale_id ASC,line ASC ");
		while($row = mysql_fetch_assoc($result)){
			$sales_details[] = $row;
		}

		$data['sale_details']=$sales_details;

		$this->load->view("employees/sales_details_form",$data);
	}
	function save_permission($employee_id=-1)
	{

		$current_date=date("Y-m-d");

		if(count($_POST)){

			$path_to_root=getcwd();
			include($path_to_root . "/application/config/database.php");
			$conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
			mysql_select_db($db['default']['database'], $conn);

			$sales_details = array();
			$result = mysql_query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND location='".LOCATION_CODE."' AND is_sync=0 AND is_permission=0 AND clr_sync=0) AND quantity_purchased>0 ORDER BY sale_id ASC,line ASC ");
			while($row = mysql_fetch_assoc($result)){
				$sales_details[] = $row;
			}



			foreach ($sales_details as $key => $value) {
				$reset_index=$value['sale_id']."_".$value['line']."_".$value['stock_id']."_".$value['lot_no'];
				$reset_index_previous=$value['sale_id']."_".$value['line']."_".$value['stock_id']."_".$value['lot_no']."_previous";

				$update_sync_permission=0;


				if(intval($this->input->post($reset_index))){

					if(intval($this->input->post($reset_index))>intval($this->input->post($reset_index_previous))){
						$update_sync_permission=intval($this->input->post($reset_index))-intval($this->input->post($reset_index_previous));
					}
				}


				$update_query="UPDATE ospos_sales_items SET sync_permission='".$update_sync_permission."'
			WHERE sale_id='".$value['sale_id']."' AND line='".$value['line']."' AND stock_id='".$value['stock_id']."' AND lot_no='".$value['lot_no']."'";

				mysql_query($update_query);
				$success=true;
			}
		}else{
			$success=false;
		}
		if($success)
		{
			echo json_encode(array('success'=>true,'message'=>'Update Successfully','person_id'=>$employee_id));
		}
		else//failure
		{
			echo json_encode(array('success'=>false,'message'=>'Post data is not submitted. please try again','person_id'=>$employee_id));
		}
	}

	/*
	Inserts/updates an employee
	*/
	function save($employee_id=-1)
	{


		$person_data = array(
		'first_name'=>$this->input->post('first_name'),
		'last_name'=>$this->input->post('last_name'),
		'email'=>$this->input->post('email'),
		'phone_number'=>$this->input->post('phone_number'),
		'address_1'=>$this->input->post('address_1'),
		'address_2'=>$this->input->post('address_2'),
		'city'=>$this->input->post('city'),
		'state'=>$this->input->post('state'),
		'zip'=>$this->input->post('zip'),
		'country'=>$this->input->post('country'),
		'comments'=>$this->input->post('comments')
		);
		$permission_data = $this->input->post("permissions")!=false ? $this->input->post("permissions"):array();

		//Password has been changed OR first time password set
		if($this->input->post('password')!='')
		{
			$employee_data=array(
			'username'=>$this->input->post('username'),
			'password'=>md5($this->input->post('password'))
			);
		}
		else //Password not changed
		{
			$employee_data=array('username'=>$this->input->post('username'));
		}

		if($this->Employee->save($person_data,$employee_data,$permission_data,$employee_id))
		{
			//New employee
			if($employee_id==-1)
			{
				echo json_encode(array('success'=>true,'message'=>$this->lang->line('employees_successful_adding').' '.
				$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>$employee_data['person_id']));
			}
			else //previous employee
			{
				echo json_encode(array('success'=>true,'message'=>$this->lang->line('employees_successful_updating').' '.
				$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>$employee_id));
			}
		}
		else//failure
		{
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('employees_error_adding_updating').' '.
			$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>-1));
		}
	}

	function save_password($employee_id=-1)
	{
		$old_pass_exist=$this->Employee->check_old_password($this->input->post('username'),md5($this->input->post('old_password')));

		if($old_pass_exist==0){
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('employees_error_old_password'),'person_id'=>$employee_id));

		}else{
			if($this->Employee->change_pass_save($this->input->post('username'),md5($this->input->post('password')),$employee_id))
			{
				echo json_encode(array('success'=>true,'message'=>$this->lang->line('employees_successful_password_change'),'person_id'=>$employee_id));

			}
			else//failure
			{
				echo json_encode(array('success'=>false,'message'=>$this->lang->line('employees_error_password_change'),'person_id'=>$employee_id));
			}
		}
	}

	function check_report_password($employee_id=-1)
	{


		$file_content_live=file_get_contents("http://sales.grameenshamogree.com/admin/sales_password_for_local/sales_password_".LOCATION_CODE.".txt");
		$current_directory=getcwd();
		$file_name_with_date="sales_password.txt";
		$filename = $current_directory.'\pdf_report\report_file_runtime\\'.$file_name_with_date;
		$text=trim($file_content_live);
		if(trim($text)){
			if (!file_exists($filename)) {
				$fhandle = fopen($filename,"w");
				fwrite($fhandle,$text);
				fclose($fhandle);
			}else{
				$fhandle = fopen($filename,"w");
				fwrite($fhandle,$text);
				fclose($fhandle);
			}
		}

		$this->session->set_userdata('report_check_password','');
		$this->session->set_userdata('report_check_weekend','');
		$this->session->set_userdata('report_check_leave_start','');
		$this->session->set_userdata('report_check_leave_end','');
		$this->session->set_userdata('report_check_session_start','1983-01-01 10:20:30');
		$this->session->set_userdata('report_check_session_end','1983-01-01 10:25:30');
		$this->session->set_userdata('report_full_access','0');
		$this->session->set_userdata('report_pass_all_condition','0');


		if ($fd = fopen($filename, 'rb')) {
			$saved_data = fread($fd, filesize($filename));
			fclose($fd);

			$saved_data_array=explode("@#@",$saved_data);

			$sales_password=$saved_data_array[0];
			$sales_weekend=$saved_data_array[1];
			$sales_leave_start=$saved_data_array[2];
			$sales_leave_end=$saved_data_array[3];


			if(md5($this->input->post('password'))==$sales_password){
				$this->session->set_userdata('report_check_password',$sales_password);
				$this->session->set_userdata('report_check_session_start',date("Y-m-d H:i:s"));

				$reprint_password_session_start=date("Y-m-d H:i:s");
				$reprint_password_session_end=date("Y-m-d H:i:s",strtotime($reprint_password_session_start)+(60*5));
				$this->session->set_userdata('report_check_session_end',$reprint_password_session_end);
				$this->session->set_userdata('report_full_access','1');
				$this->session->set_userdata('report_pass_all_condition','1');
			}else{


				$current_directory=getcwd();
				$file_name_with_date="report_password_illegal_activity.txt";
				$filename = $current_directory.'\pdf_report\report_file_runtime\\'.$file_name_with_date;
				$text=$this->input->post('password')."|@#@|".date("Y-m-d H:i:s")."\n";

				if (!file_exists($filename)) {
					$fhandle = fopen($filename,"w");
					fwrite($fhandle,$text);
					fclose($fhandle);
				}else{
					if ($fd = fopen($filename, 'rb')) {
						$data = fread($fd, filesize($filename));
						fclose($fd);
						$text_final=$data.$text;
						$fhandle = fopen($filename,"w");
						fwrite($fhandle,$text_final);
						fclose($fhandle);
					}
				}
			}
			$this->session->set_userdata('report_check_weekend',$sales_weekend);
			$this->session->set_userdata('report_check_leave_start',$sales_leave_start);
			$this->session->set_userdata('report_check_leave_end',$sales_leave_end);
		}
		redirect('/sales');
	}

	/*
	This deletes employees from the employees table
	*/
	function delete()
	{
		$employees_to_delete=$this->input->post('ids');

		if($this->Employee->delete_list($employees_to_delete))
		{
			echo json_encode(array('success'=>true,'message'=>$this->lang->line('employees_successful_deleted').' '.
			count($employees_to_delete).' '.$this->lang->line('employees_one_or_multiple')));
		}
		else
		{
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('employees_cannot_be_deleted')));
		}
	}
	/*
	get the width for the add/edit form
	*/
	function get_form_width()
	{
		return 650;
	}
}
?>