<?php

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

/* 	
 * 	Author 	: Ladur
 * 	Tanggal : 18-11-2014
 * 	Revisi 	: Dhidhik, 23 Maret 2016, array in model system
 */

class Fixed_asset_list extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 182;
    public $code = "Item Code";
    public $name = "Item Name";

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

        $this->load->model('m_menu');
        $this->load->model('m_fixed_asset_list');
        $this->load->model('m_fixed_asset_type');
        $this->load->model('custom/m_custom');
        $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();
            }
        }
    }

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

                    $data['list_branch'] = $this->m_custom->get_branch();

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

    //Function preview data
    public function to_preview($obj_string = null) {
        // set data
        $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);
//		
//		if($this->m_branchinfo->get_branch_status_by_code($this->session->userdata('branch')) == 0) {
//			$data['list'] = $this->m_fixed_asset_list->join_all();
//		}
//		else {
//			$data['list'] = $this->m_fixed_asset_list->join_all_by_branch($this->session->userdata('branch'));
//		}

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

        $this->load->view('v_header');
        $this->load->view('fixed_asset_list/v_preview_fixed_asset_list', $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);

        if ($this->m_branchinfo->get_branch_status_by_code($this->session->userdata('branch')) == 0) {
            $data['list'] = $this->m_fixed_asset_list->join_all();
        } else {
            $data['list'] = $this->m_fixed_asset_list->join_all_by_branch($this->session->userdata('branch'));
        }

        $this->load->view('v_header');
        $this->load->view('fixed_asset_list/v_print_fixed_asset_list', $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('AssetCode') ? $this->input->post('AssetCode') : '';
        $Desc = $this->input->post('ItemDesc') ? $this->input->post('ItemDesc') : '';

        $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('at_inventdetail.BranchCode', $BranchCode);
        } else {
            $this->db->where('at_inventdetail.BranchCode', $this->session->userdata('branch'));
        }

        if ($Code != "") {
            $this->db->like('at_inventdetail.AssetCode', $Code);
        }
        if ($Desc != "") {
            
            $this->db->like('am_item.ItemDesc', $Desc);
        }
		
		$this->db->where('am_item.TransStatus', 1);
		
		$this->db->join('am_item', 'am_item.ItemCode = at_inventdetail.ItemCode', 'inner');
		$this->db->join('am_itemcategory', 'am_itemcategory.ItemCategoryID = am_item.ItemCategoryID', 'inner');
		$this->db->join('am_branch', 'am_branch.BranchCode = at_inventdetail.BranchCode', 'inner');
        $this->db->join("am_fixedassettype", "am_fixedassettype.FixedAssetType = am_itemcategory.ItemCategoryName", "inner");
		
        $count_data = $this->db->count_all_results('at_inventdetail');

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_fixed_asset_list->join_all();
		
		for ($i = 0; $i <= ($rows - 1); $i++) {
//				$asset = $this->m_fixed_asset_type->get_by_name($result[$i]->ItemCategoryName);
//				$dep_meth = "";	$est_life = "";	$dep_rate = "";
//				foreach($asset as $rw) {
//					$dep_meth = get_depreciate_method($rw->DepMethodID);
//					$est_life = get_depreciate_method($rw->EstimatedLife);
//					$dep_rate = get_depreciate_method($rw->DepriciateRate);
//				}

			$hasil[] = array(
				'AssetCode' => $result[$i]->AssetCode,
				'BranchCode' => $result[$i]->BranchCode,
				'BranchName' => $result[$i]->BranchName,
				'ItemCode' => $result[$i]->ItemCode,
				'ItemQty' => $result[$i]->ItemQty,
				'ItemDesc' => $result[$i]->ItemDesc,
				'ItemUnit' => $result[$i]->ItemUnit,
				'ItemAverage' => $result[$i]->ItemAverage,
				//'ItemTypeName' => $row->ItemTypeName,
				'ItemCategoryID' => $result[$i]->ItemCategoryID,
				'ItemCategoryName' => $result[$i]->ItemCategoryName,
//                    'IventDetailID' => $result[$i]->IventDetailID,
				'TransNumber' => $result[$i]->IventDetailID,
				'EstimatedLife' => $result[$i]->EstimatedLife,
				'DepriciateRate' => $result[$i]->DepriciateRate,
				'depreciate_method' => get_depreciate_method($result[$i]->DepMethodID)
			);
		}
			
        if ($hasil == "") {
            $result = array();
            echo json_encode($result);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            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');

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


                    $sess_compay = $this->session->userdata('company');
                    $sess_branch = $this->session->userdata('branch');

                    $inven_detail_id = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());

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

                    $data['detail'] = $this->m_fixed_asset_list->get_edit_asset_list($inven_detail_id, $sess_branch);

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

    public function update() {
        try {
            $asset_code = $this->input->post('txt_asset_code');
            $txt_usage_date = $this->input->post('txt_usage_date');
            $txa_notes = $this->input->post('txa_notes');
            $txt_book_val = $this->input->post('txt_book_val');
            $cmb_department = $this->input->post('cmb_department');
            $dataSend = [];
            $dataSend['data_fixedassetlist_update'] = [];
            $dataSend['idcode'] = $asset_code;

            $dataSend['data_fixedassetlist_update'] = array(
                'Description' => $txa_notes,
                'UsageDate' => date("Y-m-d", strtotime($txt_usage_date)),
                'AmountBookValues' => $txt_book_val
            );

//            $result_edit = $this->m_fixed_asset_list->update($data_edit, $asset_code);

            $rstDataSend = $this->m_fixed_asset_list->datasend_fixedassetlist_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() {
        $asset_code = $this->input->post('txt_asset_code');
        $txt_usage_date = $this->input->post('txt_usage_date');
        $txa_notes = $this->input->post('txa_notes');
        $txt_book_val = $this->input->post('txt_book_val');
        $cmb_department = $this->input->post('cmb_department');

        $data_edit = array(
            'Description' => $txa_notes,
            'UsageDate' => date("Y-m-d", strtotime($txt_usage_date)),
            'AmountBookValues' => $txt_book_val
        );

        $result_edit = $this->m_fixed_asset_list->update($data_edit, $asset_code);
        if ($result_edit == 0) {
            $this->trans_rollback('update');
        }

        if ($result_edit == 0) {
            $this->db->trans_rollback();
            $result['status'] = true;
            $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 get_asset_type() {
        $result = $this->m_fixed_asset_list->cmb_aset_type();
        echo json_encode($result);
    }

    public function get_categori() {
        $result = $this->m_fixed_asset_list->cmb_categori();
        echo json_encode($result);
    }

}
