<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Wahyu
 * 	Tanggal : 02-09-2014	
 * 	Revisi 	: Dhidhik, 29 maret 2016
 */

class Shipments extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 185;

    public function __construct() {
        parent::__construct();
        $this->load->model('m_menu');
        $this->load->model('m_shipment');
        $this->load->helper('message_helper');
        $this->load->helper('custom_string_helper');
        $this->load->helper('status');
		$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 {
                    //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/shipment/v_shipment', $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)
                     */
                    //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/shipment/v_new_shipment', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    // Function Insert
    public function insert() {
        try {
            $txt_name = $this->input->post('txt_name');
            $txt_desc = $this->input->post('txt_desc');
//            $chk_suspend 	= $this->input->post('chk_suspend');//ga dipakai saat insert new
            $dataSend = [];
            $dataSend['data_shipment'] = [];

            // cek apakah kode sudah digunakan
            if ($this->m_shipment->check_code_exist($txt_name) == TRUE) {
                // set nilai untuk ke form
                throw new Exception('Shipment Name telah digunakan');
            } else {
                // inisialisasi array
                $dataSend['data_shipment'] = array(
                    'ShipmentName' => $txt_name,
                    'ShipmentDesc' => $txt_desc,
                    'TransStatus' => 1,
                    'LastUser' => $this->session->userdata("username")
                );

                // insert database
//                $hasil = $this->m_shipment->insert($data);                
                $rstDataSend = $this->m_shipment->datasend_shipment_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_name = $this->input->post('txt_name');
        $txt_desc = $this->input->post('txt_desc');
        $chk_suspend = $this->input->post('chk_suspend');

        // cek apakah kode sudah digunakan
        if ($this->m_shipment->check_code_exist($txt_name) == TRUE) {
            // set nilai untuk ke form
            $result['status'] = false;
            $result['message'] = 'Shipment Name telah digunakan';
        } else {
            // inisialisasi array
            $data = array(
                'ShipmentName' => $txt_name,
                'ShipmentDesc' => $txt_desc,
                'TransStatus' => ($chk_suspend == 3) ? $chk_suspend : 0,
                'LastUser' => $this->session->userdata("username")
            );

            // insert database
            $hasil = $this->m_shipment->insert($data);
            if ($hasil == 0) {
                $result['status'] = true;
                $result['message'] = get_notification('insert', $hasil);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('insert', $hasil);
            }
        }
        echo json_encode($result);
    }

    // Function 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)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');
                    // inisialisasi additional parameter
                    $id = $this->uri->segment(4);
                    $data['detail'] = $this->m_shipment->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/shipment/v_edit_shipment', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    // Function Update
    public function update() {
        try {
            $id = $this->input->post('id');
            $txt_name = $this->input->post('txt_name');
            $txt_desc = $this->input->post('txt_desc');
            $chk_suspend = $this->input->post('chk_suspended');
            $dataSend = [];
            $dataSend['data_shipment'] = [];
            $dataSend['idcode'] = $id;

            // inisialisasi array
            $dataSend['data_shipment'] = array(
                'ShipmentName' => $txt_name,
                'ShipmentDesc' => $txt_desc,
                'TransStatus' => ($chk_suspend == 3) ? $chk_suspend : 1,
                'LastUser' => $this->session->userdata("username")
            );

            // update database
//            $hasil = $this->m_shipment->update($data, $id);
            $rstDataSend = $this->m_shipment->datasend_shipment_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() {
        $id = $this->input->post('id');
        $txt_name = $this->input->post('txt_name');
        $txt_desc = $this->input->post('txt_desc');
        $chk_suspend = $this->input->post('chk_suspend');

        // inisialisasi array
        $data = array(
            'ShipmentName' => $txt_name,
            'ShipmentDesc' => $txt_desc,
            'TransStatus' => ($chk_suspend == 3) ? $chk_suspend : 0,
            'LastUser' => $this->session->userdata("username")
        );

        // update database
        $hasil = $this->m_shipment->update($data, $id);
        if ($hasil == 0) {
            $result['status'] = true;
            $result['message'] = get_notification('update', $hasil);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('update', $hasil);
        }
        echo json_encode($result);
    }

    // Function Delete
    public function delete() {
        try {
            // inisialisasi additional parameter
            $id = $this->input->post('id');
            $dataSend = [];
            $dataSend['data_shipment'] = [];
            $dataSend['idcode'] = $id;

            $dataSend['data_shipment'] = array(
                'TransStatus' => 3,
                'LastUser' => $this->session->userdata('username')
            );
//            $hasil = $this->m_shipment->suspend($dsata, $id);
            $rstDataSend = $this->m_shipment->datasend_shipment_suspend($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification('suspend', 1);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('suspend', 0);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

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

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

        $hasil = $this->m_shipment->suspend($data, $id);
        if ($hasil == 0) {
            $result['status'] = true;
            $result['message'] = get_notification('suspend', $hasil);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend', $hasil);
        }
        echo json_encode($result);
    }

    public function suspend_data() {
        try {
            // inisialisasi additional parameter
            $id = $this->input->post('id');
            $dataSend = [];
            $dataSend['data_shipment'] = [];
            $dataSend['idcode'] = $id;

            $dataSend['data_shipment'] = array(
                'TransStatus' => 3,
                'LastUser' => $this->session->userdata('username')
            );
//            $hasil = $this->m_shipment->suspend($dsata, $id);
            $rstDataSend = $this->m_shipment->datasend_shipment_suspend($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification('suspend', 1);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('suspend', 0);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    //Function preview data
    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_shipment->get_all();
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $data['list']           = $this->m_shipment->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('others/shipment/v_preview_shipment', $data);
        $this->load->view('v_footer');
    }

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

        $data['list'] = $this->m_shipment->get_all();

        $this->load->view('v_header');
        $this->load->view('others/shipment/v_print_shipment', $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('ShipmentName') ? $this->input->post('ShipmentName') : '';
        $Name = $this->input->post('ShipmentDesc') ? $this->input->post('ShipmentDesc') : '';

        $TransStatus = $this->input->post('TransStatus') ? $this->input->post('TransStatus') : '';
        /* ========================================end================================================== */

        if ($Code != "") {
            $this->db->like('ShipmentName', $Code);
        }
        if ($Name != "") {
            $this->db->like('ShipmentDesc', $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_shipment');

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_shipment->get_all();
        for ($i = 0; $i <= ($rows - 1); $i++) {
            $TransStatus = get_status_master($result[$i]->TransStatus);

            $hasil[] = array(
                'TransNumber' => $result[$i]->ShipmentID,
                'ShipmentName' => $result[$i]->ShipmentName,
                'ShipmentDesc' => $result[$i]->ShipmentDesc
            );
        }

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

    /* public function ajax(){
      //echo json_encode($this->m_shipment->get_all());
      $result = $this->m_shipment->get_all();

      foreach($result as $row){
      $TransStatus = get_status_master($row->TransStatus);

      $hasil[] = array(
      'ShipmentID' 		=>	$row->ShipmentID,
      'ShipmentName' 		=>	$row->ShipmentName,
      'ShipmentDesc' 		=>	$row->ShipmentDesc,
      'TransStatus' 		=>	$TransStatus
      );
      }
      if(!empty($hasil)){
      echo json_encode($hasil);
      }
      else{
      $emptyVar = array();
      echo json_encode($emptyVar);
      }
      } */
}
