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

use Nilambar\NepaliDate\NepaliDate;

require_once '../vendor/autoload.php';

class HRAdmin extends CI_Controller
{
	private $nepaliDateObject;
	private $nepali_current_date;

	public function __construct()
	{
		parent::__construct();

		//Load the required models here
		$this->load->model('HRAdmin_Model');
		$this->load->model('classroom_model');
		$this->load->model('School_model');
		//Load the required helpers here
		$this->load->helper('common_helper');
		$this->load->library('upload');
		date_default_timezone_set('Asia/Kathmandu');
		$this->nepaliDateObject = new NepaliDate();
		$this->nepali_current_date = cuurentNepaliDate($this->nepaliDateObject);
	}

	public function is_valid_admin_emailid($eid)
	{
		$this->form_validation->set_message('is_valid_admin_emailid', 'This Email Id does not exist. Please check again.');

		if ($this->HRAdmin_Model->check_is_emailid_valid($eid))
			return true;
		else
			return false;
	}

	public function is_valid_admin_credentials()
	{
		$eid = $_POST['email'];
		$encrypt_password = md5($_POST['password']);
		$this->form_validation->set_message('is_valid_admin_credentials', 'Invalid password. Please check again.');

		if ($this->HRAdmin_Model->check_login_credentials($eid, $encrypt_password))
			return true;
		else
			return false;
	}

	public function login()
	{
		$data['title'] = 'Admin Login';

		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_is_valid_admin_emailid');
		$this->form_validation->set_rules('password', 'Password', 'required');
		if (isset($_POST['password']) && $_POST['password'] != '')
			$this->form_validation->set_rules('password', 'Password', 'callback_is_valid_admin_credentials');

		if ($this->form_validation->run() === FALSE) {
			$this->load->view('bustracking-admin/login', $data);
		} else {
			$encrypt_password = md5($this->input->post('password'));
			$where = 'email="' . $this->input->post('email') . '" AND password="' . $encrypt_password . '"';

			$loginData = $this->HRAdmin_Model->get_admin_details($where);
			if (isset($loginData[0]) && !empty($loginData[0])) {
				if ($loginData[0]['status'] == 'Active') {
					if (isset($_POST['remember_me']) && $_POST['remember_me'] == 'on') {
						//set 0 instead of time to remove the cookie once the browser is closed
						setcookie("username", $_POST["email"], time() + 86400); 	//86400 seconds in a day
						setcookie("password", $_POST["password"], time() + 86400);
						setcookie("rem_me", 'On', time() + 86400);
					} else {
						if (isset($_COOKIE['username'])) {
							unset($_COOKIE['username']);
							setcookie('username', '');
						}
						if (isset($_COOKIE['password'])) {
							unset($_COOKIE['password']);
							setcookie('password', '');
						}
						if (isset($_COOKIE['rem_me'])) {
							unset($_COOKIE['rem_me']);
							setcookie('rem_me', '');
						}
					}

					$lnData = array(
						'bt_lin_id' => $loginData[0]['id'],
						'bt_lin_name' => $loginData[0]['admin_name'],
						'bt_lin_login' => true,
					);
					$this->session->set_userdata('hrAULoginData', $lnData);
					$this->session->set_userdata('hr_admin_role_ids', $loginData[0]['admin_role_ids']);
					$this->session->set_userdata('hr_admin_id', $loginData[0]['id']);
					//Set Message
					$this->session->set_flashdata('success', 'Welcome To Admin Users Dashboard.');

					$redirectToHere = 'dashboard';

					$detailsHere = $this->HRAdmin_Model->get_admin_details('', "SELECT admin_role_ids FROM bt_admin WHERE id = " . $loginData[0]['id']);
					if (isset($detailsHere[0]['admin_role_ids']) && $detailsHere[0]['admin_role_ids'] != '') {
						$permissionDetailsHere = $this->HRAdmin_Model->get_bt_admin_role_permissions('', "SELECT menu_ids FROM bt_admin_role_permissions WHERE admin_role_ids IN(" . $detailsHere[0]['admin_role_ids'] . ")");
						$menuIdsHere = explode(',', $permissionDetailsHere[0]['menu_ids']);

						if (!empty($menuIdsHere)) {

							if (isset($menuDetailsHere[0]['page_link']) && $menuDetailsHere[0]['page_link'] != '')
								$redirectToHere = $menuDetailsHere[0]['page_link'];
						}
					}

					redirect(base_url() . $redirectToHere);
				} else {
					$this->session->set_flashdata('danger', 'Your account is inactive. Please contact the administrator.');
					$this->load->view('bustracking-admin/login', $data);
				}
			} else {
				$this->session->set_flashdata('danger', 'Login Credential in invalid!');
				$this->load->view('bustracking-admin/login', $data);
			}
		}
	}

	/*----------------------------------- SATRT Of Logout --------------------------------------------------------*/
	public function logout()
	{
		$this->common_logout();

		//Set Message
		$this->session->set_flashdata('success', 'You are logged out successfully.');
		redirect(base_url() . 'admin');
	}

	public function common_logout()
	{
		$lnEuIdId = 0;
		// unset the loggout admin user data
		$this->session->unset_userdata('hrAULoginData');
	}

	public function ajaxLogout()
	{
		$this->common_logout();
		echo 'Success';
		exit;
	}
	/*----------------------------------- ENDDD Of Logout --------------------------------------------------------*/

	/*----------------------------- START of Admin User Password Functionality -----------------------------*/
	public function fp_check_is_emailid_valid($eid)
	{
		$this->form_validation->set_message('fp_check_is_emailid_valid', 'This Email Id does not exist. Please check again.');

		if ($this->HRAdmin_Model->check_is_emailid_valid($eid))
			return true;
		else {
			return false;
		}
	}

	public function forgot_password()
	{
		if (!file_exists(APPPATH . 'views/bustracking-admin/forgot-password.php'))
			show_404();

		$data['title'] = 'Forgot Password';

		$this->form_validation->set_rules('email', 'email', 'required|valid_email|callback_fp_check_is_emailid_valid');

		if ($this->form_validation->run() === FALSE) {
			$this->load->view('bustracking-admin/forgot-password', $data);
		} else {
			$where = 'email="' . $this->input->post('email') . '" ';
			$detailsHere = $this->HRAdmin_Model->get_admin_details($where);
			$rpData['nameHere'] = '';
			if (isset($detailsHere[0]['admin_name']))
				$rpData['nameHere'] = $detailsHere[0]['admin_name'];

			$rpData['emailId'] = urlsafe_b64encode($this->input->post('email'));
			$emailContent = $this->load->view('bustracking-admin/emails/admin-user-forgot-password.php', $rpData, TRUE);

			$emailData['to'] = $this->input->post('email');
			$emailData['subject'] = 'Erisn Classroom Bustracking - Admin User Password Recovery Mail';
			$emailData['message'] = $emailContent;
			//echo $emailContent;exit;

			$result = ciSendEmail($emailData);

			$this->session->set_userdata('isForgotPasswordSuccess', 'Yes');
			$this->load->view('bustracking-admin/forgot-password', $data);
		}
	}

	function reset_password($encodedEmailId)
	{
		if (isset($encodedEmailId) && $encodedEmailId != '') {
			$decodedEmailId = urlsafe_b64decode($encodedEmailId);

			$data['encodedEmailId'] = $encodedEmailId;
			$data['title'] = 'Reset Password';

			$this->form_validation->set_rules('password', 'Enter New Password', 'trim|required');
			$this->form_validation->set_rules('conf_password', 'Retype New Password', 'required|matches[password]');
			if ($this->form_validation->run() === FALSE) {
				$this->load->view('bustracking-admin/reset-password', $data);
			} else {
				$where = 'email ="' . $decodedEmailId . '"';
				$isValidUser = $this->HRAdmin_Model->get_admin_details($where);

				if (!empty($isValidUser) && count($isValidUser) == 1) {
					$this->HRAdmin_Model->reset_admin_password($isValidUser[0]['id'], $this->input->post('password'));

					//Set Message
					$this->session->set_userdata('isResetPasswordSuccess', 'Yes');
					redirect('reset-password/' . $encodedEmailId);
				} else {
					$this->session->set_flashdata('danger', 'OOps. Something went wrong.');
					redirect('reset-password/' . $encodedEmailId);
				}
			}
		} else {
			redirect(base_url() . "admin");
		}
	}
	/*----------------------------- ENDDD of Admin User Password Functionality -----------------------------*/


	public function dashboard()
	{
		// print_r($_SESSION['hrAULoginData']['bt_lin_id']);
		// exit();
		if (!isset($_SESSION['hrAULoginData']))
			redirect(base_url() . 'admin');
		$data['currentURL'] = current_url();
		$data['title'] = 'Dashboard';
		$data['driver_count'] = $this->HRAdmin_Model->count_query('bt_drivers');
		$data['bus_count'] = $this->HRAdmin_Model->count_query('bt_buses');
		$data['student_count'] = $this->HRAdmin_Model->count_query('bt_students_bus_route_details');
		$data['school_info'] = $this->classroom_model->get_logo_from_setting();
		$query = $this->db->query('select * from bt_routes');

		$data['route_name'] = $query->result_array();

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/dashboard', $data);
	}

	/*----------------------------------- START Of Admin Roles --------------------------------------------------------*/
	public function roles()
	{
		if (!isset($_SESSION['hr_admin_id']))
			redirect(base_url() . 'admin');
		$data['currentURL'] = current_url();
		$data['title'] = 'Designations';
		$data['school_info'] = $this->classroom_model->get_logo_from_setting();

		$sqlRole = 'SELECT r.*, rp.menu_ids FROM bt_admin_roles AS r, bt_admin_role_permissions AS rp WHERE r.id = rp.admin_role_ids';
		$rolesList = $this->HRAdmin_Model->get_bt_admin_roles('', $sqlRole);
		if (!empty($rolesList)) {
			foreach ($rolesList as $key => $role) {
				$rPs = '';
				$sqlRolePermissions = 'SELECT menu_name FROM bt_admin_menu WHERE id IN(' . $role['menu_ids'] . ')';
				$rolePermissions = $this->HRAdmin_Model->get_bt_admin_roles('', $sqlRolePermissions);
				if (!empty($rolePermissions)) {
					foreach ($rolePermissions as $p) {
						if ($rPs == '')
							$rPs = $p['menu_name'];
						else
							$rPs .= ',' . $p['menu_name'];
					}
				}
				$rolesList[$key]['permissions'] = $rPs;
			}
		}
		$data['roleList'] = $rolesList;
		//echo '<pre>'; print_r($data['roleList']);exit;

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/roles', $data);
	}

	public function ajaxCheckIsRoleAlreadyExists()
	{
		$result = 'Insufficient Data';
		if (isset($_POST['role_name']) && $_POST['role_name'] != '' && isset($_POST['id']) && $_POST['id'] != '') {
			if ($this->HRAdmin_Model->check_role_exists($_POST['id'], $_POST['role_name']))
				$result = 'Unique Role';
			else
				$result = 'Duplicate Role';
		}
		echo $result;
		exit;
	}

	public function add_edit_role($idVal)
	{
		$sql = "SELECT * FROM bt_admin_roles WHERE id = $idVal";
		$details = $this->HRAdmin_Model->get_bt_admin_roles("id = $idVal");
		if (empty($details) && $idVal != 0)
			redirect(base_url() . 'roles');

		$data['title'] = 'Add New Role';
		if ($idVal > 0)
			$data['title'] = 'Update Role';
		$data['school_info'] = $this->classroom_model->get_logo_from_setting();

		$data['details'] = $details;
		$data['idVal'] = $idVal;
		$data['menus'] = $this->HRAdmin_Model->get_admin_menu_details('', 'SELECT id,menu_name FROM bt_admin_menu WHERE status="Active" AND parent_id=0');
		$data['role_permissions'] = $this->HRAdmin_Model->get_bt_admin_role_permissions('', "SELECT menu_ids FROM bt_admin_role_permissions WHERE admin_role_ids = $idVal");

		if (count($_POST) > 0) {
			$permissions = '';
			if (isset($_POST['role_permissions']) && !empty($_POST['role_permissions'])) {
				$permissions = implode(',', $_POST['role_permissions']);
				unset($_POST['role_permissions']);
			}

			$res = $this->HRAdmin_Model->add_edit_admin_role($idVal, $_POST);
			if ($res) {
				if ($permissions != '') {
					if ($idVal == 0) {
						$rpData['admin_role_ids'] = $res;
						$rpData['menu_ids'] = $permissions;
						$this->HRAdmin_Model->add_edit_admin_role_permissions(0, $rpData);
					} else {
						$getRPrid = $this->HRAdmin_Model->get_bt_admin_role_permissions('', "SELECT id FROM bt_admin_role_permissions WHERE admin_role_ids = $idVal");
						if (isset($getRPrid[0]['id'])) {
							$rpData['admin_role_ids'] = $idVal;
							$rpData['menu_ids'] = $permissions;
							$this->HRAdmin_Model->add_edit_admin_role_permissions($getRPrid[0]['id'], $rpData);
						}
					}
				}
				$this->session->set_flashdata('success', str_replace('%s', 'new role', THE_ADD_SUCCESS_MSG));
				if ($idVal > 0)
					$this->session->set_flashdata('success', str_replace('%s', 'role', THE_UPDATE_SUCCESS_MSG));
			}
			redirect(base_url() . 'roles');
		}

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/add-edit-role', $data);
	}

	public function delete_role()
	{
		$roleId = $_POST['id'];
		$sql = "SELECT id FROM bt_admin WHERE admin_role_ids=" . $roleId;
		$result = $this->HRAdmin_Model->get_admin_details('', $sql);
		//echo '<pre>'; print_r($result);exit;
		if (!empty($result))
			echo 'Error';
		else {
			$this->HRAdmin_Model->delete_admin_role($roleId);
			echo 'Success';
		}
	}
	/*----------------------------------- ENDDD Of Admin Roles --------------------------------------------------------*/

	/*----------------------------------- START Of Admin Users --------------------------------------------------------*/
	public function users()
	{
		$data['title'] = 'Users';

		$sql = 'SELECT a.*, ar.role_name FROM bt_admin AS a, bt_admin_roles AS ar WHERE a.admin_role_ids = ar.id';
		$data['userList'] = $this->HRAdmin_Model->get_admin_details('', $sql);
		$data['school_info'] = $this->classroom_model->get_logo_from_setting();
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/users', $data);
	}

	public function ajaxCheckIsUserEmailAlreadyExists()
	{
		$result = 'Insufficient Data';
		if (isset($_POST['email']) && $_POST['email'] != '' && isset($_POST['id']) && $_POST['id'] != '') {
			if ($this->HRAdmin_Model->check_emailid_exists($_POST['id'], $_POST['email']))
				$result = 'Unique Email';
			else
				$result = 'Duplicate Email';
		}
		echo $result;
		exit;
	}

	public function add_edit_user($idVal)
	{
		$sql = "SELECT * FROM bt_admin WHERE id = $idVal";
		$details = $this->HRAdmin_Model->get_admin_details("id = $idVal");
		if (empty($details) && $idVal != 0)
			redirect(base_url() . 'users');

		$data['title'] = 'Add New User';
		if ($idVal > 0)
			$data['title'] = 'Update User';

		$data['details'] = $details;
		$data['idVal'] = $idVal;
		$data['roles'] = $this->HRAdmin_Model->get_bt_admin_roles('', 'SELECT id,role_name FROM bt_admin_roles WHERE status="Active"');

		if (count($_POST) > 0) {
			if (isset($_POST['password']))
				$_POST['password'] = md5($_POST['password']);
			if (isset($_POST['confirm_password']))
				unset($_POST['confirm_password']);

			$res = $this->HRAdmin_Model->add_edit_admin_user($idVal, $_POST);

			$this->session->set_flashdata('success', str_replace('%s', 'new user', THE_ADD_SUCCESS_MSG));
			if ($idVal > 0)
				$this->session->set_flashdata('success', str_replace('%s', 'user', THE_UPDATE_SUCCESS_MSG));

			redirect(base_url() . 'users');
		}

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/add-edit-user', $data);
	}

	public function delete_user()
	{
		$userId = $_POST['id'];
		$result = $this->HRAdmin_Model->delete_admin_user($userId);
		if ($result)
			echo 'Success';
		else
			echo 'Error';
	}
	/*----------------------------------- ENDDD Of Admin Users --------------------------------------------------------*/

	/*----------Add Bus Code start here from Shankar--------------------------*/

	public function designation()
	{
		if (!isset($_SESSION['hr_admin_id']))
			redirect(base_url() . 'admin');
		$data['currentURL'] = current_url();
		$data['title'] = 'Designations';
		$data['school_info'] = $this->classroom_model->get_logo_from_setting();

		if (isset($_POST['addDesignation']) && $_POST['addDesignation'] == 'Add') {
			$designationTitle = $_POST['title'];

			$isUnique = $this->HRAdmin_Model->get_unique_name('title', $designationTitle, 'hr_designation');
			echo '<pre>';
			print_r($isUnique);

			if ($isUnique) {
				$in_data['title'] = $designationTitle;
				$in_data['is_active'] = 'yes';
				$in_data['created_on'] = $this->nepali_current_date;

				$in_data['modified_on'] =  $this->nepali_current_date;
				$this->db->insert('hr_designation', $in_data);
				$this->session->set_flashdata('success', str_replace('%s', 'Designation', 'New designation has been added.'));
			} else {
				$this->session->set_flashdata('danger', str_replace('%s', 'Designation', 'Designation title already exist.'));
			}
			redirect(base_url() . 'designation');
		} else if (isset($_POST['updateDesignation']) && $_POST['updateDesignation'] == 'Update') {
			$designationTitle = $_POST['title'];
			$designationId = $_POST['designationId'];

			$update_data = array(
				'title' => $designationTitle,
				'is_active' => $_POST['is_active'],
				'modified_on' =>  $this->nepali_current_date,
			);
			$this->db->where('id', $designationId);
			$update = $this->db->update("hr_designation", $update_data);
			if ($update) {

				$this->session->set_flashdata('success', str_replace('%s', 'Designation', 'Designation has been updated successfully.'));
			} else {
				$this->session->set_flashdata('danger', str_replace('%s', 'Designation', 'THE_ADD_ERROR_MSG'));
			}


			redirect(base_url() . 'designation');
		}

		$query = $this->db->query('select * from hr_designation');
		$data['designation_list'] = $query->result_array();

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/designation', $data);
	}

	public function staff_roles()
	{
		if (!isset($_SESSION['hr_admin_id']))
			redirect(base_url() . 'admin');
		$data['currentURL'] = current_url();
		$data['title'] = 'Staff Roles';
		$data['school_info'] = $this->classroom_model->get_logo_from_setting();

		if (isset($_POST['addStaffRole']) && $_POST['addStaffRole'] == 'Add') {
			$staffRoleTitle = $_POST['title'];

			$isUnique = $this->HRAdmin_Model->get_unique_name('title', $staffRoleTitle, 'staff_roles');
			// echo '<pre>';
			// print_r($isUnique);

			if ($isUnique) {
				$in_data['title'] = $staffRoleTitle;
				$in_data['is_active'] = 'yes';
				$in_data['created_on'] = $this->nepali_current_date;

				$in_data['modified_on'] =  $this->nepali_current_date;
				$this->db->insert('staff_roles', $in_data);
				$this->session->set_flashdata('success', str_replace('%s', 'Role', 'New has been added.'));
			} else {
				$this->session->set_flashdata('danger', str_replace('%s', 'Role', 'Role already exist.'));
			}
			redirect(base_url() . 'staff-roles');
		} else if (isset($_POST['updateStaffRole']) && $_POST['updateStaffRole'] == 'Update') {
			// var_dump($_POST);
			// exit();
			$staffRoleTitle = $_POST['title'];
			$staffRoleId = $_POST['roleId'];

			$update_data = array(
				'title' => $staffRoleTitle,
				'is_active' => $_POST['is_active'],
				'modified_on' =>  $this->nepali_current_date,
			);
			$this->db->where('id', $staffRoleId);
			$update = $this->db->update("staff_roles", $update_data);
			if ($update) {

				$this->session->set_flashdata('success', str_replace('%s', 'Roles', 'Role has been updated successfully.'));
			} else {
				$this->session->set_flashdata('danger', str_replace('%s', 'Roles', 'THE_ADD_ERROR_MSG'));
			}


			redirect(base_url() . 'staff-roles');
		}

		$query = $this->db->query('select * from staff_roles');
		$data['staffRole_list'] = $query->result_array();

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/staff-roles', $data);
	}
	public function department()
	{
		if (!isset($_SESSION['hr_admin_id']))
			redirect(base_url() . 'admin');
		$data['currentURL'] = current_url();
		$data['title'] = 'Departments';
		$data['school_info'] = $this->classroom_model->get_logo_from_setting();
		if (isset($_POST['addDepartment']) && $_POST['addDepartment'] == 'Add') {
			$departmentTitle = $_POST['title'];

			$isUnique = $this->HRAdmin_Model->get_unique_name('title', $departmentTitle, 'hr_department');
			echo '<pre>';
			print_r($isUnique);

			if ($isUnique) {
				$in_data['title'] = $departmentTitle;
				$in_data['is_active'] = 'yes';
				$in_data['created_on'] = $this->nepali_current_date;

				$in_data['modified_on'] =  $this->nepali_current_date;
				$this->db->insert('hr_department', $in_data);
				$this->session->set_flashdata('success', str_replace('%s', 'Department', 'New department has been added.'));
			} else {
				$this->session->set_flashdata('danger', str_replace('%s', 'Department', 'Department title already exist.'));
			}
			redirect(base_url() . 'department');
		} else if (isset($_POST['updateDepartment']) && $_POST['updateDepartment'] == 'Update') {
			$departmentTitle = $_POST['title'];
			$departmentId = $_POST['departmentId'];

			$update_data = array(
				'title' => $departmentTitle,
				'is_active' => $_POST['is_active'],
				'modified_on' =>  $this->nepali_current_date,
			);
			$this->db->where('id', $departmentId);
			$update = $this->db->update("hr_department", $update_data);
			if ($update) {

				$this->session->set_flashdata('success', str_replace('%s', 'Department', 'Department has been updated successfully.'));
			} else {
				$this->session->set_flashdata('danger', str_replace('%s', 'Department', 'THE_ADD_ERROR_MSG'));
			}


			redirect(base_url() . 'department');
		}

		$query = $this->db->query('select * from hr_department');
		$data['department_list'] = $query->result_array();

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/department', $data);
	}
	public function staffs()
	{
		if (!isset($_SESSION['hr_admin_id']))
			redirect(base_url() . 'admin');
		$data['currentURL'] = current_url();
		$data['title'] = 'Staffs';
		$data['school_info'] = $this->classroom_model->get_logo_from_setting();

		$staffQuery = "select s.*, sr.title as role_title, 
						IF(des.id is null,'-',des.title) as designation_title, 
						IF(dep.id is null,'-',dep.title) as department_title,
						IF(dep.id is null,'-',dep.title) as department_title
						from staffs s JOIN staff_roles sr ON sr.id=s.role 
						LEFT JOIN hr_designation des ON des.id=s.designations 
						LEFT JOIN hr_department dep ON dep.id=s.department";
		$query = $this->db->query($staffQuery);

		$data['staff_list'] = $query->result_array();
		// dd($data['staff_list']);
		$designation_query = $this->db->query('select * from hr_designation');
		$data['designation_list'] = $designation_query->result_array();

		$data['provinces'] = $this->School_model->get_table_info('provinces');

		$department_query = $this->db->query('select * from hr_department');
		$data['department_list'] = $department_query->result_array();

		$roles_query = $this->db->query('select * from staff_roles WHERE is_active = "yes"');
		$data['staff_roles'] = $roles_query->result_array();

		if (isset($_POST['updateStaff']) && $_POST['updateStaff'] == 'Update') {
			echo '<pre>';
			print_r($_POST);
			print_r($_FILES);
			$staffId = $_POST['theStaffId'];

			$profile = $_POST['staffPhoto'];
			$documentImage = $_POST['staffDocImg'];
			$otherDocument = $_POST['staffOtherDoc'];
			$resume = $_POST['staffResume'];
			$joiningLetter = $_POST['staffJoiningLetter'];

			if ($_FILES['photo']['size'] != 0) {
				$config['upload_path']   = '../assets_admin/images/teacher-profile/';
				$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
				if (!empty($profile)) {
					unlink('../assets_admin/images/teacher-profile/' . $profile);
				}
				$config['file_name'] =  $staffId . '_profile';
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('photo')) {
					$profile = "";
				} else {
					$photo = array('upload_data' => $this->upload->data());
					$profile = $photo['upload_data']['file_name'];
				}
			}

			if ($_FILES['document_image']['size'] != 0) {
				if (!empty($documentImage)) {
					unlink('../assets_admin/docs/staff-documents/' . $documentImage);
				}
				$config['upload_path']   = '../assets_admin/docs/staff-documents/';
				$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
				$config['file_name'] = $staffId . '_doc1';
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('document_image')) {
					$documentImage = "";
				} else {
					$photo = array('upload_data' => $this->upload->data());
					$documentImage = $photo['upload_data']['file_name'];
				}
			}

			if ($_FILES['other_document']['size'] != 0) {
				if (!empty($otherDocument)) {
					unlink('../assets_admin/docs/staff-documents/' . $otherDocument);
				}
				$config['upload_path']   = '../assets_admin/docs/staff-documents/';
				$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
				$config['file_name'] = $staffId . '_doc2';
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('other_document')) {
					$otherDocument = "";
				} else {
					$photo = array('upload_data' => $this->upload->data());
					$otherDocument = $photo['upload_data']['file_name'];
				}
			}
			if ($_FILES['resume']['size'] != 0) {
				if (!empty($resume)) {
					unlink('../assets_admin/docs/staff-documents/' . $resume);
				}
				$config['upload_path']   = '../assets_admin/docs/staff-documents/';
				$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
				$config['file_name'] = $staffId . '_resume';
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('resume')) {
					$resume = "";
				} else {
					$photo = array('upload_data' => $this->upload->data());
					$resume = $photo['upload_data']['file_name'];
				}
			}
			if ($_FILES['joining_letter']['size'] != 0) {
				if (!empty($joiningLetter)) {
					unlink('../assets_admin/docs/staff-documents/' . $joiningLetter);
				}
				$config['upload_path']   = '../assets_admin/docs/staff-documents/';
				$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
				$config['file_name'] = $staffId . '_joining_letter';
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('joining_letter')) {
					$joiningLetter = "";
				} else {
					$photo = array('upload_data' => $this->upload->data());
					$joiningLetter = $photo['upload_data']['file_name'];
				}
			}

			$data_array = array(
				'staffId' => $staffId,
				'name' => $_POST['name'],
				'gender' => $_POST['gender'],
				'dob' => $_POST['sdob'],
				'role' => $_POST['role'],
				'department' => $_POST['department'],
				'designations' => $_POST['designation'],
				'father_name' => $_POST['father_name'],
				'mother_name' => $_POST['mother_name'],
				'email' => $_POST['email'],
				'mobile' => $_POST['mobile'],
				'martial_status' => $_POST['martial_status'],
				'emergency_number' => $_POST['emergency_number'],
				'document_type' => $_POST['document_type'],
				'document_id' => $_POST['document_id'],
				'address' => $_POST['address'],
				'province' => $_POST['province'],
				'country' => $_POST['country'],
				'qualification' => $_POST['qualifications'],
				'experience' => $_POST['experience'],
				'date_of_joining' => $_POST['date_of_joining'],
				'epf_no' => $_POST['epf_no'],
				'basic_salary' => $_POST['basic_salary'],
				'contract_type' => $_POST['contract_type'],
				'bank_account_name' => $_POST['bank_account_name'],
				'bank_account_number' => $_POST['bank_account_number'],
				'bank_name' => $_POST['bank_name'],
				'branch_name' => $_POST['bank_branch'],
				'pan' => $_POST['pan'],
				'photo' => $profile,
				'other_document' => $otherDocument,
				'document_photo_1' => $documentImage,
				'resume' => $resume,
				'joining_letter' => $joiningLetter,
				'is_active' => $_POST['is_active'],
				'modified_on' => $this->nepali_current_date,
			);
			print_r($data_array);

			$this->db->where('id', $_POST['staffId']);
			$update = $this->db->update("staffs", $data_array);

			if ($update) {
				$this->session->set_flashdata('success', str_replace('%s', $_POST['name'], "Record has been updated successfully."));
				redirect(base_url() . 'staffs');
			} else {
				$this->session->set_flashdata('danger', str_replace('%s', 'Staff', 'Something went wrong. Try again.'));
				redirect(base_url() . 'staffs');
			}


			// exit();
		}
		$dateTimeArray = explode(' ', $this->nepali_current_date);
		$data['today_date'] = $dateTimeArray[0];
		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/staffs', $data);
	}

	public function ae_staff($id)
	{
		if (!isset($_SESSION['hr_admin_id']))
			redirect(base_url() . 'admin');
		$data['currentURL'] = current_url();

		$data['school_info'] = $this->classroom_model->get_logo_from_setting();

		$roles_query = $this->db->query('select * from staff_roles WHERE is_active = "yes"');
		$data['staff_roles'] = $roles_query->result_array();

		if ($id > 0) {
			$staff = $this->db->query('select * from staffs WHERE id = ' . $id)->row_array();
			$data['staff_detail'] = $staff;
			$data['title'] = 'Update Staff Record';
		} else {
			$data['title'] = 'Add New Staff';
		}

		if (isset($_POST['submit']) && $_POST['submit'] == 'Add New Staff') {
			echo '<pre>';
			print_r($_POST);
			print_r($_FILES);

			$staffIdPrefix = '';

			foreach ($data['staff_roles']  as $roleKey => $role) {

				if ($_POST['role'] == $role['id']) {
					$staffIdPrefix = substr($role['title'], 0, 1);
				}

				print_r($role['title']);
			}



			$this->db->select_max('id');
			$query  = $this->db->get('staffs');
			$res = $query->row_array();
			$pid = $res['id'] + 1;
			$school_prefix = (!empty($data['school_info']['school_prefix_id'])) ? $data['school_info']['school_prefix_id'] : 'BB';
			$staffId = $school_prefix . $staffIdPrefix . date('Ymd', strtotime($this->nepali_current_date)) . '0' . $pid;


			$mobile = $_POST['mobile'];

			$isUnique = $this->HRAdmin_Model->get_unique_name('mobile', $mobile, 'staffs');
			echo '<pre>';
			print_r($isUnique);

			if ($isUnique) {
				$profile = "";
				$documentImage = "";
				$otherDocument = "";
				$resume = "";
				$joiningLetter = "";

				if ($_FILES['photo']['size'] != 0) {
					$config['upload_path']   = '../assets_admin/images/teacher-profile/';
					$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
					$config['file_name'] = $staffId . '_profile';
					$this->load->library('upload', $config);
					$this->upload->initialize($config);
					if (!$this->upload->do_upload('photo')) {
						$profile = "";
					} else {
						$photo = array('upload_data' => $this->upload->data());
						$profile = $photo['upload_data']['file_name'];
					}
				}
				if ($_FILES['document_image']['size'] != 0) {
					$config['upload_path']   = '../assets_admin/docs/staff-documents/';
					$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
					$config['file_name'] = $staffId . '_doc1';
					$this->load->library('upload', $config);
					$this->upload->initialize($config);
					if (!$this->upload->do_upload('document_image')) {
						$documentImage = "";
					} else {
						$photo = array('upload_data' => $this->upload->data());
						$documentImage = $photo['upload_data']['file_name'];
					}
				}
				if ($_FILES['other_document']['size'] != 0) {
					$config['upload_path']   = '../assets_admin/docs/staff-documents/';
					$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
					$config['file_name'] = $staffId . '_doc2';
					$this->load->library('upload', $config);
					$this->upload->initialize($config);
					if (!$this->upload->do_upload('other_document')) {
						$otherDocument = "";
					} else {
						$photo = array('upload_data' => $this->upload->data());
						$otherDocument = $photo['upload_data']['file_name'];
					}
				}
				if ($_FILES['resume']['size'] != 0) {
					$config['upload_path']   = '../assets_admin/docs/staff-documents/';
					$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
					$config['file_name'] = $staffId . '_resume';
					$this->load->library('upload', $config);
					$this->upload->initialize($config);
					if (!$this->upload->do_upload('resume')) {
						$resume = "";
					} else {
						$photo = array('upload_data' => $this->upload->data());
						$resume = $photo['upload_data']['file_name'];
					}
				}
				if ($_FILES['joining_letter']['size'] != 0) {
					$config['upload_path']   = '../assets_admin/docs/staff-documents/';
					$config['allowed_types']     = 'gif|jpg|jpeg|png|jiff|jfif|pdf|doc|docx';
					$config['file_name'] = $staffId . '_joining_letter';
					$this->load->library('upload', $config);
					$this->upload->initialize($config);
					if (!$this->upload->do_upload('joining_letter')) {
						$joiningLetter = "";
					} else {
						$photo = array('upload_data' => $this->upload->data());
						$joiningLetter = $photo['upload_data']['file_name'];
					}
				}

				$data_array = array(
					'staffId' => $staffId,
					'name' => $_POST['name'],
					'gender' => $_POST['gender'],
					'dob' => $_POST['sdob'],
					'role' => $_POST['role'],
					'department' => $_POST['department'],
					'designations' => $_POST['designation'],
					'father_name' => $_POST['father_name'],
					'mother_name' => $_POST['mother_name'],
					'email' => $_POST['email'],
					'mobile' => $_POST['mobile'],
					'martial_status' => $_POST['martial_status'],
					'emergency_number' => $_POST['emergency_number'],
					'document_type' => $_POST['document_type'],
					'document_id' => $_POST['document_id'],
					'address' => $_POST['address'],
					'province' => $_POST['province'],
					'country' => $_POST['country'],
					'qualification' => $_POST['qualifications'],
					'experience' => $_POST['experience'],
					'date_of_joining' => $_POST['date_of_joining'],
					'epf_no' => $_POST['epf_no'],
					'basic_salary' => $_POST['basic_salary'],
					'contract_type' => $_POST['contract_type'],
					'bank_account_name' => $_POST['bank_account_name'],
					'bank_account_number' => $_POST['bank_account_number'],
					'bank_name' => $_POST['bank_name'],
					'branch_name' => $_POST['bank_branch'],
					'pan' => $_POST['pan'],
					'photo' => $profile,
					'other_document' => $otherDocument,
					'document_photo_1' => $documentImage,
					'resume' => $resume,
					'joining_letter' => $joiningLetter,
					'created_on' => $this->nepali_current_date,
					'modified_on' => $this->nepali_current_date,
				);
				print_r($data_array);

				$insert = $this->db->insert('staffs', $data_array);
				if ($insert) {
					$this->session->set_flashdata('success', 'New record has been inserted in staff.');
				} else {
					$this->session->set_flashdata('danger', 'Something went wrong. Please try again');
				}

				redirect(base_url() . 'staffs');
			} else {
				$this->session->set_flashdata('danger', str_replace('%s', 'Staff', 'Staff with the contact number already exists.'));
			}


			// exit();
		}

		$data['provinces'] = $this->School_model->get_table_info('provinces');

		$designation_query = $this->db->query('select * from hr_designation');
		$data['designation_list'] = $designation_query->result_array();

		$department_query = $this->db->query('select * from hr_department');
		$data['department_list'] = $department_query->result_array();



		$dateTimeArray = explode(' ', $this->nepali_current_date);
		$data['today_date'] = $dateTimeArray[0];
		// exit();

		$this->load->view('bustracking-admin/common/left-menu', $data);
		$this->load->view('bustracking-admin/common/header', $data);
		$this->load->view('bustracking-admin/ae-staff', $data);
	}
}