<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Tagor / 04-08-2014	
 * 	Revisi 	: Ferry / 06-01-2015
 */

class Departement extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 95;
    public $menu_model = 'm_department';

    public function __construct() {
        parent::__construct();
        $this->load->model('m_department');
        $this->load->helper('regex');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
		$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();
            }
        }
    }

    //Function Index
    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 {
                    $group_menu = $this->session->userdata('group_menu');

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

                    // get link from tbl_menu 
                    $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('department/v_department', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    //Functiom Add Form
    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)
                     */
                    $group_menu = $this->session->userdata('group_menu');

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

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

                    //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('department/v_add_department', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function ajax_list_department() {
        $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('DepartmentCode')) ? $this->input->post('DepartmentCode') : '';
        $Name = ($this->input->post('DepartmentName')) ? $this->input->post('DepartmentName') : '';

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

        if ($Code != "") {
            $this->db->like('DepartmentCode', $Code);
        }
        if ($Name != "") {
            $this->db->like('DepartmentName', $Name);
        }
        if ($TransStatus != '') {
            $this->db->where_in('TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6 utk transaksi. => Finished dan Need Approval
              default adalah 0,1 utk transaksi. => Active
             */
            $this->db->where_in('TransStatus', array(0, 1));
        }

        /* ==========================end================================================================= */

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

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

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

            $hasil[] = array(
                'TransNumber' => $result[$i]->DepartmentCode,
                'DepartmentName' => $result[$i]->DepartmentName,
                'DepartmentDesc' => $result[$i]->DepartmentDesc,
                'TransStatus' => $TransStatus
            );
        }

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

    //Function Insert Data
    public function insert() {
        try {
            $result_edit = 0;
            $CompanyCode = $this->session->userdata('company');
            $BranchCode = $this->session->userdata('branch');

            $txt_deptartement_code = $this->input->post('txt_deptartement_code');
            $txt_deptartement_name = strtoupper($this->input->post('txt_deptartement_name'));
            $txt_deptartement_description = $this->input->post('txt_deptartement_description');
            $dataSend = [];
            $dataSend['data_departement_insert'] = [];
            $dataSend['data_departement_insert'] = array(
                'CompanyCode' => $CompanyCode,
                'DepartmentCode' => $txt_deptartement_code,
                'DepartmentName' => $txt_deptartement_name,
                'DepartmentDesc' => $txt_deptartement_description,
                'TransStatus' => 1,
                'LastUser' => $this->session->userdata("username")
            );

//            $result_insert = $this->m_department->insert($data);
            $rstDataSend = $this->m_department->data_send_departement_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() {
        $result_edit = 0;
        $CompanyCode = $this->session->userdata('company');
        $BranchCode = $this->session->userdata('branch');

        $txt_deptartement_code = $this->input->post('txt_deptartement_code');
        $txt_deptartement_name = strtoupper($this->input->post('txt_deptartement_name'));
        $txt_deptartement_description = $this->input->post('txt_deptartement_description');
//        $company_code = $this->session->userdata('company');


        $data = array(
            'CompanyCode' => $CompanyCode,
            'DepartmentCode' => $txt_deptartement_code,
            'DepartmentName' => $txt_deptartement_name,
            'DepartmentDesc' => $txt_deptartement_description,
            'TransStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        $this->db->trans_begin();
        $result_insert = $this->m_department->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);
    }

    //Function Form Edit
    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)
                     */
                    $group_menu = $this->session->userdata('group_menu');
                    // inisialisasi additional parameter
                    $id = $this->uri->segment(4);
                    // set data
                    $data['detail'] = $this->m_department->get_by_id($id);

                    // get form title from tbl_menu 
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    // get link from tbl_menu 
                    $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);

                    // set for view
                    $this->load->view('v_header');
                    $this->load->view('department/v_edit_department', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    //Function Update Data

    public function update() {
        try {
            $dept_code = $this->input->post('txt_deptartement_code');
            $dept_name = $this->input->post('txt_deptartement_name');
            $dept_desc = $this->input->post('txt_deptartement_description');
            $dataSend = [];
            $dataSend['data_dept_update'] = [];
            $dataSend['idcode'] = $dept_code;

            $dataSend['data_dept_update'] = array(
                'DepartmentName' => $dept_name,
                'DepartmentDesc' => $dept_desc,
                'TransStatus' => 1,
                'LastUser' => $this->session->userdata("username")
            );
            //        $result_edit = $this->m_department->update($dept_code, $data);
            $rstDataSend = $this->m_department->data_send_departement_update($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification('update', 1);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('update', 0);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function update_LAMA() {
        $dept_code = $this->input->post('txt_deptartement_code');
        $dept_name = $this->input->post('txt_deptartement_name');
        $dept_desc = $this->input->post('txt_deptartement_description');

        $data = array(
            'DepartmentName' => $dept_name,
            'DepartmentDesc' => $dept_desc,
            'TransStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        $this->db->trans_begin();
        $result_edit = $this->m_department->update($dept_code, $data);

        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);
    }

    // Function Delete
    public function suspend_data() {
        try {
            // inisialisasi additional parameter
            $id = $this->input->post('id');
            $dataSend = [];
            $dataSend['idcode'] = $id;
            $dataSend['data_dept_suspend'] = [];
            $dataSend['data_dept_suspend'] = array(
                'TransStatus' => 3,
                'LastUser' => $this->session->userdata("username")
            );
//            $this->m_department->update($id, $data);

            $rstDataSend = $this->m_department->data_send_departement_suspend($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = 'Depertemen berhasil disuspend';
            } else {
                $result['status'] = false;
                $result['message'] = 'Depertemen gagal disuspend';
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function suspend_data_LAMA() {
        // inisialisasi additional parameter
        $id = $this->input->post('id');

        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata("username")
        );

        if ($this->m_department->update($id, $data)) {
            echo json_encode(array('status' => true, 'message' => 'Depertemen berhasil disuspend'));
        } else {
            echo json_encode(array('status' => false));
        }
    }

    //Function preview data
    public function to_preview($obj_string=null) {
        //$CompanyCode    = $this->session->userdata('company');
//        $data['list'] = $this->m_department->get_all_data($CompanyCode);

        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $data['list']           = $this->m_department->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('department/v_preview_department', $data);
        $this->load->view('v_footer');
    }

    public function to_preview_LAMA() {
        //$CompanyCode    = $this->session->userdata('company');
        $CompanyCode = $this->uri->segment(4);
        $BranchCode = $this->uri->segment(5);
        // set data
        $data['company_code'] = $CompanyCode;
        $data['branch_code'] = $BranchCode;

        $data['list'] = $this->m_department->get_all_data($CompanyCode);

        $this->load->view('v_header');
        $this->load->view('department/v_preview_department', $data);
        $this->load->view('v_footer');
    }

    //Function To Print
    public function to_print() {
        $CompanyCode = $this->session->userdata('company');

        // set data
        $data['list'] = $this->m_department->get_all_data($CompanyCode);

        $this->load->view('v_header');
        $this->load->view('department/v_print_department', $data);
        $this->load->view('v_footer');
    }

    //Function Form Import
    public function to_import() {
        // set for view
        $this->load->view('v_header');
        $this->load->view('department/v_form_import');
        $this->load->view('v_footer');
    }

}
