<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Fachri
 * 	Tanggal : 06-10-2014	
 * 	Revisi 	: DHIDHIK, 23 MARET 2016
 */

class Fixed_asset_dispose extends CI_Controller {

    public $menu_id = 380;
    public $menu_model = 'm_fixed_asset_dispose';
    public $name = "Fixed Asset Dispose";

    public function __construct() {
        parent::__construct();
        $this->load->model('m_fixed_asset_dispose');
        $this->load->model('m_account_journal');
        $this->load->helper('message_helper');
        $this->load->helper('convert_date_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();
            }
        }
    }

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

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

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

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

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

    //Function Menampilkan Data Pada Data Grid View
    //function get data to grid
    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======= */

        /* =================================post dari find di kiri==================================================== */
        $param = $this->input->post('param');
        $Number = isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : '';
        $Desc = isset($param['txt_Description']) ? $param['txt_Description'] : '';

        $DateFrom = isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
        $DateTo = isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
        $TransStatus = isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
        $BranchCode = isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
        /* ============================================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 ($Number != "") {
            $this->db->like('FDNumber', $Number);
        } //change
        if ($Desc != "") {
            $this->db->like('FDDesc', $Desc);
        } //change
        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, 4, 5, 6, 7, 8));
        }


        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('at_fixed_asset_dispose.FDDate >=', date("Y-m-d", strtotime($DateFrom))); //change
                $this->db->where('at_fixed_asset_dispose.FDDate <=', date("Y-m-d", strtotime($DateTo))); //change
            }
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_fixed_asset_dispose'); //change
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_fixed_asset_dispose->get_all(); //change

        for ($i = 0; $i <= ($rows - 1); $i++) {
            // kalau master ambil dari get_status_master(), kalau transaksi get_status()
            $TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(
                'TransNumber' => $result[$i]->FDNumber,
                'FDDate' => $result[$i]->FDDate,
                'FDDesc' => $result[$i]->FDDesc,
                'TotalAmount' => $result[$i]->TotalAmount,
                'TransStatus' => $TransStatus,
                'CreatedBy' => $result[$i]->CreatedBy
            );
        }

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

    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');
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $sess_brach = $this->session->userdata('branch');

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
                    $data['date_now'] = date('d-m-Y');
                    //$data['pay_number']  			= $this->m_payment->create_pay_number(date('d-m-Y'));
                    $this->load->view('v_header');
                    $this->load->view('fixed_asset_dispose/v_add_fixed_asset_dispose', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    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_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');

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

                    $data['detail'] = $this->m_fixed_asset_dispose->get_edit_fixed_asset_dispose($fd_number, $sess_branch);

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

    public function insert() {
        try {
            $branch = $this->session->userdata('branch');
            $user = $this->session->userdata('username');
            $detail = $this->input->post('detail');
            $detail = json_decode($detail);
            $txt_date = date('Y-m-d', strtotime($this->input->post('txt_date')));

            $FDNumber = $this->m_fixed_asset_dispose->create_fd_number($txt_date); //create FDNumber
            $acc_gl = $this->input->post('cmb_gl');
            $desc = $this->input->post('txa_description');
            $TotalAmount = $this->input->post('TotalAmount');

            $dataSend = [];
            $dataSend['data_group'] = [];
            $dataSend['data_detail'] = [];
            $dataSend['data_journal'] = [];
            $dataSend['data_invdetail'] = [];

            //================== function insert group ========================//
            $dataSend['data_group'] = $this->insert_group($branch, $FDNumber, $txt_date, $acc_gl, $desc, $TotalAmount, $user); //single array
            //================== End function insert group ===================//
            //================== function insert detail ======================//
            $dataSend['data_detail'] = $this->insert_detail($detail, $FDNumber, $user); //multiarray
            //================== End function insert detail ==================//
            //================== function insert journal =====================//
            $dataSend['data_journal'] = $this->insert_journal($branch, $detail, $FDNumber, $txt_date, $desc, $acc_gl, $user, false); //multiarray
            //================== End function insert journal =================//
            //================== update inv detail ===========================//
            $dataSend['data_invdetail'] = $this->update_inv_detail($branch, $detail); //multiarray
            //================== End update inv detail =======================//

            $rstDataSend = $this->m_fixed_asset_dispose->datasend_fixedassetdispose_insert($dataSend);
//            $rstDataSend = TRUE;
            $result['dataSend'] = $dataSend;
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $FDNumber);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $FDNumber);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function insert_LAMA() {

        $branch = $this->session->userdata('branch');
        $user = $this->session->userdata('username');
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $txt_date = date('Y-m-d', strtotime($this->input->post('txt_date')));

        /* ====================== create FDNumber ============================== */
        $FDNumber = $this->m_fixed_asset_dispose->create_fd_number($txt_date);

        $acc_gl = $this->input->post('cmb_gl');
        $desc = $this->input->post('txa_description');
        $TotalAmount = $this->input->post('TotalAmount');

        /* ============================ begin transaction =============================== */
        $this->db->trans_begin();

        /* ==================function insert group================================================ */
        $this->insert_group($branch, $FDNumber, $txt_date, $acc_gl, $desc, $TotalAmount, $user);

        /* ==================function insert detail================================================ */
        $this->insert_detail($detail, $FDNumber, $user);

        /* ==================function insert journal ================================================ */
        $this->insert_journal($branch, $detail, $FDNumber, $txt_date, $desc, $acc_gl, $user);

        /* ===================== update inv detail ========================================== */
        $this->update_inv_detail($branch, $detail);

        /* =============================trans roll back dan trans commit============================/ */
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $FDNumber);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $FDNumber);
        }

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


        echo json_encode($result);
    }

    //============== insert group ============================================//
    function insert_group($branch, $FDNumber, $txt_date, $acc_gl, $desc, $TotalAmount, $user) {
        $data_group = array(
            'BranchCode' => $branch,
            'FDNumber' => $FDNumber,
            'FDDate' => $txt_date,
            'FDDesc' => $desc,
            'GLAccount' => $acc_gl,
            'TotalAmount' => $TotalAmount,
            'TransStatus' => 5,
            'CreatedBy' => $user,
            'CreatedAt' => date('Y-m-d H:i:s'),
            'LastUser' => $user
        );
        return $data_group;
        //$this->m_fixed_asset_dispose->insert_group($data_group);
    }

    //============== End insert group ========================================//

    function update_group($branch, $FDNumber, $txt_date, $acc_gl, $desc, $TotalAmount, $user) {
        $data_group[] = array(
            'BranchCode' => $branch,
            'FDDate' => $txt_date,
            'FDDesc' => $desc,
            'GLAccount' => $acc_gl,
            'TotalAmount' => $TotalAmount,
            'TransStatus' => 5,
            'CreatedBy' => $user,
            'CreatedAt' => date('Y-m-d'),
            'LastUser' => $user,
            'FDNumber' => $FDNumber //untuk parameter update di model
        );
        //$this->m_fixed_asset_dispose->update_group($data_group,$FDNumber);
        return $data_group;
    }

    function update_group_LAMA($branch, $FDNumber, $txt_date, $acc_gl, $desc, $TotalAmount, $user) {

        $data_group = array(
            'BranchCode' => $branch,
            'FDDate' => $txt_date,
            'FDDesc' => $desc,
            'GLAccount' => $acc_gl,
            'TotalAmount' => $TotalAmount,
            'TransStatus' => 5,
            'CreatedBy' => $user,
            'CreatedAt' => date('Y-m-d'),
            'LastUser' => $user
        );

        $this->m_fixed_asset_dispose->update_group($data_group, $FDNumber);
    }

    //============== insert detail ===========================================//
    function insert_detail($detail, $FDNumber, $user) {
        $dataRst = [];
        foreach ($detail as $row) {
            $ItemCode = $row->ItemCode;
            $Amount = $row->AccumAmount === null ? 0 : $row->AccumAmount;
            $ReceiptNumber = $row->ReceiptNumber;
            $FixedAssetType = $row->FixedAssetType;
            $AssetCode = $row->AssetCode;
            $ItemAverage = $row->ItemAverage;
            $dataRst[] = array(
                'FDNumber' => $FDNumber,
                'ReceiptNumber' => $ReceiptNumber,
                'FixedAssetType' => $FixedAssetType,
                'AssetCode' => $AssetCode,
                'ItemCode' => $ItemCode,
                'FDAmount' => $Amount,
                'ItemAverage' => $ItemAverage,
                'LastUser' => $user
            );
//                $this->m_fixed_asset_dispose->insert_detail($detail_data);
        }
        return $dataRst;
    }

    //============== End insert detail ========================================//

    /* function update_detail($detail, $FDNumber,$user){
      foreach($detail as $row){
      $ItemCode 				= $row->ItemCode;
      $Amount   	 			= $row->Amount;
      $ReceiptNumber    		= $row->ReceiptNumber;
      $FixedAssetType     	= $row->FixedAssetType;
      $AssetCode     			= $row->AssetCode;

      $detail_data=array(
      'ReceiptNumber' 	=> $ReceiptNumber,
      'FixedAssetType'	=> $FixedAssetType,
      'ItemCode'			=> $ItemCode,
      'FDAmount'			=> $Amount,
      'LastUser' 			=> $user
      );

      $this->m_fixed_asset_dispose->update_detail($detail_data,$FDNumber,$AssetCode);
      }
      } */

    function insert_journal($branch, $detail, $FDNumber, $txt_date, $desc, $acc_gl, $user, $status_approve) {
        $dataRst = [];
        $dataRst['journal_data_gl'] = [];
        $dataRst['journal_data_acc'] = [];
        $dataRst['journal_data_inv'] = [];

        foreach ($detail as $row) {
            $ItemCode = $row->ItemCode;
            $AccumAmount = $row->AccumAmount;
            $ReceiptNumber = $row->ReceiptNumber;
            $FixedAssetType = $row->FixedAssetType;
            $AssetCode = $row->AssetCode;
            $ItemAverage = $row->ItemAverage;
            $ItemCategoryID = $row->ItemCategoryID;

            $acc_fixed_asset = $this->m_fixed_asset_dispose->get_fixed_asset_account($FixedAssetType);
            $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $ItemCategoryID, 'IDR');

            $ItemAverageNew = $this->m_fixed_asset_dispose->get_item_average($AssetCode, $branch);
            $AccumAmountNew = $this->m_fixed_asset_dispose->get_total_amount_period($branch, $AssetCode,$acc_gl);

            $ItemAverage = $status_approve == true ? $ItemAverageNew : $ItemAverage;
            $AccumAmount = $status_approve == true ? $AccumAmountNew : $AccumAmount;

            if ($AccumAmount == 0) {

                /* ========================== revenue Credit selling journal ================================ */
                $dataRst['journal_data_gl'][] = array(
                    'FDDate' => $txt_date,
                    'FDNumber' => $FDNumber,
                    'AssetCode' => $AssetCode,
                    'FDAccountNumber' => $acc_gl,
                    'FDSaldoDebet' => $ItemAverage,
                    'FDSaldoCredit' => 0,
                    'AmountCurrency' => $ItemAverage,
                    'FDSignStatus' => 0,
                    'FDDesc' => $desc,
                    'LastUser' => $user
                );

                /* ========================== inventory journal ================================ */
                $dataRst['journal_data_inv'][] = array(
                    'FDDate' => $txt_date,
                    'FDNumber' => $FDNumber,
                    'AssetCode' => $AssetCode,
                    'FDAccountNumber' => $InventoryAccount->AccountNumber,
                    'FDSaldoDebet' => 0,
                    'FDSaldoCredit' => $ItemAverage,
                    'AmountCurrency' => $ItemAverage,
                    'FDSignStatus' => 1,
                    'FDDesc' => $desc,
                    'LastUser' => $user
                );
            } else if ($AccumAmount > 0 and $AccumAmount < $ItemAverage) {
                /* ========================= accumulation journal =========================== */

                /* ========================== deposit selling journal ================================ */
                $dataRst['journal_data_gl'][] = array(
                    'FDDate' => $txt_date,
                    'FDNumber' => $FDNumber,
                    'AssetCode' => $AssetCode,
                    'FDAccountNumber' => $acc_gl,
                    'FDSaldoDebet' => doubleval($ItemAverage) - doubleval($AccumAmount),
                    'FDSaldoCredit' => 0,
                    'AmountCurrency' => doubleval($ItemAverage) - doubleval($AccumAmount),
                    'FDSignStatus' => 0,
                    'FDDesc' => $desc,
                    'LastUser' => $user
                );

                $dataRst['journal_data_acc'][] = array(
                    'FDDate' => $txt_date,
                    'FDNumber' => $FDNumber,
                    'AssetCode' => $AssetCode,
                    'FDAccountNumber' => $acc_fixed_asset,
                    'FDSaldoDebet' => $AccumAmount,
                    'FDSaldoCredit' => 0,
                    'AmountCurrency' => $AccumAmount,
                    'FDSignStatus' => 1,
                    'FDDesc' => $desc,
                    'LastUser' => $user
                );

                /* ========================== inventory journal ================================ */
                $dataRst['journal_data_inv'][] = array(
                    'FDDate' => $txt_date,
                    'FDNumber' => $FDNumber,
                    'AssetCode' => $AssetCode,
                    'FDAccountNumber' => $InventoryAccount->AccountNumber,
                    'FDSaldoDebet' => 0,
                    'FDSaldoCredit' => doubleval($ItemAverage),
                    'AmountCurrency' => doubleval($ItemAverage),
                    'FDSignStatus' => 1,
                    'FDDesc' => $desc,
                    'LastUser' => $user
                );
            } else if (round(($AccumAmount - $ItemAverage), 4) == 0) {

                /* ========================= accumulation journal =========================== */
                $dataRst['journal_data_acc'][] = array(
                    'FDDate' => $txt_date,
                    'FDNumber' => $FDNumber,
                    'AssetCode' => $AssetCode,
                    'FDAccountNumber' => $acc_fixed_asset,
                    'FDSaldoDebet' => $AccumAmount,
                    'FDSaldoCredit' => 0,
                    'AmountCurrency' => $AccumAmount,
                    'FDSignStatus' => 1,
                    'FDDesc' => $desc,
                    'LastUser' => $user
                );

                /* ========================== inventory journal ================================ */
                $dataRst['journal_data_inv'][] = array(
                    'FDDate' => $txt_date,
                    'FDNumber' => $FDNumber,
                    'AssetCode' => $AssetCode,
                    'FDAccountNumber' => $InventoryAccount->AccountNumber,
                    'FDSaldoDebet' => 0,
                    'FDSaldoCredit' => $ItemAverage,
                    'AmountCurrency' => $ItemAverage,
                    'FDSignStatus' => 1,
                    'FDDesc' => $desc,
                    'LastUser' => $user
                );
            }
        }

        return $dataRst;
    }

    function update_inv_detail($branch, $detail) {
        $dataRst = [];
        $dataRst['Arrassetcode'] = [];
        $dataRst['data_invent'] = [];
        $dataRst['data_invent'] = array('SoldStatus' => 5);

        foreach ($detail as $row) {
//            array_push($Arrassetcode,$row->AssetCode);//
            $dataRst['Arrassetcode'][] = $row->AssetCode;
        }
//        $this->m_fixed_asset_dispose->update_soldstatus($Arrassetcode,$data_invent);
        return $dataRst;
    }

    public function update() {
        try {
            $branch = $this->session->userdata('branch');
            $user = $this->session->userdata('username');
            $detail = $this->input->post('detail');
            $detail = json_decode($detail);
            $detail_id = $this->input->post('detail_id');
            $detail_id = json_decode($detail_id);
            $txt_date = date('Y-m-d', strtotime($this->input->post('txt_date')));

            //====================== create FDNumber =========================//
            $FDNumber = $this->input->post('txt_fd_no');
            $acc_gl = $this->input->post('cmb_gl');
            $desc = $this->input->post('txa_description');
            $TotalAmount = $this->input->post('TotalAmount');
            $dataSend = [];
            $dataSend['group_update'] = [];
            $dataSend['detail_delete'] = [];
            $dataSend['journal_insert'] = [];
            $dataSend['FDNumber'] = $FDNumber;

            /* ==================function insert group================================================ */
            $dataSend['group_update'] = $this->update_group($branch, $FDNumber, $txt_date, $acc_gl, $desc, $TotalAmount, $user);

            /* ==================function delete journal ================================================ */
            //$this->m_fixed_asset_dispose->m_delete_journal($FDNumber);//masuk ke model

            /* ===========================delete detail================================================================= */
            if (count($detail_id) > 0) {
                foreach ($detail_id as $ass_code) {
                    $dataSend['detail_delete'][] = array(
                        'ass_code' => $ass_code,
                        'FDNumber' => $FDNumber
                    );
//                    $this->m_fixed_asset_dispose->m_delete_detail($ass_code,$FDNumber);//masuk ke model
                }
            }

            /* ==================function insert journal ================================================ */
            $dataSend['journal_insert'] = $this->insert_journal($branch, $detail, $FDNumber, $txt_date, $desc, $acc_gl, $user, false);

            $rstDataSend = $this->m_fixed_asset_dispose->datasend_fixedassetdispose_update($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification_transaksi($this->name, 'update', 1, $FDNumber);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification_transaksi($this->name, 'update', 0, $FDNumber);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function update_LAMA() {
        $branch = $this->session->userdata('branch');
        $user = $this->session->userdata('username');
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $detail_id = $this->input->post('detail_id');
        $detail_id = json_decode($detail_id);
        $txt_date = date('Y-m-d', strtotime($this->input->post('txt_date')));

        /* ====================== create FDNumber ============================== */
        $FDNumber = $this->input->post('txt_fd_no');

        $acc_gl = $this->input->post('cmb_gl');
        $desc = $this->input->post('txa_description');
        $TotalAmount = $this->input->post('TotalAmount');

        /* ============================ begin transaction =============================== */
        $this->db->trans_begin();

        /* ==================function insert group================================================ */
        $this->update_group($branch, $FDNumber, $txt_date, $acc_gl, $desc, $TotalAmount, $user);

        /* ==================function delete journal ================================================ */
        $this->m_fixed_asset_dispose->m_delete_journal($FDNumber);

        /* ===========================delete detail================================================================= */
        if (count($detail_id) > 0) {
            foreach ($detail_id as $ass_code) {
                $this->m_fixed_asset_dispose->m_delete_detail($ass_code, $FDNumber);
            }
        }

        // ==================function insert detail================================================
        // $this->update_detail($detail, $FDNumber,$user);

        /* ==================function insert journal ================================================ */
        $this->insert_journal($branch, $detail, $FDNumber, $txt_date, $desc, $acc_gl, $user);

        /* =============================trans roll back dan trans commit============================/ */
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $FDNumber);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $FDNumber);
        }

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


        echo json_encode($result);
    }

    public function suspend_data() {
        try {
            $FDNumber = $this->input->post('id');
            $branch = $this->session->userdata('branch');
            $dataSend = [];
            $dataSend['data_suspend'] = [];
            $dataSend['data_invent'] = [];
            $dataSend['FDNumber'] = $FDNumber;

            $dataSend['data_suspend'] = array(
                'TransStatus' => 3,
                'LastUser' => $this->session->userdata('username')
            );

            $dataSend['data_invent'] = array(
                'SoldStatus' => 0
            );

            /* ===================== update fixed asset group to suspend ========================== */
//            $this->m_fixed_asset_dispose->suspend_fixed_asset_dispose($data_suspend,$FDNumber);//masuk ke model

            /* ============ get asset code from fixed asset dispose by FDNumber ============================== */
            $arr_code = $this->m_fixed_asset_dispose->get_asset_code_fixed_asset($FDNumber);
            $dataSend['arr_asset_code'] = $arr_code['arr_asset_code'];
//            $this->m_fixed_asset_dispose->update_soldstatus($arr_code['arr_asset_code'],$data_invent);//masuk ke model 

            $rstDataSend = $this->m_fixed_asset_dispose->datasend_fixedassetdispose_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 suspend_data_LAMA() {

        $FDNumber = $this->input->post('id');
        $branch = $this->session->userdata('branch');

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

        $data_invent = array(
            'SoldStatus' => 0
        );

        $this->db->trans_begin();

        /* ===================== update fixed asset group to suspend ========================== */
        $this->m_fixed_asset_dispose->suspend_fixed_asset_dispose($data_suspend, $FDNumber);

        /* ============ get asset code from fixed asset dispose by FDNumber ============================== */
        $arr_code = $this->m_fixed_asset_dispose->get_asset_code_fixed_asset($FDNumber);

        $this->m_fixed_asset_dispose->update_soldstatus($arr_code['arr_asset_code'], $data_invent);

        /* =============================trans roll back dan trans commit============================/ */
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = false;
            $result['message'] = get_notification('suspend', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('suspend', 1);
        }
        /* ==================================end====================================================== */

        echo json_encode($result);
    }

    public function approved_dir() {
        try {
            $FDNumber = $this->input->post('id');
            $branch = $this->session->userdata('branch');

            $dataSend = [];
            $dataSend['data_approval'] = [];
            $dataSend['data_invent'] = [];
            $dataSend['FDNumber'] = $FDNumber;

            $dataSend['data_approval'] = array(
                'AppLevel2Status' => 1,
                'AppLevel2Code' => $this->session->userdata('username'),
                'AppLevel2Date' => date('Y-m-d'),
                'TransStatus' => 2,
                'AppFinished' => 1,
                'LastUser' => $this->session->userdata('username')
            );

            $dataSend['data_invent'] = array(
                'SoldStatus' => 4,
                'ItemQty' => 0,
                'Description' => 'Dispose :' . date('d-m-Y')
            );

            $arr_code = $this->m_fixed_asset_dispose->get_asset_code_fixed_asset($FDNumber);
            $dataSend['arr_asset_code'] = $arr_code['arr_asset_code'];
            $dataSend['arr_item_code'] = $arr_code['arr_item_code'];
            $dataSend['arr_item_average'] = $arr_code['arr_item_average'];

            $rstDataSend = $this->m_fixed_asset_dispose->datasend_fixed_asset_dispose_app_dir($dataSend);

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

    public function approved_dir_LAMA() {

        $FDNumber = $this->input->post('id');
        $branch = $this->session->userdata('branch');

        $data_approval = array(
            'AppLevel2Status' => 1,
            'AppLevel2Code' => $this->session->userdata('username'),
            'AppLevel2Date' => date('Y-m-d'),
            'TransStatus' => 2,
            'AppFinished' => 1,
            'LastUser' => $this->session->userdata('username')
        );

        $data_invent = array(
            'SoldStatus' => 4,
            'ItemQty' => 0,
            'Description' => 'Dispose :' . date('d-m-Y'));

        /* ======================== begin transaction ====================================== */
        $this->db->trans_begin();

        /* ===================== update fixed asset group to approve ========================== */
        $this->m_fixed_asset_dispose->approval_fixed_asset_dispose($data_approval, $FDNumber);

        /* ============ get asset code from fixed asset dispose by FDNumber ============================== */
        $arr_code = $this->m_fixed_asset_dispose->get_asset_code_fixed_asset($FDNumber);

        /* ============================ update soldstatus inv detail to sold ========================== */
        $this->m_fixed_asset_dispose->update_soldstatus($arr_code['arr_asset_code'], $data_invent);

        /* =========================== update inventories qty  =============================== */
        $this->m_fixed_asset_dispose->update_quantity_inventory($arr_code['arr_item_code']);

        /* =========================== update inventories value  =============================== */
        $this->m_fixed_asset_dispose->update_value_inventory($arr_code['arr_item_code']);

        /* =============================trans roll back dan trans commit============================/ */
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = false;
            $result['message'] = get_notification('approval', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('approval', 1);
        }
        /* ==================================end====================================================== */
        echo json_encode($result);
    }

    /* ===================================Fungsi reverse transaksi========================================== */

    public function reversed_data() {
        try {
            /* ===================================Deklarasi Variabel untuk proses insert atau update=================================== */
            $FDNumber = $this->input->post('id');
            $branch = $this->session->userdata('branch');
            $arr_no = explode("/", $FDNumber);
            $no_transaction = substr($arr_no[1], 0, 4);
            $month_transaction = (int) substr($no_transaction, 0, 2);
            $year_transaction = ((int) substr($no_transaction, 2, 2)) + 2000;
            $date_transaction = $year_transaction . $month_transaction;
            $dataSend = [];
            $dataSend['data_suspend'] = [];
            $dataSend['data_invent'] = [];
            $dataSend['FDNumber'] = $FDNumber;

            $dataSend['data_suspend'] = array(
                "TransStatus" => 5,
                "AppFinished" => 0
            );

            $dataSend['data_invent'] = array('SoldStatus' => 5, 'ItemQty' => 1, 'Description' => '');

            /* ============================== check period end ======================================== */
            $check_period = $this->m_fixed_asset_dispose->check_period_end($date_transaction);
            if ($check_period == false) {

                /* ============ get asset code from fixed asset dispose by FDNumber ============================== */
                $arr_code = $this->m_fixed_asset_dispose->get_asset_code_fixed_asset($FDNumber);
                $dataSend['arr_asset_code'] = $arr_code['arr_asset_code'];
                $dataSend['arr_item_code'] = $arr_code['arr_item_code'];
                $dataSend['arr_item_average'] = $arr_code['arr_item_average'];

                $rstDataSend = $this->m_fixed_asset_dispose->datasend_fixedassetdispose_reverse($dataSend);
                if ($rstDataSend) {
                    $result['status'] = true;
                    $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $FDNumber);
                } else {
                    $result['status'] = false;
                    $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $FDNumber);
                }
                echo json_encode($result);
            } else {
                throw new Exception(get_notification('reverse_in_period', 0));
            }
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function reversed_data_LAMA() {
        /* ===================================Deklarasi Variabel untuk proses insert atau update=================================== */
        $FDNumber = $this->input->post('id');

        $arr_no = explode("/", $FDNumber);
        $no_transaction = substr($arr_no[1], 0, 4);
        $month_transaction = substr($no_transaction, 0, 2);
        $year_transaction = ((int) substr($no_transaction, 2, 2)) + 2000;

        $date_transaction = $year_transaction . $month_transaction;

        $data = array(
            "TransStatus" => 5,
            "AppFinished" => 0
        );

        $data_invent = array('SoldStatus' => 5, 'ItemQty' => 1, 'Description' => '');


        /* ============================== check period end ======================================== */
        $check_period = $this->m_fixed_asset_dispose->check_period_end($date_transaction);

        if ($check_period == false) {

            /* =============================Transac begin =================================== */
            $this->db->trans_begin();

            /* =============================update fixed asset/ reverse =================================== */
            $this->m_fixed_asset_dispose->update_to_reverse_fixed_asset($FDNumber, $data);

            /* ============================= delete reconcile =============================================== */
            $this->m_fixed_asset_dispose->delete_reconcile($FDNumber);

            /* ============ get asset code from fixed asset dispose by FDNumber ============================== */
            $arr_code = $this->m_fixed_asset_dispose->get_asset_code_fixed_asset($FDNumber);

            $this->m_fixed_asset_dispose->update_soldstatus($arr_code['arr_asset_code'], $data_invent);

            /* =========================== update inventories qty + 1 =============================== */
            $this->m_fixed_asset_dispose->update_inventory_plus($arr_code['arr_item_code']);

            /* =========================== update inventories value  =============================== */
            $this->m_fixed_asset_dispose->update_value_inventory($arr_code['arr_item_code']);

            /* =========================== update inventories item average =============================== */
            $this->m_fixed_asset_dispose->update_inventory_average($arr_code['arr_item_code']);

            if ($this->db->trans_status() === TRUE) {
                $this->db->trans_commit();
                $result['status'] = true;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $FDNumber);
            } else {
                $this->db->trans_rollback();
                $result['status'] = false;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $FDNumber);
            }
            /* ============================= End Transac =================================== */
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('reverse_in_period', 0);
        }

        echo json_encode($result);
    }

    public function to_preview($obj_string = null) {
        $data['company'] = $this->m_fixed_asset_dispose->get_company_by_branch($this->session->userdata('branch'));
//        $data['list'] = $this->m_fixed_asset_dispose->get_all_to_print($this->session->userdata('branch'));

        $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_fixed_asset_dispose->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('fixed_asset_dispose/v_print_fixed_asset_dispose', $data);
        $this->load->view('v_footer');
    }
    public function to_preview_LAMA() {

        $data['company'] = $this->m_fixed_asset_dispose->get_company_by_branch($this->session->userdata('branch'));
        $data['list'] = $this->m_fixed_asset_dispose->get_all_to_print($this->session->userdata('branch'));

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

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

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

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

        $data['detail'] = $this->m_fixed_asset_dispose->get_detail_journal($FDNumber);

        $list = $this->m_fixed_asset_dispose->get_list_journal($branch, $FDNumber);

        $arr_list = array();
        $ind_arr = 0;
        $ind_arr_1 = 0;
        foreach ($list as $row) {

            $AssetCode = $row->AssetCode;
            $FDAccountNumber = $row->FDAccountNumber;
            $AccountName = $row->AccountName;
            $FDSaldoDebet = $row->FDSaldoDebet;
            $FDSaldoCredit = $row->FDSaldoCredit;

            if (count($arr_list) == 0) {
                $arr_list[0] = array('AssetCode' => $AssetCode,
                    'list' => array(
                        array(
                            'FDAccountNumber' => $FDAccountNumber,
                            'AccountName' => $AccountName,
                            'FDSaldoDebet' => $FDSaldoDebet,
                            'FDSaldoCredit' => $FDSaldoCredit)));
            } else {

                if ($AssetCode == $arr_list[$ind_arr]['AssetCode']) {

                    $ind_arr_1 += 1;
                    $arr_list[$ind_arr]['list'][$ind_arr_1] = array(
                        'FDAccountNumber' => $FDAccountNumber,
                        'AccountName' => $AccountName,
                        'FDSaldoDebet' => $FDSaldoDebet,
                        'FDSaldoCredit' => $FDSaldoCredit);
                } else {

                    $ind_arr += 1;
                    $ind_arr_1 = 0;
                    $arr_list[$ind_arr] = array('AssetCode' => $AssetCode,
                        'list' => array(
                            array(
                                'FDAccountNumber' => $FDAccountNumber,
                                'AccountName' => $AccountName,
                                'FDSaldoDebet' => $FDSaldoDebet,
                                'FDSaldoCredit' => $FDSaldoCredit)));
                }
            }
        }

        $data['list'] = $arr_list;

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

    function to_print_detail() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $companyCode = $this->session->userdata('company');

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

        if ($FDNumber != "") {

            $data['detail'] = $this->m_fixed_asset_dispose->get_detail_print($FDNumber);
            $data['list'] = $this->m_fixed_asset_dispose->get_detail_item_print($FDNumber);

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

    // public function get_fixed_asset(){
    // 	$branch 		= $this->session->userdata('branch');
    // 	$fixed_asset 	= $this->m_fixed_asset_dispose->get_fixed_asset($branch);
    // 	echo json_encode($fixed_asset);
    // }

    public function get_fixed_asset() {
        $branch = $this->session->userdata('branch');
        $fixed_asset = $this->m_fixed_asset_dispose->get_fixed_asset($branch);
        // echo $this->db->last_query();
        // die();

        $arrData = array();

        foreach ($fixed_asset as $row) {

            $fixed_asset_account    = $this->m_fixed_asset_dispose->get_fixed_asset_account_period($row->FixedAssetType);
            $AccumAccount           = $fixed_asset_account->AccumAccountNumber;
            $AccumAmount            = $this->m_fixed_asset_dispose->get_total_amount_period($branch, $row->AssetCode,$AccumAccount);

            $arrData[] = array(
                'ReceiptNumber' => $row->ReceiptNumber,
                'ReceiptDate' => $row->ReceiptDate,
                'ItemCode' => $row->ItemCode,
                'ItemAverage' => $row->ItemAverage,
                'ItemAverageHidden' => $row->ItemAverage,
                'AssetCode' => $row->AssetCode,
                'FixedAssetType' => $row->FixedAssetType,
                'ItemDesc' => $row->ItemDesc,
                'ItemQty' => $row->ItemQty,
                'ItemCategoryID' => $row->ItemCategoryID,
                'AccumAmount' => $AccumAmount,
                'AccumAmountHidden' => $AccumAmount);
        }

        echo json_encode($arrData);
    }

    public function get_gl_account() {
        $branch = $this->session->userdata('branch');
        $gl_account = $this->m_fixed_asset_dispose->m_get_gl_account($branch);
        echo json_encode($gl_account);
    }

    public function get_detail_fixed_asset($FDNumber) {
        $branch = $this->session->userdata('branch');

        $FDNumber = str_replace('slash', '/', $FDNumber);
        $FDNumber = str_replace('_', '-', $FDNumber);

        $fixed_asset_detail = $this->m_fixed_asset_dispose->get_fixed_asset_detail($branch, $FDNumber);
        //echo $this->db->last_query();
        echo json_encode($fixed_asset_detail);
    }

}
