<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/* 	
 * 	Author 	: Herpan / Tanggal : 02-09-2014	
 * 	Revisi 	: Ferry / Tanggal : 02-02-2015
 */

class Employee extends CI_Controller {

    public $menu_id = 259;
    public $code = "Employee Code";
    public $name = "Employee Name";

    public function __construct() {
        parent::__construct();
        $this->load->helper('regex');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->helper('convert_date');
        $this->load->helper('custom_string_helper');

        $this->load->model('m_menu');
        $this->load->model('m_employee');
        $this->load->model('setup/m_branchinfo');
		$this->load->model('login/m_login');
	
		$is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
		if($is_login){

		}else{
			$username       = $this->session->userdata('username');
			$session_id     = $this->session->userdata('session_id');
			$this->m_login->delete_session($username,$session_id);
			$this->session->sess_destroy();

			$uri_func = $this->uri->segment(3);
			if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
				redirect(base_url() . 'login', 'refresh');
			}else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
				$result['status']   = 'session';
				$result['message']  = get_notification('session_destroy',0);
				echo json_encode($result);
				die();
			}
		}
    }

    public function index() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    // set data
                    $data['menu_id'] = $this->menu_id;

                    // get link from tbl_menu 
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $this->load->view('v_header');
                    $this->load->view('others/employee/v_employee', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function add() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    // set data
                    $data['menu_id'] = $this->menu_id;
                    $data['branch_info'] = $this->m_branchinfo->view_detail($this->session->userdata('branch'));

                    // get link from tbl_menu 
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $this->load->view('v_header');
                    $this->load->view('others/employee/v_new_employee', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function insert() {
        try {
            $txt_employeeno = trim($this->input->post('txt_employeeno'));
            $txt_employeename = trim($this->input->post('txt_employeename'));
            $cmb_departement = $this->input->post('cmb_departement');
            $cmb_jobtitle = $this->input->post('cmb_jobtitle');
            $txt_address = $this->input->post('txt_address');
            $cmb_city = $this->input->post('cmb_city');
            $cmb_state = $this->input->post('cmb_state');
            $cmb_country = $this->input->post('cmb_country');
            $txt_hire_date = $this->input->post('txt_hire_date');

            $resign_date = empty($txt_hire_date) ? null : date("Y-m-d", strtotime($txt_hire_date));
            $dataSend = [];
            $dataSend['data_employee'] = [];

            if (!regex_code($txt_employeeno)) {
                throw new Exception(msg_invalid_code($this->code));
            } else {
                if (!regex_name($txt_employeename)) {
                    throw new Exception(msg_invalid_name($this->name));
                } else {
                    if ($this->m_employee->check_code_exist($txt_employeeno) == TRUE) {
                        throw new Exception(msg_already_used($this->code));
                    } else {
                        $dataSend['data_employee'] = array(
                            'EmployeeCode' => strtoupper($txt_employeeno),
                            'EmployeeName' => strtoupper($txt_employeename),
                            'BranchCode' => $this->session->userdata('branch'), //$cmb_branch,
                            'DepartmentCode' => $cmb_departement,
                            'JobTitleCode' => $cmb_jobtitle,
                            'EmployeeAddress' => $txt_address,
                            'EmployeeCity' => $cmb_city,
                            'EmployeeState' => $cmb_state,
                            'EmployeeCountry' => $cmb_country,
                            'HireDate' => $resign_date,
                            'ResignDate' => NULL,
                            'TransStatus' => 1,
                            'LastUser' => $this->session->userdata("username")
                        );
                        //insert database
//                        $result_insert = $this->m_employee->insert($data);

                        $rstDataSend = $this->m_employee->datasend_employee_insert($dataSend);
                        if ($rstDataSend) {
                            $result['status'] = true;
                            $result['message'] = get_notification('insert', 1);
                        } else {
                            $result['status'] = false;
                            $result['message'] = get_notification('insert', 0);
                        }
                        echo json_encode($result);
                    }
                }
            }
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function insert_LAMA() {
        $txt_employeeno = trim($this->input->post('txt_employeeno'));
        $txt_employeename = trim($this->input->post('txt_employeename'));
        $cmb_departement = $this->input->post('cmb_departement');
        $cmb_jobtitle = $this->input->post('cmb_jobtitle');
        $txt_address = $this->input->post('txt_address');
        $cmb_city = $this->input->post('cmb_city');
        $cmb_state = $this->input->post('cmb_state');
        $cmb_country = $this->input->post('cmb_country');
        $txt_hire_date = $this->input->post('txt_hire_date');

        $resign_date = empty($txt_hire_date) ? null : date("Y-m-d", strtotime($txt_hire_date));

        if (!regex_code($txt_employeeno)) {
            $result['status'] = false;
            $result['message'] = msg_invalid_code($this->code);
        } else {
            if (!regex_name($txt_employeename)) {
                $result['status'] = false;
                $result['message'] = msg_invalid_name($this->name);
            } else {
                if ($this->m_employee->check_code_exist($txt_employeeno) == TRUE) {
                    $result['status'] = false;
                    $result['message'] = msg_already_used($this->code);
                } else {
                    $data = array(
                        'EmployeeCode' => strtoupper($txt_employeeno),
                        'EmployeeName' => strtoupper($txt_employeename),
                        'BranchCode' => $this->session->userdata('branch'), //$cmb_branch,
                        'DepartmentCode' => $cmb_departement,
                        'JobTitleCode' => $cmb_jobtitle,
                        'EmployeeAddress' => $txt_address,
                        'EmployeeCity' => $cmb_city,
                        'EmployeeState' => $cmb_state,
                        'EmployeeCountry' => $cmb_country,
                        'HireDate' => $resign_date,
                        'ResignDate' => NULL,
                        'TransStatus' => 1,
                        'LastUser' => $this->session->userdata("username")
                    );

                    //insert database
                    $this->db->trans_begin();
                    $result_insert = $this->m_employee->insert($data);

                    if ($result_insert == 0) {
                        $this->db->trans_rollback();
                        $result['status'] = false;
                        $result['message'] = get_notification('insert', 0);
                    } else {
                        $this->db->trans_commit();
                        $result['status'] = true;
                        $result['message'] = get_notification('insert', 1);
                    }
                }
            }
        }

        echo json_encode($result);
    }

    public function edit() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    $id = $this->uri->segment(4);
                    $data['detail'] = $this->m_employee->get_detail($id);

                    // set data
                    $data['menu_id'] = $this->menu_id;

                    // get link from tbl_menu 
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $this->load->view('v_header');
                    $this->load->view('others/employee/v_edit_employee', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function update() {
        try {
            $txt_employeeno = trim($this->input->post('txt_employeeno'));
            $txt_employeename = trim($this->input->post('txt_employeename'));
            $cmb_departement = $this->input->post('cmb_departement');
            $cmb_jobtitle = $this->input->post('cmb_jobtitle');
            $txt_address = $this->input->post('txt_address');
            $cmb_city = $this->input->post('cmb_city');
            $cmb_state = $this->input->post('cmb_state');
            $cmb_country = $this->input->post('cmb_country');
            $txt_hire_date = $this->input->post('txt_hire_date');
            $txt_resign_date = $this->input->post('txt_resign_date');

            $hired_date = empty($txt_hire_date) ? null : date("Y-m-d", strtotime($txt_hire_date));
            $resign_date = empty($txt_resign_date) ? null : date("Y-m-d", strtotime($txt_resign_date));
            $dataSend = [];
            $dataSend['data_employee'] = [];
            $dataSend['idcode'] = $txt_employeeno;

            if (!regex_name($txt_employeename)) {
                throw new Exception(msg_invalid_name($this->name));
            } else {
                if ($txt_resign_date == '') {
                    $trans_status = 1;
                } else {
                    $trans_status = 3;
                }

                $dataSend['data_employee'] = array(
                    'EmployeeName' => strtoupper($txt_employeename),
                    'BranchCode' => $this->session->userdata('branch'),
                    'DepartmentCode' => $cmb_departement,
                    'JobTitleCode' => $cmb_jobtitle,
                    'EmployeeAddress' => $txt_address,
                    'EmployeeCity' => $cmb_city,
                    'EmployeeState' => $cmb_state,
                    'EmployeeCountry' => $cmb_country,
                    'HireDate' => $hired_date,
                    'ResignDate' => $resign_date,
                    'TransStatus' => $trans_status,
                    'LastUser' => $this->session->userdata("username")
                );

                //update database
//                $result_edit = $this->m_employee->update($data, $txt_employeeno);

                $rstDataSend = $this->m_employee->datasend_employee_update($dataSend);
                if ($rstDataSend) {
                    $result['status'] = true;
                    $result['message'] = get_notification('insert', 1);
                } else {
                    $result['status'] = false;
                    $result['message'] = get_notification('insert', 0);
                }
                echo json_encode($result);
            }
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function update_LAMA() {
        $txt_employeeno = trim($this->input->post('txt_employeeno'));
        $txt_employeename = trim($this->input->post('txt_employeename'));
        $cmb_departement = $this->input->post('cmb_departement');
        $cmb_jobtitle = $this->input->post('cmb_jobtitle');
        $txt_address = $this->input->post('txt_address');
        $cmb_city = $this->input->post('cmb_city');
        $cmb_state = $this->input->post('cmb_state');
        $cmb_country = $this->input->post('cmb_country');
        $txt_hire_date = $this->input->post('txt_hire_date');
        $txt_resign_date = $this->input->post('txt_resign_date');

        $hired_date = empty($txt_hire_date) ? null : date("Y-m-d", strtotime($txt_hire_date));
        $resign_date = empty($txt_resign_date) ? null : date("Y-m-d", strtotime($txt_resign_date));

        if (!regex_name($txt_employeename)) {
            $result['status'] = false;
            $result['message'] = msg_invalid_name($this->name);
        } else {
            if ($txt_resign_date == '') {
                $trans_status = 1;
            } else {
                $trans_status = 3;
            }

            $data = array(
                'EmployeeName' => strtoupper($txt_employeename),
                'BranchCode' => $this->session->userdata('branch'),
                'DepartmentCode' => $cmb_departement,
                'JobTitleCode' => $cmb_jobtitle,
                'EmployeeAddress' => $txt_address,
                'EmployeeCity' => $cmb_city,
                'EmployeeState' => $cmb_state,
                'EmployeeCountry' => $cmb_country,
                'HireDate' => $hired_date,
                'ResignDate' => $resign_date,
                'TransStatus' => $trans_status,
                'LastUser' => $this->session->userdata("username")
            );

            //update database
            $this->db->trans_begin();
            $result_edit = $this->m_employee->update($data, $txt_employeeno);

            if ($result_edit == 0) {
                $this->db->trans_rollback();
                $result['status'] = false;
                $result['message'] = get_notification('update', 0);
            } else {
                $this->db->trans_commit();
                $result['status'] = true;
                $result['message'] = get_notification('update', 1);
            }
        }

        echo json_encode($result);
    }

    public function delete() {
        try {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu);
            $data['available_menu'] = array_unique($arr_group_id);
            if (!in_array($this->menu_id, $data['available_menu'])) {
                redirect(base_url() . 'error', 'refresh');
            }
            $id = $this->input->post('id');
            $dataSend = [];
            $dataSend['idcode'] = $id;
//            $result_delete = $this->m_employee->suspended($id);

            $rstDataSend = $this->m_employee->datasend_employee_delete($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification('delete', 1);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('delete', 0);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function delete_LAMA() {
        $group_menu = $this->session->userdata('group_menu');
        $arr_group_id = $this->m_menu->get_menu_by_group($group_menu);

        $data['available_menu'] = array_unique($arr_group_id);

        if (!in_array($this->menu_id, $data['available_menu'])) {
            redirect(base_url() . 'error', 'refresh');
        }

        $id = $this->input->post('id');

        $this->db->trans_begin();
        $result_delete = $this->m_employee->suspended($id);

        if ($result_delete == 1) {
            $result['status'] = true;
            $result['message'] = get_notification('delete', 0) . "= bener iki";
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('delete', 1);
        }

        echo json_encode($result);
    }

    public function suspend_data() {//sebelum diedit dhidhik,29Maret2016, ni function memang ga ada,jd dibikinkan karena di tampilan error 404(function ga ada) 
        try {
            $id = $this->input->post('id');
            $dataSend = [];
            $dataSend['idcode'] = $id;
            //        $result_delete = $this->m_employee->suspended($id);

            $rstDataSend = $this->m_employee->datasend_employee_suspend($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification('delete', 1);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('delete', 0);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function to_preview($obj_string = null) {
        $data['menu_id'] = $this->menu_id;
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

//        $data['list']       = $this->m_employee->join_all();

        $data['menu_id'] = $this->menu_id;
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

        $data_filter = arrayParamInUrlToStr($obj_string);
        $data['company_code'] = $data_filter['cmb_company'];
        $data['branch_code'] = $data_filter['cmb_branch'];
        $data['list'] = $this->m_employee->get_all_to_print($data_filter);

        $this->load->view('v_header');
        $this->load->view('others/employee/v_preview_employee', $data);
        $this->load->view('v_footer');
    }

    public function to_print() {
        $data['menu_id'] = $this->menu_id;
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $data['list'] = $this->m_employee->join_all();

        $this->load->view('v_header');
        $this->load->view('others/employee/v_print_employee', $data);
        $this->load->view('v_footer');
    }

    public function ajax() {
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $hasil = array();
        /* ===========rows*page tidak boleh melebihi dari jumlah data======= */

        /* ===========================declar post by find================================================ */
        $Code = $this->input->post('EmployeeCode') ? $this->input->post('EmployeeCode') : '';
        $Name = $this->input->post('EmployeeName') ? $this->input->post('EmployeeName') : '';

        $TransStatus = $this->input->post('TransStatus') ? $this->input->post('TransStatus') : '';
        $BranchCode = $this->input->post('BranchCode') ? $this->input->post('BranchCode') : '';
        /* ========================================end================================================== */
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if============ */
        if ($BranchCode != "") {
            $this->db->where('BranchCode', $BranchCode);
        } else {
            $this->db->where('BranchCode', $this->session->userdata('branch'));
        }

        if ($Code != "") {
            $this->db->like('EmployeeCode', $Code);
        }
        if ($Name != "") {
            $this->db->like('EmployeeName', $Name);
        }

        if ($TransStatus != '') {
            $this->db->where_in('TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('TransStatus', array(0, 1));
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('am_employee');

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_employee->join_all();

        for ($i = 0; $i <= ($rows - 1); $i++) {
            $TransStatus = get_status_master($result[$i]->TransStatus);

            $hasil[] = array(
                'CompanyName' => $result[$i]->CompanyName,
                'BranchName' => $result[$i]->BranchName,
                'TransNumber' => $result[$i]->EmployeeCode,
                'EmployeeName' => $result[$i]->EmployeeName,
                'DepartmentName' => $result[$i]->DepartmentName,
                'JobTitleName' => $result[$i]->JobTitleName,
                'Status' => $TransStatus
            );
        }

        if ($hasil == "") {
            $result = array();
            echo json_encode($result);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            echo json_encode($result);
        }
    }

}
