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

/* Create : Ferry // Date : 2015-06-03 */

class Period_end extends CI_Controller {
    public $name                = "Period End";
    public $menu_id             = 224;
    public $menu_model          = array('custom/m_custom','m_period_end','m_currency','m_account_journal','report/m_index_to_report');
    public $jobtitle_status     = array('0', '1');
    public $trans_data          = array();
    public $arr_all_calculate   = array();
    public $arr_jvnumber        = array();
    public $arr_pp              = array();
    
    public function __construct() {
        parent::__construct();
        $this->load->helper('regex');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->model($this->menu_model);
        
        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,null);
            $data['available_menu'] = array_unique($arr_group_id);
            
            if(!in_array($this->menu_id, $data['available_menu'])) { 
                redirect(base_url() . 'error', 'refresh');  
            }else{
                $data_branch  = $this->m_custom->get_branch_detail();
                $this->branch = $this->session->userdata('branch');
        
                if($data_branch->BranchStatus == 0){
                    $this->ho = true;
                }else{
                    $this->ho = false;
                }
            }       
        }
        else{
            redirect(base_url() . 'login', 'refresh');
        }    
    }

    function get_interval_month1($from_date,$begin_date){

        $temp_d1 = new DateTime(date('Y-m-d', strtotime($from_date))); // 2012-01-01
        $temp_d2 = new DateTime(date('Y-m-d', strtotime($begin_date))); // 2013-02-01
        $interval = $temp_d2->diff($temp_d1); 
        $monthsAhead = $interval->m + ($interval->y * 12);

        return $monthsAhead;
    }

    function get_interval_month($month_begin,$year_begin,$month_end,$year_end){

        if($year_begin > $year_end){
            $from_year  = $year_end;
            $last_year  = $year_begin;
        }else{
            $from_year  = $year_begin;
            $last_year  = $year_end;
        }

        $interval = ((($last_year - $from_year) * 12) + $month_end) - $month_begin;
        return $interval;
    }

    function process_period_end(){

        //$this->output->enable_profiler(TRUE);

        /*============================ get variabel session ========================================*/
        $company_code       = $this->session->userdata('company');
        $branch_ho_code     = $this->session->userdata('branch');
        $department_code    = $this->session->userdata('department');
        $user_login         = $this->session->userdata("username");

        $detail_post        = $this->input->post('Detail');
        $detail             = json_decode($detail_post);
        $period_date        = date('Y-m-d');

        /*=========================== set periode month, year n desc =======================================*/
        $period_month       = (int)$this->input->post('PeriodMonth');
        $period_year        = (int)$this->input->post('PeriodYear');
        $period_desc        = $this->input->post('Description');
        $period_month       = $period_month;
        $period_end         = $period_year . $period_month;
        
        /*=============================== set begin_date and end_date ====================================*/
        $begin_date         = date('Y-m-d',strtotime($period_year.'-'.$period_month.'-01'));
        $day_month          = date('t', strtotime($begin_date));
        $end_date           = date('Y-m-d');

        /*======================== cek bulan end period harus < bulan sekarang ========================*/
        $cek_period_ym      = date('Y-m',strtotime($period_year.'-'.$period_month));
        $cek_now_ym         = date('Y-m');

        /*======================= cek apakah bulan sekarang sudah di period end atau belum ===========================*/
        $is_periodend = $this->m_period_end->check_endperiod($period_end);

        if($is_periodend == false){

            if($cek_now_ym > $cek_period_ym){

                if(count($detail) > 0){

                    /*============================ get last end period =================================*/
                    $last_endperiod         = $this->m_period_end->get_last_endperiod();

                    if($last_endperiod != false){
                        $last_year          = substr($last_endperiod,0,4);
                        $last_month         = substr($last_endperiod,4,2);

                        /*======================== get month interval end period ================================*/
                        $month_interval     = $this->get_interval_month($last_month,$last_year,$period_month,$period_year);

                    }else{
                        $is_CompCreateDate = $this->m_period_end->check_company_create($company_code,$period_month,$period_year);
                        if($is_CompCreateDate){
                            $month_interval = TRUE;
                        }else{
                            $month_interval = FALSE;
                        }
                    }

                    /*=============================== cek approved transaksi ==================================*/
                    $check_approved     = $this->m_period_end->check_transstatus_not_approved($begin_date, $end_date,$last_endperiod);

                    /*=============================== check reconcile ========================================*/
                    $check_reconcile    = $this->m_period_end->check_transaction_not_reconcile($begin_date,$end_date,$last_endperiod);

                    if(($month_interval == 1) or ($month_interval == TRUE)){

                        if($check_approved == false){

                            if($check_reconcile == false){

                                /*====================== get all branch by company ========================*/
                                $arr_branch         = $this->m_period_end->get_branch($company_code);

                                /*====================== get last JVchNumber by branch ====================*/
                                $this->arr_jvnumber = $this->m_period_end->get_arr_jvnumber($arr_branch,$begin_date);

                                /*=================================== calculate kurs ================================================================*/
                                $this->calculate_exchange_rate($detail,$last_endperiod,$begin_date,$end_date,$company_code,$department_code,$period_month,$period_year);

                                /*================================== calculate adv payment ==============================*/
                                $this->calculate_advance_payment($company_code,$department_code,$period_month,$period_year);

                                /*================================== calulate depreciation fixed asset ============================*/
                                $this->calculate_depreciation_fixed_asset($company_code,$department_code,$period_month,$period_year);

                                /*========================================= calculate PL ============================================*/
                                $this->calculate_profit_lost($company_code,$department_code,$period_month,$period_year);

                                /*===================================== if cek_account > 0 then filed =====================================*/
                                $cek_account = $this->recalculate_coa($company_code,$period_date,$period_year,$period_month,$last_endperiod);

                                if($cek_account['return'] < 1){
                                    /*====================================== create balance sheet =====================================*/
                                    $this->create_new_balancesheet($company_code,$cek_account['arr_account'],$period_month,$period_year);

                                    /*====================================== check balance sheet balance / not balance ==============================*/
                                    $is_balance = $this->checking_balancesheet($detail);

                                    if($is_balance){
                                        /*=================================== insert to table end periode ==================================================*/
                                        $this->insert_group_period($company_code,$period_date,$period_year,$period_month,$period_desc);

                                        /*=================================== change master currency rate ==================================================*/
                                        $this->change_master_currency_rate($detail);

                                        /*================== insert history currency =============================*/
                                        $this->create_history_currency($detail,$period_year,$period_month);
                                        
                                        $result_return = $this->m_period_end->m_process_period_end($this->trans_data);

                                        $this->trans_data = [];

                                        if($result_return){
                                            $result['status']   = true;
                                            $result['message']  = get_notification_transaksi($this->name,'period',1,$period_end);
                                        }else{
                                            $result['status']   = false;
                                            $result['message']  = get_notification_transaksi($this->name,'period',0,$period_end);
                                        }
                                        
                                    }else{
                                        /*============== Balancesheet tidak balance ==========================*/
                                        $result['status'] = false;
                                        $result['message'] = get_notification('not_balance',0);
                                    }

                                }else{

                                    /*================== Recalculate coa not balance ============================*/
                                    $result['status']   = FALSE;
                                    $result['message']  = get_notification('recalculate_coa',0).$cek_account['arr_err'][0]['Account'].'. Branch : '.$cek_account['arr_err'][0]['branch'];
                                }

                            }else{

                                /*============== not full reconcile ======================*/
                                $result['status'] = false;
                                $result['message'] = get_notification('not_reconcile',0).$check_reconcile['Journal_Number'].', Type Transaksi : '.$check_reconcile['Trans_Type'];
                            }

                        }else{

                            /*============== not full approved ======================*/
                            $result['status'] = false;
                            $result['message'] = get_notification('not_approved',0).$check_approved['Journal_Number'].', Type Transaksi : '.$check_approved['Trans_Type'];
                        }
                    }else{

                        /*======================= month_interval > 1 or YM period end pertama tidak sama dengan YM Comapny Date =======================*/
                        $result['status'] = false;
                        $result['message'] = get_notification('month_interval',0);
                    }

                }else{
                    /*============== detail currency null ======================*/
                    $result['status'] = false;
                    $result['message'] = get_notification('master_currency',0);
                }

            }else{

                /*============== period date YM > now date YM ======================*/
                $result['status'] = false;
                $result['message'] = get_notification('month_lower',0);
            }
        }
        else{

            /*============== sudah di period end ======================*/
            $result['status'] = false;
            $result['message'] = get_notification('already_in_period',0);
        }

        echo json_encode($result);
    }

    function insert_group_period($company_code,$period_date,$period_year,$period_month,$period_desc){

        $period_end     = $period_year.$period_month;

        $data_period    = array(
                        'PeriodEnd'     => $period_end,
                        'CompanyCode'   => $company_code,
                        'PeriodDate'    => date('Y-m-d H:i:s',strtotime($period_date)),
                        'PeriodDesc'    => $period_desc,
                        'LastUser'      => $this->session->userdata('username'));

        //$this->m_period_end->insert_group_period($data_period);
        $this->trans_data['insert_group_period']['data'] = $data_period;

    }

    function change_master_currency_rate($detail){

        foreach($detail as $row){

            $CompanyCode    = $row->CompanyCode;
            $CurrencyID     = $row->CurrencyID;
            $CurrencyRate   = $row->CurrencyRate;

            $data_currency  = array('CurrencyRate'=>$CurrencyRate);

            //$this->m_period_end->update_master_currency_rate($CompanyCode,$CurrencyID,$data_currency);
            $this->trans_data['master_currency']['companycode'][] = $CompanyCode;
            $this->trans_data['master_currency']['CurrencyID'][] = $CurrencyID;
            $this->trans_data['master_currency']['data'][] = $data_currency;
        }

    }

    function create_history_currency($detail,$period_year,$period_month){
        foreach($detail as $row){

            $CompanyCode    = $row->CompanyCode;
            $CurrencyID     = $row->CurrencyID;
            $CurrencyCode   = $row->CurrencyCode;
            //$CurrencyRate   = $row->CurrencyRate;
            $PeriodEnd      = $period_year.$period_month;
            $master_rate    = $this->m_period_end->get_master_currency($CompanyCode,$CurrencyCode);

            $data_currency  = array('CurrencyRate'  => $master_rate,
                                    'CurrencyID'    => $CurrencyID,
                                    'CompanyCode'   => $CompanyCode,
                                    'PeriodEnd'     => $PeriodEnd);

            $this->trans_data['history_currency']['data'][] = $data_currency;
        }

    }

    function search_key($branch,$search_branch,$account,$search_account,$array) {
       foreach ($array as $key => $val) {
           if (($val[$search_branch] === $branch) and ($val[$search_account] === $account )) {
               return $key;
           }
       }
        return FALSE; 
       
    }

    function search_key_year($branch,$search_branch,$account,$search_account,$year,$GLSaldoYears,$array) {
       foreach ($array as $key => $val) {
           if (($val[$search_branch] === $branch) and ($val[$search_account] === $account ) and ($val[$GLSaldoYears] == $year )) {
               return $key;
           }
       }
        return FALSE; 
       
    }

    function single_search_key($val_search,$array) {
       foreach($array as $key => $val){
            if($val === $val_search){
                return $key;
            }
       }

       return FALSE;
    }

    function hitung_bank(){
        /*=================================== get all account bsstatus = 1 =============================================*/
        $account_gl                 = $this->m_period_end->get_account_by_bsstatus_reverse($company_code,$period_month,$period_year,1);
        
        $before_from_date           = $period_year.'-'.$period_month.'-01';
        $day_month                  = date('t',strtotime($before_from_date));
        $before_end_date            = $period_year.'-'.$period_month.'-'.$day_month;

        $after_from_date            = $period_year.'-'.($period_month + 1).'-01';
        $after_end_date             = date('Y-m-d');
        $company_code               = $this->session->userdata('company');

        /*=========================================== get first balance and last balance ==============================================================*/
        $before_transaction_period  = $this->m_period_end->get_all_transaction_by_bsstatus($company_code,$before_from_date,$before_end_date,1);
    
        /*================================== grouping array before transaction ========================================*/
        $arr_before     = array();
        $no_before      = -1;

        foreach($before_transaction_period as $row){

            $account_number = $row->Account_Number;
            $AmountCurrency = $row->Amount_Currency;
            $branch         = $row->Branch_Code;
            $trans_type     = $row->Trans_Type;
            $rate           = $row->CurrencyRate;

            /*================ check credit or debet ======================*/
            $debet_kredit   = $this->m_account_journal->debet_kredit_profit_loss($Acc_Type_Name,$Sub_Type_Name);

            if($debet_kredit['plus'] == 'Credit'){
                if($pos_trans == 'Credit'){
                    $AmountCurrency = $AmountCurrency;
                }else{
                    $AmountCurrency = $AmountCurrency * -1;
                } 
            }else{
               if($pos_trans == 'Debet'){
                    $AmountCurrency = $AmountCurrency;
                }else{
                    $AmountCurrency = $AmountCurrency * -1;
                }  
            }

            if(count($arr_before) == 0){
                array_push($arr_before,array('branch'=>$branch,'account_number'=> $account_number,'amount_currency'=> $AmountCurrency));
                $no_before++;
            }else{

                if(($branch == $arr_before[$no_before]['branch']) and ($account_number == $arr_before[$no_before]['account_number'])){
                    $arr_before[$no_before]['amount_currency'] += $AmountCurrency;
                }else{
                    array_push($arr_before,array('branch'=>$branch,'account_number'=> $account_number,'amount_currency'=> $AmountCurrency));
                    $no_before++;
                }
            }
        }

        $total_before   = count($arr_before);
        $total_after    = count($arr_after);
        $total_bank     = count($account_gl);

        /*=================================== total balance account before ================================*/
        for($i=0;$i<$total_before;$i++){

            $branch                 = $arr_before[$i]['branch'];
            $account_number         = $arr_before[$i]['account_number'];
            $amount_before          = $arr_before[$i]['amount_currency'];

            $key                    = $this->search_key($branch,'BranchCode',$account_number,'AccountNumber',$account_gl);

            $balancesheet_bank      = $account_gl[$key]['BankBalance'];
            $saldo_balance_bank     = $account_gl[$key]['GLSaldoBalance'];
            $opening_balance_bank   = $account_gl[$key]['GLSaldoOpening'];

            if($last_endperiod == false){
                $balance_before     = $opening_balance_bank + $amount_before;
            }else{
                $balance_before     = $saldo_balance_bank + $amount_before;
            }

            array_push($arr_return,array('branch' => $branch,
                                        'Account' => $account_number,
                                        'balance_before'  => $balance_before,
                                        'arr_before' => $arr_before,
                                        ));
        }
    }

    

    function debet_kredit($account_subtype){
        if($account_subtype == 'Hutang Dagang' || $account_subtype == 'Akumulasi Penyusutan Aktiva Tetap' || $account_subtype == 'Hutang Bahan Baku' || $account_subtype == 'Hutang Bahan Bakar' || 
            $account_subtype == 'Hutang Bahan Bakar Penolong' || $account_subtype == 'Hutang Afiliasi' || $account_subtype == 'Hutang Ekspedisi' || 
            $account_subtype == 'Hutang Lain-Lain' || $account_subtype == 'Hutang Pajak' || $account_subtype == 'Hutang Yg Belum di Tagih' || 
            $account_subtype == 'Hutang Barang Migrasi' || $account_subtype == 'Hutang Expense' || $account_subtype == 'Hutang Advance Payment' || 
            $account_subtype == 'Hutang PPn Fiscal' || $account_subtype == 'Hutang Aktiva Tetap' || $account_subtype == 'Uang Muka Penjualan' || 
            $account_subtype == 'Bank Garansi Customer' || $account_subtype == 'Hutang Pemegang Saham' || $account_subtype == 'Hutang Bank' || 
            $account_subtype == 'Hutang Leasing' || $account_subtype == 'Kewajiban Pajak Tangguhan' || $account_subtype == 'Modal' || 
            $account_subtype == 'Prive' || $account_subtype == 'Laba (Rugi) Ditahan' || $account_subtype == 'Laba (Rugi) Berjalan' || 
            $account_subtype == 'Laba (Rugi) Bulan Berjalan' || $account_subtype == 'Dividen' || $account_subtype == 'Revenue' || 
            $account_subtype == 'Retur Pembelian' || $account_subtype == 'Other Revenue' || $account_subtype == 'Selisih Kurs Akhir Transaksi' || 
            $account_subtype == 'Selisih Kurs Akhir Transaksi' || $account_subtype == 'Hutang Bank'){  
            
            $debet_kredit = "Kredit";
        }
        else{
            $debet_kredit = "Debet";
        }

        return $debet_kredit;
    }

    
    function calculate_exchange_rate($detail,$last_endperiod,$from_date,$end_date,$company_code,$department_code,$period_month,$period_year){

        $day_month      = date('t',strtotime($period_year.'-'.$period_month.'-01'));
        $period_date    = date('Y-m-d',strtotime($period_year.'-'.$period_month.'-'.$day_month));
        $PeriodEnd      = $period_year.$period_month;

        if(abs($period_month) == 1){
            $month  = 12;
            $year   = abs($period_year) - 1;
        }else{
            $month  = abs($period_month) - 1;
            $year   = $period_year;
        }

        /*===================== defaine array untuk menampung data group ==============================*/
        $ind_arr    = 0;
        $arr_data   = array();
        /*===================== end end end end end end end end end end ===============================*/

        /*===================== looping detail ==========================*/
        foreach($detail as $row){
            $ind_branch         = 0;
            $arr_data[$ind_arr] = array('branch'=>array(),'JVchNumber'=>array(),'Amount'=>array());

            /*======================== set variabel ===========================*/
            $currency_code  = $row->CurrencyCode;
            $currency_rate  = $row->CurrencyRate;

            /*=============== calculasi untuk currency code !=IDR ==================================*/
            if($currency_code != 'IDR'){
                /*============================= get master currency =======================================*/
                $master_rate        = $this->m_period_end->get_master_currency($company_code,$currency_code);

                /*============================= get bank account non IDR =======================*/
                $account_gl         = $this->m_period_end->get_bank_account($currency_code,$company_code,$period_year);
                // echo $this->db->last_query();

                /*========================= looping account_gl ==================================*/
                for($x=0;$x<count($account_gl);$x++){

                    $total_arr_branch   = count($arr_data[$ind_arr]['branch']);
                    $bank               = $account_gl[$x]['AccountNumber'];
                    $branch             = $account_gl[$x]['BranchCode'];
                    $bank_currency_code = $account_gl[$x]['CurrencyCode'];

                    $account_diff       = $this->m_period_end->get_account_diff($bank_currency_code,$branch,$period_year);

                    /*================= account selisih kurs tidak boleh false ========================*/
                    if($account_diff == false){
                        $this->trans_data   = [];
                        $result['status']   = FALSE;
                        $result['message']  = get_notification('coa_diff_kurs',0);
                        echo json_encode($result);
                        die();
                    }else{

                        /*========================== get saldo last balance ===============================================*/
                        $last_balance       = $this->m_period_end->get_saldo_balance_by_branch($bank,$branch,$period_year);
                        /*===================================================== get last saldo ============================*/
                        $last_saldo         = $this->m_period_end->get_last_saldo_bank($bank,$branch,$from_date,$period_date);
                        /*================================== get saldo awal bank ==========================================*/
                        $first_balance      = $this->m_period_end->get_saldo_opening_balance($branch,$bank,$month,$year,$last_endperiod);
                        // echo $this->db->last_query();
                        /*==================================================== set diff currency ==========================*/
                        $diff_kurs          = $this->m_period_end->get_diff_kurs($bank,$branch,$first_balance,$last_balance,$last_saldo,$currency_rate,$master_rate);
                
                        if($diff_kurs < 0){
                            $JVchTotalDebet     = bcmul($diff_kurs,-1,20);
                            $JVchTotalCredit    = 0;
                            $JVchSignStatus     = 0;
                        }else{
                            $JVchTotalDebet     = 0;
                            $JVchTotalCredit    = $diff_kurs;
                            $JVchSignStatus     = 1;
                        }

                        $AmountCurrency          = $diff_kurs < 0 ? bcmul($diff_kurs,-1,20):$diff_kurs;
                        //echo 'selisi kurs :' .$diff_kurs < 0 ? bcmul($diff_kurs,-1,20):bcmul($diff_kurs,-1,20);

                        /*========================= semua amount n account selisih kusr di tampung untuk calculate profit n lost =====================*/
                        $this->arr_all_calculate['amount'][]            = $diff_kurs < 0 ? bcmul($diff_kurs,-1,20):bcmul($diff_kurs,-1,20);
                        $this->arr_all_calculate['account_number'][]    = $account_diff; 
                        $this->arr_all_calculate['BranchCode'][]        = $branch;
                        $this->arr_all_calculate['Acc_Type_Name'][]     = $this->m_period_end->get_account_type($company_code,$account_diff,$period_year); 
                        /*======================================================= END ==============================================================*/
                        
                        //echo $diff_kurs.' vs '.abs($diff_kurs).' vs '.($diff_kurs < 0 ? bcmul($diff_kurs,-1,20):bcmul($diff_kurs,-1,20));

                        /*======================================= group by branch =====================================*/
                        if($total_arr_branch > 0){
                            if($branch == $arr_data[$ind_arr]['branch'][$ind_branch-1]){
                                $arr_data[$ind_arr]['Amount'][$ind_branch-1] += $diff_kurs;
                            }else{
                                /*============================== create jvb number ================================*/
                                //$JVchNumber                           = $this->m_period_end->create_jv_number($period_date,$branch);
                                $ind_jv                                 = $this->single_search_key($branch,$this->arr_jvnumber['BranchCode']);
                                $JVchNumber                             = $this->arr_jvnumber['JVchNumber'][$ind_jv];

                                /*============================== untuk JVchNumber calculate adv.payment,fix.asset, dan pp ===========================*/
                                /*============================== harus get dan update dari JVNumber selisih kurs ==========================*/

                                /*============================== create new JVchNumber untuk selanjutnya ============================*/
                                $jv_number                                          = $this->create_manual_jvnumber($JVchNumber);
                                $this->arr_jvnumber['JVchNumber'][$ind_jv]          = $jv_number;

                                $arr_data[$ind_arr]['branch'][$ind_branch]         = $branch;
                                $arr_data[$ind_arr]['JVchNumber'][$ind_branch]     = $JVchNumber;
                                $arr_data[$ind_arr]['Amount'][$ind_branch]         = $diff_kurs;
                    
                                /*============================== insert group journal voucher balance ==========================================*/
                                $data_group     = array(
                                        'BranchCode'        => $branch,
                                        'JVchDate'          => $period_date,
                                        'JVchNumber'        => $JVchNumber,
                                        'JVchDesc'          => 'Selisih Kurs Akhir Period '.$bank_currency_code,
                                        'JVchTotalDebet'    => 0,
                                        'JVchTotalCredit'   => 0,
                                        'JVchType'          => 0,
                                        'TransStatus'       => 6,
                                        'AppFinished'       => 0,
                                        'CreatedBy'         => $this->session->userdata('username'),
                                        'CreatedAt'         => date('Y-m-d H:i:s',strtotime($period_date)),
                                        'LastUser'          => $this->session->userdata('username'));

                                // $this->m_period_end->insert_group_jvb($data_group);
                                $this->trans_data['selisih_kurs']['insert_group_jvb']['data'][] = $data_group;

                                $ind_branch++;
                            }
                        }else{

                            //$JVchNumber                           = $this->m_period_end->create_jv_number($period_date,$branch);
                            $ind_jv                                 = $this->single_search_key($branch,$this->arr_jvnumber['BranchCode']);
                            $JVchNumber                             = $this->arr_jvnumber['JVchNumber'][$ind_jv];

                            /*============================== create new JVchNumber ============================*/
                            /*============================== untuk JVchNumber calculate adv.payment,fix.asset, dan pp ===========================*/
                            /*============================== harus get dan update dari JVNumber selisih kurs ==========================*/

                            $jv_number                                          = $this->create_manual_jvnumber($JVchNumber);
                            $this->arr_jvnumber['JVchNumber'][$ind_jv]          = $jv_number;

                            $arr_data[$ind_arr]['branch'][$ind_branch]         = $branch;
                            $arr_data[$ind_arr]['JVchNumber'][$ind_branch]     = $JVchNumber;
                            $arr_data[$ind_arr]['Amount'][$ind_branch]         = $diff_kurs;
                
                            /*============================== insert group journal voucher balance ==========================================*/
                            $data_group     = array(
                                    'BranchCode'        => $branch,
                                    'JVchDate'          => $period_date,
                                    'JVchNumber'        => $JVchNumber,
                                    'JVchDesc'          => 'Selisih Kurs Akhir Period '.$bank_currency_code,
                                    'JVchTotalDebet'    => 0,
                                    'JVchTotalCredit'   => 0,
                                    'JVchType'          => 0,
                                    'TransStatus'       => 6,
                                    'AppFinished'       => 0,
                                    'CreatedBy'         => $this->session->userdata('username'),
                                    'CreatedAt'         => $period_date,
                                    'LastUser'          => $this->session->userdata('username'));

                            // $this->m_period_end->insert_group_jvb($data_group);
                            $this->trans_data['selisih_kurs']['insert_group_jvb']['data'][] = $data_group;

                            $ind_branch++;
                        }
                        /*======================================= end group by branch =====================================*/

                        /*============================== insert detail journal voucher balance =========================================*/
                        $data_detail    = array(
                                'JVchNumber'        => $arr_data[$ind_arr]['JVchNumber'][$ind_branch-1],
                                'JVchAccount'       => $account_diff,
                                'JVchDebetSaldo'    => $JVchTotalDebet,
                                'JVchCreditSaldo'   => $JVchTotalCredit,
                                'JVchDetailMemo'    => '',
                                'JVchRate'          => 1,
                                'CurrencyCode'      => $currency_code,
                                'JVchDetailDept'    => $department_code,
                                'ReconcileStatus'   => 1,
                                'PeriodEnd'         => $PeriodEnd,
                                'LastUser'          => $this->session->userdata('username'));

                        //$this->m_period_end->insert_detail_jvb($data_detail);
                        $this->trans_data['selisih_kurs']['insert_detail_jvb']['data'][] = $data_detail;
                        /*============================== end insert detail journal voucher balance =========================================*/

                        /*============================== insert journal voucher balance ================================================*/
                        $data_journal   = array(
                                'JVchDate'          => $period_date,
                                'JVchNumber'        => $arr_data[$ind_arr]['JVchNumber'][$ind_branch-1],
                                'JVchDesc'          => '',
                                'JVchAccountNumber' => $account_diff,
                                'JVchSaldoDebet'    => $JVchTotalDebet,
                                'JVchSaldoCredit'   => $JVchTotalCredit,
                                'JVchSignStatus'    => $JVchSignStatus,
                                'AmountCurrency'    => $AmountCurrency,
                                'AppFinished'       => 0,
                                'LastUser'          => $this->session->userdata('username'));

                        //$this->m_period_end->insert_journal_jvb($data_journal);
                        $this->trans_data['selisih_kurs']['insert_journal_jvb']['data'][] = $data_journal;
                        /*============================== end insert journal voucher balance ================================================*/

                    }
                    /*================= end account selisih kurs tidak boleh false ========================*/
                }
                /*========================= end looping account_gl ==================================*/
            }
            /*=============== end calculasi untuk currency code !=IDR ==================================*/
            $ind_arr++;
        }
        /*===================== end looping detail ==========================*/

        $this->trans_data['selisih_kurs']['total_group'] = 0;

        $total_data = count($arr_data);
        for($x=0;$x<$total_data;$x++){
            $total_branch = count($arr_data[$x]['branch']);
            for($i=0;$i<$total_branch;$i++){
                $data_update   = array(
                    'JVchTotalDebet'    => $arr_data[$x]['Amount'][$i] < 0 ? $arr_data[$x]['Amount'][$i]:0,
                    'JVchTotalCredit'   => $arr_data[$x]['Amount'][$i] > 0 ? $arr_data[$x]['Amount'][$i]:0,
                    'AppLevel1Status'   => 1,
                    'AppLevel1Code'     => $this->session->userdata('username'),
                    'AppLevel1Date'     => $period_date,
                    'AppLevel2Status'   => 1,
                    'AppLevel2Code'     => $this->session->userdata('username'),
                    'AppLevel2Date'     => $period_date,
                    'TransStatus'       => 2,
                    'AppFinished'       => 1,
                    'LastEdited'        => $this->session->userdata('username')); 

                //$this->m_period_end->update_group_jvb($JVchNumber,$data_update);
                $this->trans_data['selisih_kurs']['update_group_jvb']['data'][]           = $data_update;
                $this->trans_data['selisih_kurs']['update_group_jvb']['TransNumber'][]    = $arr_data[$x]['JVchNumber'][$i];

                /*========================== increment total selisih kurs ===========================*/
                $this->trans_data['selisih_kurs']['total_group']  += 1;
            }
        }

        // print_r($this->arr_all_calculate);
        // die();
    }

    function calculate_advance_payment($company_code,$department_code,$period_month,$period_year){

        $cek_branch                 = '';
        $arr_JVB                    = array();
        $no_array                   = -1;
        $PeriodEnd                  = $period_year.$period_month;

        $day_month                  = date('t',strtotime($period_year.'-'.$period_month.'-01'));
        $period_date                = date('Y-m-d',strtotime($period_year.'-'.$period_month.'-'.$day_month));

        /*======================= get all adv payment =============================*/
        $get_adv_payment            = $this->m_period_end->get_adv_payment($company_code,$period_date);
        // echo $this->db->last_query();
        // die();

        $this->trans_data['advance_payment']['total_detail']    = 0;
        $this->trans_data['advance_payment']['total_group']     = 0; 

        foreach($get_adv_payment as $row){

            $branch             = $row->BranchCode;
            $pinv_number        = $row->PInvNumber;
            //$item_code          = $row->ItemCode.','.$row->PInvNumber;
            $item_code          = $row->ItemCode;

            /*=========================== get Expense Account n Advance Account ==========================*/
            $ExpenseAccount     = $this->m_period_end->get_sys_advance_account('Expense', 'IDR',$item_code,$branch,$period_year);
            $AdvanceAccount     = $this->m_period_end->get_sys_advance_account('Advance', 'IDR',$item_code,$branch,$period_year);
           
            if(($ExpenseAccount != false) and ($AdvanceAccount != false)){

                $pinv_date              = $row->PInvDate;
                $pinv_curr_code         = $row->CurrencyCode;
                $payment_period         = $row->PaymentPeriod + 1;
                $JVoucherBalance        = $row->JVoucherBalance;
                $pinv_total_amount      = $row->ItemTotalAmount;
                //$pinv_payment_amount    = $row->PaymentAmount;
                $pinv_adv_net_due_in    = $row->ItemAdvNetDueIn;
                $item_code              = $row->ItemCode.'-'.$pinv_number;

                /*====================== count total period end for this ItemCode =====================*/
                $count_period           = $this->m_period_end->count_period_by_itemcode($branch,$item_code,$AdvanceAccount->AccountNumber);
                if($count_period > 0){
                    $count_period = $count_period / 2;
                }
                
                /*======================== total payment endperiod from journal voucher balance by ItemCode ==============================*/
                $total_amount_period    = $this->m_period_end->get_total_amount_period($branch,$item_code,$AdvanceAccount->AccountNumber);
                $total_amount_period    = bcadd($total_amount_period,$JVoucherBalance,20);

                /*======================= sisa advance payment ================================================*/
                $sisa_period            = $pinv_adv_net_due_in - $count_period;
                $sisa_amount            = bcsub($pinv_total_amount,$total_amount_period,20);

                //$payment_per_period     = ($pinv_total_amount - (doubleval($total_amount_period) + $JVoucherBalance )) / $sisa_period;
                $payment_per_period     = $sisa_period > 0 ? bcdiv(bcsub($pinv_total_amount,$total_amount_period,20),$sisa_period,20):bcsub($pinv_total_amount,$total_amount_period,20);

                //$pinv_payment_amount    = bcadd($payment_per_period,$pinv_payment_amount,20);

                /*========================= update at_pinvdetailrecur ============================*/
                // $data_update_advance    = array(
                //         'PaymentPeriod'     => $payment_period,
                //         'PaymentDate'       => $period_date,
                //         'PaymentPeriod'     => $pinv_payment_amount);

                // $this->m_period_end->update_invdetailrec($pinv_number,$data_update_advance);

                if($sisa_amount > 0){

                    if($branch == $cek_branch){
                        $arr_JVB[$no_array]['total_payment']    = bcadd($payment_per_period,$arr_JVB[$no_array]['total_payment'],20);
                    }else{

                         //$JVchNumber                           = $this->m_period_end->create_jv_number($period_date,$branch);
                        $ind_jv                                 = $this->single_search_key($branch,$this->arr_jvnumber['BranchCode']);
                        $JVchNumber                             = $this->arr_jvnumber['JVchNumber'][$ind_jv];

                        /*============================== create new JVchNumber untuk selanjutnya ============================*/
                        $jv_number                                          = $this->create_manual_jvnumber($JVchNumber);
                        $this->arr_jvnumber['JVchNumber'][$ind_jv]          = $jv_number;

                        /*========================== insert group journal voucher ================================*/
                        $data_group                 = array(
                                'BranchCode'        => $branch,
                                'JVchDate'          => $period_date,
                                'JVchNumber'        => $JVchNumber,
                                'JVchDesc'          => 'Advance Payment',
                                'JVchTotalDebet'    => 0,
                                'JVchTotalCredit'   => 0,
                                'JVchType'          => 0,
                                'TransStatus'       => 6,
                                'AppFinished'       => 0,
                                'CreatedBy'         => $this->session->userdata('username'),
                                'CreatedAt'         => date('Y-m-d H:i:s',strtotime($period_date)),
                                'LastUser'          => $this->session->userdata('username'));

                        //$this->m_period_end->insert_group_jvb($data_group);
                        $this->trans_data['advance_payment']['insert_group_jvb']['data'][] = $data_group;


                        $cek_branch             = $branch;
                        array_push($arr_JVB,array('JVchNumber' => $JVchNumber,'total_payment' => $payment_per_period));
                        $no_array += 1;
                    }

                    /*========================= semua amount n account selisih kusr di tampung untuk calculate profit n lost =====================*/
                    

                    /*======================================================= END ==============================================================*/

                    /*================== insert detail journal voucher balance for Expense ============*/
                    $data_detail_expense    = array(
                            'JVchNumber'        => $arr_JVB[$no_array]['JVchNumber'],
                            'JVchAccount'       => $ExpenseAccount->AccountNumber,
                            'JVchDebetSaldo'    => $payment_per_period,
                            'JVchCreditSaldo'   => 0,
                            'JVchDetailMemo'    => '',
                            'JVchRate'          => 1,
                            'CurrencyCode'      => 'IDR',
                            'JVchDetailDept'    => $department_code,
                            'ReconcileStatus'   => 1,
                            'AssetCode'         => $item_code,
                            'PeriodEnd'         => $PeriodEnd,
                            'LastUser'          => $this->session->userdata('username'));

                    //$this->m_period_end->insert_detail_jvb($data_detail_expense);
                     $this->trans_data['advance_payment']['insert_detail_jvb']['data'][] = $data_detail_expense;

                    /*================== insert detail journal voucher balance for Advance ============*/
                    $data_detail_advance    = array(
                            'JVchNumber'        => $arr_JVB[$no_array]['JVchNumber'],
                            'JVchAccount'       => $AdvanceAccount->AccountNumber,
                            'JVchDebetSaldo'    => 0,
                            'JVchCreditSaldo'   => $payment_per_period,
                            'JVchDetailMemo'    => '',
                            'JVchRate'          => 1,
                            'CurrencyCode'      => 'IDR',
                            'JVchDetailDept'    => $department_code,
                            'ReconcileStatus'   => 1,
                            'AssetCode'         => $item_code,
                            'PeriodEnd'         => $PeriodEnd,
                            'LastUser'          => $this->session->userdata('username'));

                    //$this->m_period_end->insert_detail_jvb($data_detail_advance);
                    $this->trans_data['advance_payment']['insert_detail_jvb']['data'][] = $data_detail_advance;

                    /*==================================== cek debet kredit expense ================================================*/
                    $debet_kredit           = $this->m_account_journal->debet_kredit_profit_loss($ExpenseAccount->Acc_Type_Name,$ExpenseAccount->Sub_Type_Name);
                    
                    /*=================== insert journal voucher balance for expense ============================*/
                    $data_journal_expense   = array(
                            'JVchDate'          => $period_date,
                            'JVchNumber'        => $arr_JVB[$no_array]['JVchNumber'],
                            'JVchDesc'          => '',
                            'JVchAccountNumber' => $ExpenseAccount->AccountNumber,
                            'JVchSaldoDebet'    => $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period,
                            'JVchSaldoCredit'   => 0,
                            'JVchSignStatus'    => 0,
                            'AmountCurrency'    => $payment_per_period,
                            'AppFinished'       => 0,
                            'LastUser'          => $this->session->userdata('username'));

                    //$this->m_period_end->insert_journal_jvb($data_journal_expense);
                    $this->trans_data['advance_payment']['insert_journal_jvb']['data'][] = $data_journal_expense;
                    /*=====================expense===============================*/
                    $this->arr_all_calculate['amount'][]            = $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period;
                    $this->arr_all_calculate['account_number'][]    = $ExpenseAccount->AccountNumber;
                    $this->arr_all_calculate['BranchCode'][]        = $branch;
                    $this->arr_all_calculate['Acc_Type_Name'][]     = $this->m_period_end->get_account_type($company_code,$ExpenseAccount->AccountNumber,$period_year); 
                   
                    /*==================================== cek debet kredit expense ================================================*/
                    $debet_kredit           = $this->m_account_journal->debet_kredit_profit_loss($AdvanceAccount->Acc_Type_Name,$AdvanceAccount->Sub_Type_Name);
                    /*=================== insert journal voucher balance for advance ============================*/
                    $data_journal_advance       = array(
                            'JVchDate'          => $period_date,
                            'JVchNumber'        => $arr_JVB[$no_array]['JVchNumber'],
                            'JVchDesc'          => '',
                            'JVchAccountNumber' => $AdvanceAccount->AccountNumber,
                            'JVchSaldoDebet'    => 0,
                            'JVchSaldoCredit'   => $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period,
                            'JVchSignStatus'    => 1,
                            'AmountCurrency'    => $payment_per_period,
                            'AppFinished'       => 0,
                            'LastUser'          => $this->session->userdata('username'));

                    //$this->m_period_end->insert_journal_jvb($data_journal_advance);
                    $this->trans_data['advance_payment']['insert_journal_jvb']['data'][] = $data_journal_advance;
                    /*=====================advance===============================*/
                    $this->arr_all_calculate['amount'][]            = bcmul($payment_per_period,-1,20);
                    $this->arr_all_calculate['account_number'][]    = $AdvanceAccount->AccountNumber;
                    $this->arr_all_calculate['BranchCode'][]        = $branch;
                    $this->arr_all_calculate['Acc_Type_Name'][]     = $this->m_period_end->get_account_type($company_code,$AdvanceAccount->AccountNumber,$period_year);

                    /*========================= total detail advance payment =============================*/
                    $this->trans_data['advance_payment']['total_detail'] += 2;
                }
            }else{
                /*========================================= coa expense or advance tidak ditemukan ====================================*/
                 $result['status'] = false;
                 $result['message'] = get_notification('coa_advancepayment_notfound',0);
                 echo json_encode($result);
                 die();
            }

        }

        for($n=0;$n<count($arr_JVB);$n++) {
            /*================================== update group journal voucher balance ======================================*/
            $data_update   = array(
                    'JVchTotalCredit'   => $arr_JVB[$n]['total_payment'],
                    'AppLevel1Status'   => 1,
                    'AppLevel1Code'     => $this->session->userdata('username'),
                    'AppLevel1Date'     => $period_date,
                    'AppLevel2Status'   => 1,
                    'AppLevel2Code'     => $this->session->userdata('username'),
                    'AppLevel2Date'     => $period_date,
                    'TransStatus'       => 2,
                    'AppFinished'       => 1,
                    'LastEdited'        => $this->session->userdata('username'));

            //$this->m_period_end->update_group_jvb($arr_JVB[$n]['JVchNumber'],$data_update);
            $this->trans_data['advance_payment']['update_group_jvb']['data'][]        = $data_update;
            $this->trans_data['advance_payment']['update_group_jvb']['TransNumber'][] = $arr_JVB[$n]['JVchNumber'];

            $this->trans_data['advance_payment']['total_group'] += 1;
        }

        //print_r($this->arr_all_calculate);
        // print_r($this->trans_data['advance_payment']);
        // die();
 
    }



    function calculate_depreciation_fixed_asset($company_code,$department_code,$period_month,$period_year){

        $cek_branch                 = '';
        $arr_JVB                    = [];
        $no_array                   = -1;
        $PeriodEnd                  = $period_year.$period_month;

        $day_month                  = date('t',strtotime($period_year.'-'.$period_month.'-01'));
        $period_date                = date('Y-m-d',strtotime($period_year.'-'.$period_month.'-'.$day_month));

        /*=========================== get fixed asset by branch =============================*/
        $get_fixed_asset            = $this->m_period_end->get_fixed_asset($company_code,$period_date);
        // echo $this->db->last_query();
        // die();

        $this->trans_data['fixed_asset']['total_detail'] = 0;
        $this->trans_data['fixed_asset']['total_group'] = 0;

        foreach($get_fixed_asset as $row){

            $branch                 = $row->BranchCode;
            $prec_date              = $row->ReceiptDate;
            $prec_number            = $row->ReceiptNumber;
            $fixed_asset_type       = $row->FixedAssetType;
            $AssetCode              = $row->AssetCode;
            $ItemAverage            = $row->ItemAverage;
            $payment_period         = $row->PaymentPeriod + 1;
            $payment_per_period     = $row->Payment_per_periode;
            $payment_amount         = bcadd($row->PaymentAmount,$payment_per_period,20);

            $fixed_asset_account    = $this->m_period_end->get_fixed_asset_account($fixed_asset_type);

            if($fixed_asset_account == false){
                /*========================================= coa expense or advance tidak ditemukan ====================================*/
                 $result['status'] = false;
                 $result['message'] = get_notification('coa_fixedasset_notfound',0);
                 echo json_encode($result);
                 die();
            }else{

                $AccumAccount           = $fixed_asset_account->AccumAccountNumber;                   
                $ExpenseAccount         = $fixed_asset_account->ExpenseAccountNumber;

                /*======================== total payment endperiod from journal voucher balance by assetcode ==============================*/
                $total_amount_period    = $this->m_period_end->get_total_amount_period($branch,$AssetCode,$AccumAccount);
                $sisa_amount            = bcsub($ItemAverage,$total_amount_period,20);

                if($sisa_amount > 0){

                    /*========================= update at_pinvdetailrecur ============================*/
                    // $data_update_dep    = array(
                    //         'PaymentAmount'     => $payment_amount,
                    //         'PaymentPeriod'     => $payment_period);

                    // $this->m_period_end->update_inventdetail($prec_number,$AssetCode,$data_update_dep);

                    if($cek_branch == $branch){

                        $arr_JVB[$no_array]['total_payment']    = bcadd($payment_per_period,$arr_JVB[$no_array]['total_payment'],20);

                    }else{

                         //$JVchNumber                           = $this->m_period_end->create_jv_number($period_date,$branch);
                        $ind_jv                                 = $this->single_search_key($branch,$this->arr_jvnumber['BranchCode']);
                        $JVchNumber                             = $this->arr_jvnumber['JVchNumber'][$ind_jv];

                        /*============================== create new JVchNumber untuk selanjutnya ============================*/
                        $jv_number                                          = $this->create_manual_jvnumber($JVchNumber);
                        $this->arr_jvnumber['JVchNumber'][$ind_jv]          = $jv_number;

                        /*========================== insert group journal voucher ================================*/
                        $data_group                 = array(
                                'BranchCode'        => $branch,
                                'JVchDate'          => $period_date,
                                'JVchNumber'        => $JVchNumber,
                                'JVchDesc'          => 'Depreciation fixed Asset',
                                'JVchTotalDebet'    => 0,
                                'JVchTotalCredit'   => 0,
                                'JVchType'          => 0,
                                'TransStatus'       => 6,
                                'AppFinished'       => 0,
                                'CreatedBy'         => $this->session->userdata('username'),
                                'CreatedAt'         => date('Y-m-d H:i:s',strtotime($period_date)),
                                'LastUser'          => $this->session->userdata('username'));

                        //$this->m_period_end->insert_group_jvb($data_group);
                        $this->trans_data['fixed_asset']['insert_group_jvb']['data'][] = $data_group;

                        $cek_branch             = $branch;
                        array_push($arr_JVB,array('JVchNumber' => $JVchNumber,'total_payment' => $payment_per_period));
                        $no_array += 1;
                    }

                    /*================== insert detail journal voucher balance for Debet ============*/
                    $data_detail_debet              = array(
                            'JVchNumber'            => $arr_JVB[$no_array]['JVchNumber'],
                            'JVchAccount'           => $ExpenseAccount,
                            'JVchDebetSaldo'        => $payment_per_period,
                            'JVchCreditSaldo'       => 0,
                            'JVchDetailMemo'        => '',
                            'JVchDetailDept'        => $department_code,
                            'JVchRate'              => 1,
                            'CustomerCode'          => null,
                            'CurrencyCode'          => 'IDR',
                            'VendorCode'            => null,
                            'PeriodEnd'             => $PeriodEnd,
                            'AssetCode'             => $AssetCode,
                            'LastUser'              => $this->session->userdata('username'));

                    //$this->m_period_end->insert_detail_jvb($data_detail_debet);
                     $this->trans_data['fixed_asset']['insert_detail_jvb']['data'][] = $data_detail_debet;

                    /*================== insert detail journal voucher balance for Credit ============*/
                    $data_detail_credit             = array(
                            'JVchNumber'            => $arr_JVB[$no_array]['JVchNumber'],
                            'JVchAccount'           => $AccumAccount,
                            'JVchDebetSaldo'        => 0,
                            'JVchCreditSaldo'       => $payment_per_period,
                            'JVchDetailMemo'        => '',
                            'JVchDetailDept'        => $department_code,
                            'JVchRate'              => 1,
                            'CustomerCode'          => null,
                            'CurrencyCode'          => 'IDR',
                            'VendorCode'            => null,
                            'PeriodEnd'             => $PeriodEnd,
                            'AssetCode'             => $AssetCode,
                            'LastUser'              => $this->session->userdata('username'));

                    //$this->m_period_end->insert_detail_jvb($data_detail_credit);
                     $this->trans_data['fixed_asset']['insert_detail_jvb']['data'][] = $data_detail_credit;

                    /*=================== insert journal voucher balance for expense ============================*/
                    $data_journal_debet   = array(
                            'JVchDate'          => $period_date,
                            'JVchNumber'        => $arr_JVB[$no_array]['JVchNumber'],
                            'JVchDesc'          => '',
                            'JVchAccountNumber' => $ExpenseAccount,
                            'JVchSaldoDebet'    => $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period,
                            'JVchSaldoCredit'   => 0,
                            'JVchSignStatus'    => 0,
                            'AmountCurrency'    => $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period,
                            'AppFinished'       => 0,
                            'LastUser'          => $this->session->userdata('username'));

                    //$this->m_period_end->insert_journal_jvb($data_journal_debet);
                    $this->trans_data['fixed_asset']['insert_journal_jvb']['data'][] = $data_journal_debet;
                    /*=====================expense===============================*/
                    $this->arr_all_calculate['amount'][]            = $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period;
                    $this->arr_all_calculate['account_number'][]    = $ExpenseAccount;
                    $this->arr_all_calculate['BranchCode'][]        = $branch;
                    $this->arr_all_calculate['Acc_Type_Name'][]     = $this->m_period_end->get_account_type($company_code,$ExpenseAccount,$period_year); 
                    /*=================== insert journal voucher balance for advance ============================*/
                    $data_journal_credit        = array(
                            'JVchDate'          => $period_date,
                            'JVchNumber'        => $arr_JVB[$no_array]['JVchNumber'],
                            'JVchDesc'          => '',
                            'JVchAccountNumber' => $AccumAccount,
                            'JVchSaldoDebet'    => 0,
                            'JVchSaldoCredit'   => $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period,
                            'JVchSignStatus'    => 0,
                            'AmountCurrency'    => $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period,
                            'AppFinished'       => 0,
                            'LastUser'          => $this->session->userdata('username'));

                    //$this->m_period_end->insert_journal_jvb($data_journal_credit);
                    $this->trans_data['fixed_asset']['insert_journal_jvb']['data'][] = $data_journal_credit;
                    /*=====================Accumulasi===============================*/
                    $this->arr_all_calculate['amount'][]            = $payment_per_period < 0 ? bcmul($payment_per_period,-1,20):$payment_per_period;
                    $this->arr_all_calculate['account_number'][]    = $AccumAccount;
                    $this->arr_all_calculate['BranchCode'][]        = $branch;
                    $this->arr_all_calculate['Acc_Type_Name'][]     = $this->m_period_end->get_account_type($company_code,$AccumAccount,$period_year); 
                    /*========================= total detail advance payment =============================*/
                    $this->trans_data['fixed_asset']['total_detail'] += 2;

                }

            }
        }

        for($n=0;$n<count($arr_JVB);$n++){
            /*================================== update group journal voucher balance ======================================*/
            $data_update   = array(
                    'JVchTotalCredit'   => $arr_JVB[$n]['total_payment'],
                    'AppLevel1Status'   => 1,
                    'AppLevel1Code'     => $this->session->userdata('username'),
                    'AppLevel1Date'     => $period_date,
                    'AppLevel2Status'   => 1,
                    'AppLevel2Code'     => $this->session->userdata('username'),
                    'AppLevel2Date'     => $period_date,
                    'TransStatus'       => 2,
                    'AppFinished'       => 1,
                    'LastEdited'        => $this->session->userdata('username'));

            // $this->m_period_end->update_group_jvb($arr_JVB[$n]['JVchNumber'],$data_update);
            $this->trans_data['fixed_asset']['update_group_jvb']['data'][]        = $data_update;
            $this->trans_data['fixed_asset']['update_group_jvb']['TransNumber'][] = $arr_JVB[$n]['JVchNumber'];

            $this->trans_data['fixed_asset']['total_group'] += 1;
        }

        // print_r($this->arr_all_calculate);
        // print_r($this->trans_data['fixed_asset']);
        // die();
            
    }

    function calculate_profit_lost($company_code,$department_code,$period_month,$period_year){

        $begin_date                 = $period_year.'-'.$period_month.'-01';
        $day_month                  = date('t',strtotime($begin_date));
        $end_date                   = date('Y-m-d',strtotime($period_year.'-'.$period_month.'-'.$day_month));
        $period_date                = date('Y-m-d',strtotime($period_year.'-'.$period_month.'-'.$day_month));
        $PeriodEnd                  = $period_year.$period_month;

        /*============================== get branch by company=============================*/
        $total_pl                   = 0;
        $company_code               = $this->session->userdata('company');
        $branch_ho                  = $this->session->userdata('branch');

        $plus                   = 1;
        $min                    = -1;
        $all_acc_type           = array('Revenue','COGS / COGM (Cost Of Goods Made)','Expense','Other Revenue','Other Expense');
        $arr_revenue            = array();
        $arr_cogm               = array();
        $arr_expense            = array();
        $arr_other_expense      = array();
        $arr_other_revenue      = array();
        $ind_revenue            = -1;
        $ind_cogm               = -1;
        $ind_expense            = -1;
        $ind_other_expense      = -1;
        $ind_other_revenue      = -1;

        $revenue_group          = 0;
        $cogm_group             = 0;
        $expense_group          = 0;
        $other_revenue_group    = 0;
        $other_expense_group    = 0;

        /*======================================= get all transaction with account type revenue ,dll ===========================*/
        $all_transaction        = $this->m_period_end->get_all_transaction_by_date($company_code,$begin_date,$end_date,$all_acc_type);
        //echo $this->db->last_query();

        foreach($all_transaction as $row){
            $Account_Number         = $row->Account_Number;
            $Sub_Type_Name          = $row->Sub_Type_Name;
            $Acc_Type_Name          = $row->Acc_Type_Name;
            $Account_Name           = $row->Account_Name;
            $balance                = $row->balance;
            $type_trans             = $row->type_trans;

            /*============================================= get detail transaction ===============================================*/
            if($Acc_Type_Name == 'Revenue'){

                /*================================== revenue group =================================================*/
                $debet_credit           = $this->m_account_journal->debet_kredit_profit_loss($Acc_Type_Name,$Sub_Type_Name);
                if($debet_credit['plus'] == 'Debet'){
                    $balance            = (($type_trans == 'Debet') and ($debet_credit['position'] == 'Credit'))  ? $balance : bcmul($balance,$min,20);
                }else{
                    $balance            = (($type_trans == 'Credit') and ($debet_credit['position'] == 'Credit')) ? $balance : bcmul($balance,$min,20);
                }

                if($Sub_Type_Name =='Retur Penjualan'){
                    $revenue_group          = bcsub($revenue_group,$balance,20);
                }else{
                    $revenue_group          = bcadd($revenue_group,$balance,20);
                }
                /*==================================================================================================*/

            }elseif($Acc_Type_Name == 'COGS / COGM (Cost Of Goods Made)'){

                /*================================== cogm group =================================================*/
                $debet_credit           = $this->m_account_journal->debet_kredit_profit_loss($Acc_Type_Name,$Sub_Type_Name);
                if($debet_credit['plus'] == 'Debet'){
                    $balance            = (($type_trans == 'Debet') and ($debet_credit['position'] == 'Credit'))  ? $balance : bcmul($balance,$min,20);
                }else{
                    $balance            = (($type_trans == 'Credit') and ($debet_credit['position'] == 'Credit')) ? $balance : bcmul($balance,$min,20);
                }

                $cogm_group          = bcadd($cogm_group,$balance,20);
                /*==================================================================================================*/

            }elseif($Acc_Type_Name == 'Expense'){

                /*================================== expense group =================================================*/
                $debet_credit           = $this->m_account_journal->debet_kredit_profit_loss($Acc_Type_Name,$Sub_Type_Name);
                if($debet_credit['plus'] == 'Debet'){
                    $balance            = (($type_trans == 'Debet') and ($debet_credit['position'] == 'Credit'))  ? $balance : bcmul($balance,$min,20);
                }else{
                    $balance            = (($type_trans == 'Credit') and ($debet_credit['position'] == 'Credit')) ? $balance : bcmul($balance,$min,20);
                }


                $expense_group          = bcadd($expense_group,$balance,20);
                /*==================================================================================================*/
                
            }elseif($Acc_Type_Name == 'Other Revenue'){

                /*================================== other revenue group =================================================*/
                $debet_credit           = $this->m_account_journal->debet_kredit_profit_loss($Acc_Type_Name,$Sub_Type_Name);
                if($debet_credit['plus'] == 'Debet'){
                    $balance            = (($type_trans == 'Debet') and ($debet_credit['position'] == 'Debet'))  ? $balance : bcmul($balance,$min,20);
                }else{
                    $balance            = (($type_trans == 'Credit') and ($debet_credit['position'] == 'Credit')) ? $balance : bcmul($balance,$min,20);
                }

                $other_revenue_group          = bcadd($other_revenue_group,$balance,20);
                /*==================================================================================================*/
                
            }elseif($Acc_Type_Name == 'Other Expense'){

                /*================================== other expense group =================================================*/
                $debet_credit           = $this->m_account_journal->debet_kredit_profit_loss($Acc_Type_Name,$Sub_Type_Name);
                if($debet_credit['plus'] == 'Debet'){
                    $balance            = (($type_trans == 'Debet') and ($debet_credit['position'] == 'Credit'))  ? $balance : bcmul($balance,$min,20);
                }else{
                    $balance            = (($type_trans == 'Credit') and ($debet_credit['position'] == 'Credit')) ? $balance : bcmul($balance,$min,20);
                }

                $other_expense_group          = bcadd($other_expense_group,$balance,20);
                /*==================================================================================================*/
            }

        }
    
        /*=================================================== end get detail transaction =======================================================*/
        
        /*====================== akumulasi amount dari caluculasi selisih kurs, advance payment, dan fixed asset ==========================================*/
        if(count($this->arr_all_calculate)>0){
            for($x=0;$x<count($this->arr_all_calculate['Acc_Type_Name']);$x++){
                if($this->arr_all_calculate['Acc_Type_Name'][$x]=='Revenue'){
                    $revenue_group          = bcadd($revenue_group,$this->arr_all_calculate['amount'][$x],20);
                    //echo 'Revenue : '.$this->arr_all_calculate['amount'][$x].'-----';
                }elseif($this->arr_all_calculate['Acc_Type_Name'][$x]=='COGS / COGM (Cost Of Goods Made)'){
                    $cogm_group             = bcadd($cogm_group,$this->arr_all_calculate['amount'][$x],20);
                    //echo 'cogm : '.$this->arr_all_calculate['amount'][$x].'-----';
                }elseif($this->arr_all_calculate['Acc_Type_Name'][$x]=='Expense'){
                    $expense_group          = bcadd($expense_group,$this->arr_all_calculate['amount'][$x],20);
                    //echo 'expense : '.$this->arr_all_calculate['amount'][$x].'-----';
                }elseif($this->arr_all_calculate['Acc_Type_Name'][$x]=='Other Revenue'){
                    $other_revenue_group    = bcadd($other_revenue_group,$this->arr_all_calculate['amount'][$x],20);
                    //echo 'Other Revenue : '.$this->arr_all_calculate['amount'][$x].'-----';
                }elseif($this->arr_all_calculate['Acc_Type_Name'][$x]=='Other Expense'){
                    $other_expense_group    = bcadd($other_expense_group,$this->arr_all_calculate['amount'][$x],20);
                    //echo 'Other Expense : '.$this->arr_all_calculate['amount'][$x].'-----';
                }
            }
        }

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

        $total_pl                           = bcsub($revenue_group,$cogm_group,20);
        $total_pl                           = bcsub($total_pl,$expense_group,20);
        $total_pl                           = bcadd($total_pl,$other_revenue_group,20);
        $total_pl                           = bcsub($total_pl,$other_expense_group,20);

        // echo 'Total PL '.$total_pl.' ';

        $ind_jv                             = $this->single_search_key($branch_ho,$this->arr_jvnumber['BranchCode']);
        $JVchNumber                         = $this->arr_jvnumber['JVchNumber'][$ind_jv];

        if($period_month == 1){

            $month_before                   = 12;
            $year                           = $period_year - 1;

            /*============================================== get laba rugi di tahan ===============================================*/
            $laba_rugi_ditahan              = $this->m_period_end->get_laba_rugi_ditahan($company_code,$year,'Laba (Rugi) Ditahan');

            /*============================================== get laba rugi berjalan ================================================*/
            $laba_rugi_berjalan             = $this->m_period_end->get_laba_rugi_berjalan($company_code,$month_before,$year,'Laba (Rugi) Berjalan');          
            
            /*============================================== get laba rugi bulan berjalan ================================================*/
            $laba_rugi_bulan_berjalan       = $this->m_period_end->get_laba_rugi_bulan_berjalan($company_code,$month_before,$year,'Laba (Rugi) Bulan Berjalan');

            $total_laba_rugi_berjalan       = bcadd($laba_rugi_berjalan->balance,$laba_rugi_bulan_berjalan->balance,20);

            $total_laba_rugi_ditahan        = bcadd($laba_rugi_ditahan->balance,$total_laba_rugi_berjalan,20);

            $total_debet                    = $total_laba_rugi_ditahan;


        }else{

            $month_before                   = $period_month - 1;
            $year                           = $period_year - 1;

            /*============================================== get laba rugi di tahan ===============================================*/
            $laba_rugi_ditahan              = $this->m_period_end->get_laba_rugi_ditahan($company_code,$year,'Laba (Rugi) Ditahan');

            /*============================================== get laba rugi berjalan ================================================*/
            $laba_rugi_berjalan             = $this->m_period_end->get_laba_rugi_berjalan($company_code,$month_before,$period_year,'Laba (Rugi) Berjalan');

            /*============================================== get laba rugi bulan berjalan ================================================*/
            $laba_rugi_bulan_berjalan       = $this->m_period_end->get_laba_rugi_bulan_berjalan($company_code,$month_before,$period_year,'Laba (Rugi) Bulan Berjalan');


            $total_laba_rugi_berjalan       = bcadd($laba_rugi_berjalan->balance,$laba_rugi_bulan_berjalan->balance,20);

            $total_laba_rugi_ditahan        = $laba_rugi_ditahan->balance;

            $total_debet                    = bcadd($total_laba_rugi_berjalan,$total_pl,20);

        }

        /*========================== insert group journal voucher ================================*/
        $data_group                 = array(
                'BranchCode'        => $branch_ho,
                'JVchDate'          => $period_date,
                'JVchNumber'        => $JVchNumber,
                'JVchDesc'          => '',
                'JVchTotalDebet'    => $total_debet <= 0 ? abs($total_debet):0,
                'JVchTotalCredit'   => $total_debet >= 0 ? abs($total_debet):0,
                'JVchType'          => 0,
                'TransStatus'       => 6,
                'AppFinished'       => 0,
                'CreatedBy'         => $this->session->userdata('username'),
                'CreatedAt'         => $period_date,
                'LastUser'          => $this->session->userdata('username'));

        //$this->m_period_end->insert_group_jvb($data_group);
        $this->trans_data['profit_lost']['insert_group_jvb']['data'] = $data_group;

        /*================== insert detail journal voucher balance for laba rugi bulan berjalan============*/
        $data_detail                = array(
                'JVchNumber'        => $JVchNumber,
                'JVchAccount'       => $laba_rugi_bulan_berjalan->AccountNumber,
                'JVchDebetSaldo'    => $total_pl <= 0 ? abs($total_pl) : 0,
                'JVchCreditSaldo'   => $total_pl >= 0 ? abs($total_pl) : 0,
                'JVchDetailMemo'    => '',
                'JVchRate'          => 1,
                'CurrencyCode'      => 'IDR',
                'JVchDetailDept'    => $department_code,
                'ReconcileStatus'   => 1,
                'PeriodEnd'         => $PeriodEnd,
                'LastUser'          => $this->session->userdata('username'));

        //$this->m_period_end->insert_detail_jvb($data_detail);
        $this->trans_data['profit_lost']['insert_detail_jvb']['data'][] = $data_detail;

        /*=================== insert journal voucher balance for laba rugi bulan berjalan ============================*/
        $data_journal       = array(
                'JVchDate'          => $period_date,
                'JVchNumber'        => $JVchNumber,
                'JVchDesc'          => '',
                'JVchAccountNumber' => $laba_rugi_bulan_berjalan->AccountNumber,
                'JVchSaldoDebet'    => $total_pl <= 0 ? bcmul($total_pl,-1,20) : 0,
                'JVchSaldoCredit'   => $total_pl >= 0 ? $total_pl : 0,
                'JVchSignStatus'    => $total_pl > 0 ? 0 : 1,
                'AmountCurrency'    => $total_pl <= 0 ? bcmul($total_pl,-1,20) : $total_pl,
                'AppFinished'       => 0,
                'LastUser'          => $this->session->userdata('username'));

        //$this->m_period_end->insert_journal_jvb($data_journal);
        $this->trans_data['profit_lost']['insert_journal_jvb']['data'][] = $data_journal;

        $this->arr_pp['amount'][]            = $total_pl;
        $this->arr_pp['account_number'][]    = $laba_rugi_bulan_berjalan->AccountNumber; 
        $this->arr_pp['BranchCode'][]        = $branch_ho;
        $this->arr_pp['Acc_Type_Name'][]     = $this->m_period_end->get_account_type($company_code,$laba_rugi_bulan_berjalan->AccountNumber,$period_year); 


        /*===================================== jika ini end period akhir tahun ===============================*/
        if($period_month == 1){

            /*================== insert detail journal voucher balance for laba rugi ditahan============*/
            $data_detail                = array(
                    'JVchNumber'        => $JVchNumber,
                    'JVchAccount'       => $laba_rugi_ditahan->AccountNumber,
                    'JVchDebetSaldo'    => $total_laba_rugi_ditahan <= 0 ? abs($total_laba_rugi_ditahan) : 0,
                    'JVchCreditSaldo'   => $total_laba_rugi_ditahan >= 0 ? abs($total_laba_rugi_ditahan) : 0,
                    'JVchDetailMemo'    => '',
                    'JVchRate'          => 1,
                    'CurrencyCode'      => 'IDR',
                    'JVchDetailDept'    => $department_code,
                    'ReconcileStatus'   => 1,
                    'PeriodEnd'         => $PeriodEnd,
                    'LastUser'          => $this->session->userdata('username'));

            //$this->m_period_end->insert_detail_jvb($data_detail);
            $this->trans_data['profit_lost']['insert_detail_jvb']['data'][] = $data_detail;

            /*=================== insert journal voucher balance for laba rugi ditahan ============================*/
            $data_journal      = array(
                    'JVchDate'          => $period_date,
                    'JVchNumber'        => $JVchNumber,
                    'JVchDesc'          => '',
                    'JVchAccountNumber' => $laba_rugi_ditahan->AccountNumber,
                    'JVchSaldoDebet'    => $total_laba_rugi_ditahan <= 0 ? bcmul($total_laba_rugi_ditahan,-1,20) : 0,
                    'JVchSaldoCredit'   => $total_laba_rugi_ditahan >= 0 ? $total_laba_rugi_ditahan: 0,
                    'JVchSignStatus'    => $total_laba_rugi_ditahan > 0 ? 0 : 1,
                    'AmountCurrency'    => $total_laba_rugi_ditahan <= 0 ? bcmul($total_laba_rugi_ditahan,-1,20) : $total_laba_rugi_ditahan,
                    'AppFinished'       => 0,
                    'LastUser'          => $this->session->userdata('username'));

            //$this->m_period_end->insert_journal_jvb($data_journal);
            $this->trans_data['profit_lost']['insert_journal_jvb']['data'][] = $data_journal;

            $this->arr_all_calculate['amount'][]            = $total_laba_rugi_berjalan;
            $this->arr_all_calculate['account_number'][]    = $laba_rugi_ditahan->AccountNumber; 
            $this->arr_all_calculate['BranchCode'][]        = $branch_ho;
            $this->arr_all_calculate['Acc_Type_Name'][]     = $this->m_period_end->get_account_type($company_code,$laba_rugi_ditahan->AccountNumber,$period_year); 
        
        }else{

            /*================== insert detail journal voucher balance for laba rugi berjalan============*/
            $data_detail                = array(
                    'JVchNumber'        => $JVchNumber,
                    'JVchAccount'       => $laba_rugi_berjalan->AccountNumber,
                    'JVchDebetSaldo'    => $total_laba_rugi_berjalan <= 0 ? abs($total_laba_rugi_berjalan) : 0,
                    'JVchCreditSaldo'   => $total_laba_rugi_berjalan >= 0 ? abs($total_laba_rugi_berjalan) : 0,
                    'JVchDetailMemo'    => '',
                    'JVchRate'          => 1,
                    'CurrencyCode'      => 'IDR',
                    'JVchDetailDept'    => $department_code,
                    'ReconcileStatus'   => 1,
                    'PeriodEnd'         => $PeriodEnd,
                    'LastUser'          => $this->session->userdata('username'));

            //$this->m_period_end->insert_detail_jvb($data_detail);
            $this->trans_data['profit_lost']['insert_detail_jvb']['data'][] = $data_detail;

            /*=================== insert journal voucher balance for laba rugi berjalan ============================*/
            $data_journal       = array(
                    'JVchDate'          => $period_date,
                    'JVchNumber'        => $JVchNumber,
                    'JVchDesc'          => '',
                    'JVchAccountNumber' => $laba_rugi_berjalan->AccountNumber,
                    'JVchSaldoDebet'    => $total_laba_rugi_berjalan <= 0 ? bcmul($total_laba_rugi_berjalan,-1,20) : 0,
                    'JVchSaldoCredit'   => $total_laba_rugi_berjalan >= 0 ? $total_laba_rugi_berjalan : 0,
                    'JVchSignStatus'    => $total_laba_rugi_berjalan > 0 ? 0 : 1,
                    'AmountCurrency'    => $total_laba_rugi_berjalan <= 0 ? bcmul($total_laba_rugi_berjalan,-1,20) : $total_laba_rugi_berjalan,
                    'AppFinished'       => 0,
                    'LastUser'          => $this->session->userdata('username'));

            //$this->m_period_end->insert_journal_jvb($data_journal);
            $this->trans_data['profit_lost']['insert_journal_jvb']['data'][] = $data_journal;

            $this->arr_all_calculate['amount'][]            = $laba_rugi_bulan_berjalan->balance;
            $this->arr_all_calculate['account_number'][]    = $laba_rugi_berjalan->AccountNumber; 
            $this->arr_all_calculate['BranchCode'][]        = $branch_ho;
            $this->arr_all_calculate['Acc_Type_Name'][]     = $this->m_period_end->get_account_type($company_code,$laba_rugi_berjalan->AccountNumber,$period_year); 

        }

        /*==================================update group journal voucher =========================================*/    
        $data_update   = array(
                    'AppLevel1Status'   => 1,
                    'AppLevel1Code'     => $this->session->userdata('username'),
                    'AppLevel1Date'     => $period_date,
                    'AppLevel2Status'   => 1,
                    'AppLevel2Code'     => $this->session->userdata('username'),
                    'AppLevel2Date'     => $period_date,
                    'TransStatus'       => 2,
                    'AppFinished'       => 1,
                    'LastEdited'        => $this->session->userdata('username'));

        //$this->m_period_end->update_group_jvb($JVchNumber,$data_update);
        $this->trans_data['profit_lost']['update_group_jvb']['data']           = $data_update;
        $this->trans_data['profit_lost']['update_group_jvb']['TransNumber']    = $JVchNumber;
    }

    function recalculate_coa($company_code,$period_date,$period_year,$period_month,$last_endperiod){

        $return             = 0;
        $arr_return         = array();

        if($period_month == 12){
            $year_before    = $period_year;
            $month_before   = abs($period_month);

            $year_after     = $period_year + 1;
            $month_after    = 1;
            // $year_after         = date('Y');
            // $month_after        = abs(date('m'));

        }else{
            $year_before    = $period_year;
            $month_before   = abs($period_month);

            $year_after     = $period_year;
            $month_after    = abs($period_month) + 1;
            // $year_after         = date('Y');
            // $month_after        = abs(date('m'));
        }

        /*=================================== get all account bsstatus = 1 =============================================*/
        $account_gl                 = $this->m_period_end->get_account_by_bsstatus($company_code,$period_month,$period_year,1,$last_endperiod);

        /*========================== filter tgl transaksi bulan endperiod ===============================*/
        $before_from_date           = $year_before.'-'.$month_before.'-01';
        $day_month                  = date('t',strtotime($before_from_date));
        $before_end_date            = $year_before.'-'.$month_before.'-'.$day_month;
        /*========================== end filter ==========================================================*/

        /*================================= filter tgl transaksi bulan setelah end period ======================*/
        $after_from_date            = $year_after.'-'.$month_after.'-01';
        $after_end_date             = date('Y-m-d');
        $year_coa_after             = date('Y');
        /*================================= end after filter ====================================================*/

        /*=========================================== get first balance and last balance ==============================================================*/
        $before_transaction_period  = $this->m_period_end->get_all_transaction_by_bsstatus($company_code,$before_from_date,$before_end_date,1);
        
        $after_transaction_period   = $this->m_period_end->get_all_transaction_by_bsstatus($company_code,$after_from_date,$after_end_date,1); 

        /*=============== Khusus end Period bulan 1 ==========================*/
        if($period_month == 1){
            $year_before = $period_year - 1;
        }

        /*================================== grouping array before transaction ========================================*/
        $arr_before     = array();
        foreach($before_transaction_period as $row){
            $account_number = $row->Account_Number;
            $AmountCurrency = $row->Amount_Currency;
            $branch         = $row->Branch_Code;
            $trans_type     = $row->Trans_Type;
            $rate           = $row->CurrencyRate;
            $Acc_Type_Name  = $row->Acc_Type_Name;
            $Sub_Type_Name  = $row->Sub_Type_Name;
            $pos_trans      = $row->Debet_Credit;

            /*================ check credit or debet ======================*/

            $debet_kredit   = $this->m_account_journal->debet_kredit_profit_loss($Acc_Type_Name,$Sub_Type_Name);

            if($debet_kredit['plus'] == 'Credit'){
                if($pos_trans == 'Credit'){
                    $AmountCurrency = $AmountCurrency;
                }else{
                    $AmountCurrency = bcmul($AmountCurrency,-1,20);
                } 
            }else{
               if($pos_trans == 'Debet'){
                    $AmountCurrency = $AmountCurrency;
                }else{
                    $AmountCurrency = bcmul($AmountCurrency,-1,20);
                }  
            }
            
            if(count($arr_before) == 0){
                array_push($arr_before,array('branch'=>$branch,'account_number'=> $account_number,'amount_currency'=> $AmountCurrency));
            }else{

                $key    = $this->search_key($branch,'branch',$account_number,'account_number',$arr_before);
                if($key === FALSE){
                    array_push($arr_before,array('branch'=>$branch,'account_number'=> $account_number,'amount_currency'=> $AmountCurrency));
                }else{
                    $arr_before[$key]['amount_currency'] = bcadd($arr_before[$key]['amount_currency'],$AmountCurrency,20);
                }
            }
        }

        /*================================== grouping array after transaction ========================================*/
        $arr_after     = array();
        foreach($after_transaction_period as $row){
            $account_number = $row->Account_Number;
            $AmountCurrency = $row->Amount_Currency;
            $branch         = $row->Branch_Code;
            $trans_type     = $row->Trans_Type;
            $rate           = $row->CurrencyRate;
            $Acc_Type_Name  = $row->Acc_Type_Name;
            $Sub_Type_Name  = $row->Sub_Type_Name;
            $pos_trans      = $row->Debet_Credit;


            /*================ check credit or debet ======================*/
            $debet_kredit   = $this->m_account_journal->debet_kredit_profit_loss($Acc_Type_Name,$Sub_Type_Name);

            if($debet_kredit['plus'] == 'Credit'){
                if($pos_trans == 'Credit'){
                    $AmountCurrency = $AmountCurrency;
                }else{
                    $AmountCurrency = bcmul($AmountCurrency,-1,20);
                } 
            }else{
               if($pos_trans == 'Debet'){
                    $AmountCurrency = $AmountCurrency;
                }else{
                    $AmountCurrency = bcmul($AmountCurrency,-1,20);
                }  
            }
            

            if(count($arr_after) == 0){
                array_push($arr_after,array('branch'=>$branch,'account_number'=> $account_number,'amount_currency'=> $AmountCurrency));
            }else{

                $key    = $this->search_key($branch,'branch',$account_number,'account_number',$arr_after);
                if($key === FALSE){
                    array_push($arr_after,array('branch'=>$branch,'account_number'=> $account_number,'amount_currency'=> $AmountCurrency));
                }else{
                    $arr_after[$key]['amount_currency'] = bcadd($arr_after[$key]['amount_currency'],$AmountCurrency,20);
                }
            }
        }


        $total_before   = count($arr_before);
        $total_after    = count($arr_after);
        $total_account  = count($account_gl);

        /*=================================== total balance account before ================================*/
        for($i=0;$i<$total_before;$i++){

            $branch                 = $arr_before[$i]['branch'];
            $account_number         = $arr_before[$i]['account_number'];
            $amount_before          = $arr_before[$i]['amount_currency'];

            $key_before                    = $this->search_key_year($branch,'BranchCode',$account_number,'AccountNumber',$year_before,'GLSaldoYears',$account_gl);
            $balancesheet_bank_before      = $account_gl[$key_before]['BankBalance'];
            $saldo_balance_bank_before     = $account_gl[$key_before]['GLSaldoBalance'];
            $opening_balance_bank_before   = $account_gl[$key_before]['GLSaldoOpening'];

            $key_after                    = $this->search_key_year($branch,'BranchCode',$account_number,'AccountNumber',$year_coa_after,'GLSaldoYears',$account_gl);
            $balancesheet_bank_after      = $account_gl[$key_after]['BankBalance'];
            $saldo_balance_bank_after     = $account_gl[$key_after]['GLSaldoBalance'];
            $opening_balance_bank_after   = $account_gl[$key_after]['GLSaldoOpening'];

            $key_aft              = $this->search_key($branch,'branch',$account_number,'account_number',$arr_after);

            $amount_after           = 0;

            if($key_aft === false){

            }else{

                $amount_after       = $arr_after[$key_aft]['amount_currency'];
                $amount             = $arr_after[$key_aft]['amount_currency'];
            }

            if($last_endperiod == false){
                $balance_before     = bcadd($opening_balance_bank_before,$amount_before,20);
            }else{
                $balance_before     = bcadd($saldo_balance_bank_before,$amount_before,20);
            }

            $balance_after          = bcsub($balancesheet_bank_after,$amount_after,20);

            $calculate_balance      = bcsub($balance_before,$balance_after,20);
            $calculate_balance      = round(abs($calculate_balance),4);

            if($calculate_balance > 0){

                $arr_err = array();
                array_push($arr_err,array('branch' => $branch,
                                        'Account' => $account_number,
                                        'calculate_balance'  => $calculate_balance));
                $result['arr_err']      = $arr_err;
                $result['return']       = 1;
                return $result;

            }else{
               
            }

            // array_push($arr_return,array('branch' => $branch,
            //                             'Account' => $account_number,
            //                             'balance'  => $balance_before,
            //                             'after'   => $balance_after,
            //                             'proses_after'=>$balancesheet_bank_after .'-'.$amount_after,
            //                             'proses_before'=>$saldo_balance_bank_before.' + '.$amount_before,
            //                             'key_after'=>$key_aft,
            //                             'amount'=>$key_aft === false ? $key_aft:$amount,
            //                             ));

             array_push($arr_return,array('branch' => $branch,
                                        'Account' => $account_number,
                                        'balance'  => $balance_before));
        }

        /*=================================== total balance account after ================================*/
        for($i=0;$i<$total_after;$i++){

            $branch                 = $arr_after[$i]['branch'];
            $account_number         = $arr_after[$i]['account_number'];
            $amount_after           = $arr_after[$i]['amount_currency'];

            $key_before                    = $this->search_key_year($branch,'BranchCode',$account_number,'AccountNumber',$year_before,'GLSaldoYears',$account_gl);
            $balancesheet_bank_before      = $account_gl[$key_before]['BankBalance'];
            $saldo_balance_bank_before     = $account_gl[$key_before]['GLSaldoBalance'];
            $opening_balance_bank_before   = $account_gl[$key_before]['GLSaldoOpening'];

            $key_after                    = $this->search_key_year($branch,'BranchCode',$account_number,'AccountNumber',$year_coa_after,'GLSaldoYears',$account_gl);
            $balancesheet_bank_after      = $account_gl[$key_after]['BankBalance'];
            $saldo_balance_bank_after     = $account_gl[$key_after]['GLSaldoBalance'];
            $opening_balance_bank_after   = $account_gl[$key_after]['GLSaldoOpening'];

            $key_bef                      = $this->search_key($branch,'branch',$account_number,'account_number',$arr_before);

            $amount_before          = 0; 

            if($key_bef === false){
                
            }else{
                $amount_before       = $arr_before[$key_bef]['amount_currency'];
                $amount              = $arr_before[$key_bef]['amount_currency'];
            }

            if($last_endperiod == false){
                $balance_before     = bcadd($opening_balance_bank_before,$amount_before,20);
            }else{
                $balance_before     = bcadd($saldo_balance_bank_before,$amount_before,20);
            }

            $balance_after          = bcsub($balancesheet_bank_after,$amount_after,20);

            $calculate_balance      = bcsub($balance_before,$balance_after,20);
            $calculate_balance      = round(abs($calculate_balance),4);

            if($calculate_balance > 0){
                $arr_err = array();
                array_push($arr_err,array('branch' => $branch,
                                        'Account' => $account_number,
                                        'calculate_balance'  => $calculate_balance));
                $result['arr_err']      = $arr_err;
                $result['return']       = 1;
                return $result;
            }else{
            
            }

            // array_push($arr_return,array('branch' => $branch,
            //                             'Account' => $account_number,
            //                             'before'  => $balance_before,
            //                             'balance'   => $balance_after,
            //                             'proses_after'=>$balancesheet_bank_after .'-'.$amount_after,
            //                             'proses_before'=>$saldo_balance_bank_before .'+'.$amount_before,
            //                             'key_before'=>$key_bef,
            //                             'amount'=>$key_bef === false ?$key_bef:$amount,
            //                             ));

             array_push($arr_return,array('branch' => $branch,
                                            'Account' => $account_number,
                                            'balance'  => $balance_before));
        }

        $arr_account = array();
        $ind_account = 0;
        $total_asset   = 0;
        for($x=0;$x<$total_account;$x++){

            if($account_gl[$x]['GLSaldoYears'] == $year_before){

                $BranchCode                 = $account_gl[$x]['BranchCode'];
                $AccountNumber              = $account_gl[$x]['AccountNumber'];
                $balancesheet_account       = $account_gl[$x]['BankBalance'];
                $saldo_balance_account      = $account_gl[$x]['GLSaldoBalance'];
                $opening_balance_account    = $account_gl[$x]['GLSaldoOpening'];
                $CurrencyCode               = $account_gl[$x]['CurrencyCode'];
                $SubTypeName                = $account_gl[$x]['Sub_Type_Name'];

                $key_balance                = $this->search_key($BranchCode,'branch',$AccountNumber,'Account',$arr_return);

                if($key_balance === false){
                    if($last_endperiod === false){
                        $balance    = $opening_balance_account;
                    }else{
                        $balance    = $saldo_balance_account;
                    }
                }else{
                    $balance    = $arr_return[$key_balance]['balance'];
                }

                $arr_account[$ind_account]  = array(
                                            'BranchCode'    =>  $BranchCode,
                                            'AccountNumber' =>  $AccountNumber,
                                            'balance'       =>  $balance,
                                            'CurrencyCode'  =>  $CurrencyCode,
                                            'SubTypeName'   =>  $SubTypeName);
                $ind_account++;
            }
        }

        $result['arr_account']  = $arr_account;
        $result['arr_return']   = $arr_return;
        $result['return']       = $return;
        // echo json_encode($arr_return);
        // die();
        return $result;

    }

    function create_new_balancesheet($company_code,$arr_account,$period_month,$period_year){

        for($x=0;$x<count($arr_account);$x++){

            $branch         = $arr_account[$x]['BranchCode'];
            $account        = $arr_account[$x]['AccountNumber'];
            $CurrencyCode   = $arr_account[$x]['CurrencyCode'];
            $balance        = $arr_account[$x]['balance'];
            $SubTypeName    = $arr_account[$x]['SubTypeName'];

            if($period_month == 1){
                if($SubTypeName == 'Laba (Rugi) Berjalan'){

                }else{

                    /*====================== akumulasi amount dari caluculasi selisih kurs, advance payment, dan fixed asset ============================*/
                    if(count($this->arr_all_calculate)>0){
                        for($i=0;$i<count($this->arr_all_calculate['account_number']);$i++){
                            if($this->arr_all_calculate['BranchCode'][$i]==$branch){
                                if($this->arr_all_calculate['account_number'][$i]==$account){
                                    $balance        = bcadd($balance,$this->arr_all_calculate['amount'][$i],20);
                                }
                            }
                        }
                    }
                    /*=========================================================================end =============================================*/

                    //$this->m_period_end->update_gl_saldo_balance($branch,$account,$balance,$period_month,$period_year);
                    $this->trans_data['new_balancesheet']['branch'][]        = $branch;
                    $this->trans_data['new_balancesheet']['account'][]       = $account;
                    $this->trans_data['new_balancesheet']['CurrencyCode'][]  = $CurrencyCode;
                    $this->trans_data['new_balancesheet']['balance'][]       = $balance;
                    $this->trans_data['new_balancesheet']['period_month'][]  = $period_month;
                    $this->trans_data['new_balancesheet']['period_year'][]   = $period_year;
                }

            }else{

                /*====================== akumulasi amount dari caluculasi selisih kurs, advance payment, dan fixed asset ============================*/
                if(count($this->arr_all_calculate)>0){
                    for($i=0;$i<count($this->arr_all_calculate['account_number']);$i++){
                        if($this->arr_all_calculate['BranchCode'][$i]==$branch){
                            if($this->arr_all_calculate['account_number'][$i]==$account){
                                $balance        = bcadd($balance,$this->arr_all_calculate['amount'][$i],20);
                            }
                        }
                    }
                }

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

                //$this->m_period_end->update_gl_saldo_balance($branch,$account,$balance,$period_month,$period_year);
                $this->trans_data['new_balancesheet']['branch'][]        = $branch;
                $this->trans_data['new_balancesheet']['account'][]       = $account;
                $this->trans_data['new_balancesheet']['CurrencyCode'][]  = $CurrencyCode;
                $this->trans_data['new_balancesheet']['balance'][]       = $balance;
                $this->trans_data['new_balancesheet']['period_month'][]  = $period_month;
                $this->trans_data['new_balancesheet']['period_year'][]   = $period_year;
            }
        }

    }

    function checking_balancesheet($detail){
        $total_asset        = 0;
        $total_liability    = 0;

        for($i=0;$i<count($this->trans_data['new_balancesheet']['account']);$i++){
            $Type = $this->m_account_journal->m_get_account_type($this->trans_data['new_balancesheet']['account'][$i],$this->trans_data['new_balancesheet']['branch'][$i]);
            if(in_array($Type->Type_Name, array('Account Receivable','Accumulated Depreciation Fixed Asset','Assets','Cash / Bank','Fixed Asset','Inventory','Other Current Asset'))){
                if($Type->Type_Name=='Accumulated Depreciation Fixed Asset'){
                    $total_asset = bcsub($total_asset,$this->trans_data['new_balancesheet']['balance'][$i],20);
                }elseif($Type->Type_Name=='Cash / Bank'){
                    foreach($detail as $row){
                        $currency_code  = $row->CurrencyCode;
                        $currency_rate  = $row->CurrencyRate;
                        if($this->trans_data['new_balancesheet']['CurrencyCode'][$i] == $currency_code){
                             $total_asset = bcadd($total_asset,(bcmul($this->trans_data['new_balancesheet']['balance'][$i],$currency_rate,20)),20);
                        }
                    }
                }else{
                    $total_asset = bcadd($total_asset,$this->trans_data['new_balancesheet']['balance'][$i],20);
                }
            }elseif(in_array($Type->Type_Name, array('Account Payable','Equity','Long Term Liability','Other Current Liability'))){
                if($Type->Type_Name=='Equity'){
                    if($Type->Sub_Type_Name == 'Dividen'){
                        $total_liability = bcsub($total_liability,$this->trans_data['new_balancesheet']['balance'][$i],20);
                    }else{
                        $total_liability = bcadd($total_liability,$this->trans_data['new_balancesheet']['balance'][$i],20);
                    }
                }else{
                    $total_liability = bcadd($total_liability,$this->trans_data['new_balancesheet']['balance'][$i],20);
                }
            }
        }

        if(count($this->arr_pp)>0){
            for($i=0;$i<count($this->arr_pp['amount']);$i++){
                $total_liability        = bcadd($total_liability,$this->arr_pp['amount'][$i],20);
            }
        }

        $total_asset        = (round($total_asset,4));
        $total_liability    = (round($total_liability,4)); 

        $balance            =  bcsub($total_asset,$total_liability);
        // echo $total_asset.' -vs- '.$total_liability;
        // die();

        if($balance == 0){
            return true;
        }else{
            return false;
        }
    }

    function calculate_diff_kurs($first_balance,$last_balance,$last_saldo,$currency_rate,$master_rate){
        $saldo_awal         = $last_balance - $first_balance[0]['Amount_Currency'];
        $saldo_awal_rupiah  = $saldo_awal * $master_rate;
        $saldo_akhir_rupiah = $last_saldo[0]['total_saldo'];
        $total_saldo_rupiah = $saldo_awal_rupiah + $saldo_akhir_rupiah;
        $diff_kurs          = ($last_saldo[0]['Amount_Currency'] * intval($currency_rate)) - $total_saldo_rupiah;

        return $diff_kurs;
    }

    function create_manual_jvnumber($JVchNumber){
        $arr_no             = explode("/", $JVchNumber);
        $no_explode         = $arr_no[2];
        $ordinal_number     = sprintf("%03s",(int)$no_explode+1);
        $transaction_number = $arr_no[0].'/'.$arr_no[1].'/'.$ordinal_number;
        return $transaction_number;
    }

    function reverse_period_end(){
        /*============================ get variabel session ========================================*/
        $company_code       = $this->session->userdata('company');
        $branch_ho_code     = $this->session->userdata('branch');
        $department_code    = $this->session->userdata('department');
        $user_login         = $this->session->userdata("username");

        $detail_post        = $this->input->post('Detail');
        $detail             = json_decode($detail_post);
        $period_date        = date('Y-m-d');

        /*=========================== set periode month, year n desc =======================================*/
        $period_month       = (int)$this->input->post('PeriodMonth');
        $period_year        = (int)$this->input->post('PeriodYear');
        $period_desc        = $this->input->post('Description');
        $period_end         = $period_year.$period_month;
        
        /*=============================== set begin_date and end_date ====================================*/
        $begin_date         = date('Y-m-d H:i:s',strtotime($period_year.'-'.$period_month.'-01 00:00:00'));
        $day_month          = date('t', strtotime($begin_date));
        $end_date           = date('Y-m-d H:i:s',strtotime($period_year.'-'.$period_month.'-'.$day_month.' 23:59:59'));

        /*======================== cek bulan end period harus < bulan sekarang ========================*/
        $cek_period_date    = (int)date('Ym');
        $cek_begin_date     = (int)$period_year.$period_month;

        /*======================= cek apakah bulan sekarang sudah di period end atau belum ===========================*/
        $check_already_period = $this->m_period_end->check_endperiod($period_end);

        /*==================== cek sudah di end period atau belum ==============================*/
        if($check_already_period == false){
            /*============== sudah di period end ======================*/
            $result['status'] = false;
            $result['message'] = get_notification('non_period',0);
            echo json_encode($result);
        }else{
            
            if($period_month == 12){
                $period_month_after     = 1;
                $period_year_after      = $period_year + 1;
                $period_end_after       = $period_year_after.$period_month_after;
            }else{
                $period_month_after     = $period_month + 1;
                $period_year_after      = $period_year;
                $period_end_after       = $period_year_after.$period_month_after;
            }

            /*======================= cek apakah bulan diatasnya sudah di period end atau belum ===========================*/
            $check_already_period = $this->m_period_end->check_endperiod($period_end_after);

            if($check_already_period == true){
                /*============== belum di period end ======================*/
                $result['status']   = false;
                $result['message']  = get_notification('greather_period',0);
                echo json_encode($result);
            }else{

                $PeriodEnd      = $period_year.$period_month;

                /*====================== get all branch by company ========================*/
                $arr_branch         = $this->m_period_end->get_branch($company_code);

                /*====================== get all journal voucher transaction ==============================*/
                $all_jv_transaction = $this->m_period_end->get_all_jv_transaction($company_code,$begin_date,$end_date,0,$PeriodEnd);
                // echo $this->db->last_query();
                // die();
            
                /*================= function suspend journal voucher transaction ===========================*/
                $this->suspend_all_jv_transaction($all_jv_transaction);

                /*========================== update balanceamount menjadi 0 semua accountgl yang bsstatus bukan profit n loss =================================*/
                $this->reverse_balancesheet_amount($arr_branch,$period_month,$period_year);

                /*======================= change master currency ============================*/

                /*======================= get history currency ==============================*/
                $list_currency  = $this->m_period_end->get_history_currency($PeriodEnd,$company_code);

                $this->change_master_currency_rate($list_currency);
                /*===================== End change master currency ===========================================*/

                /*==================== delete history currency ===============================*/
                $this->trans_data['delete_history_currency']['PeriodEnd'] = $PeriodEnd;

                /*==================== delete group period end =======================*/
                $this->trans_data['delete_group']['TransNumber'] = $period_end;

                $result_return = $this->m_period_end->m_reverse_period_end($this->trans_data);

                $this->trans_data = [];

                 if($result_return){
                    $result['status']   = true;
                    $result['message']  = get_notification_transaksi($this->name,'reverse',1,$period_end);
                }else{
                    $result['status']   = false;
                    $result['message']  = get_notification_transaksi($this->name,'reverse',0,$period_end);
                }

                echo json_encode($result);

            }
             /*======================= end cek apakah bulan diatasnya sudah di period end atau belum ===========================*/
        }
        /*==================== end cek sudah di end period atau belum ==============================*/
    }

    function suspend_all_jv_transaction($all_jv_transaction){
        $data_suspend = array('AppFinished'=>0,'TransStatus'=>3);
        $this->trans_data['suspend_jv']['total'] = count($all_jv_transaction);
        foreach($all_jv_transaction as $jv_number){
            $this->trans_data['suspend_jv']['data'][]           = $data_suspend;
            $this->trans_data['suspend_jv']['TransNumber'][]    = $jv_number;
        }
    }

    function reverse_balancesheet_amount($arr_branch,$period_month,$period_year){
        $this->trans_data['reverse_balancesheet']['arr_branch'] = $arr_branch;
        $this->trans_data['reverse_balancesheet']['month']      = $period_month;
        $this->trans_data['reverse_balancesheet']['year']       = $period_year;
    }
    
    public function trans_warning($modus) {
        $result['status']   = false;

        switch($modus){
            case 'status':
                $result['message']  = 'Period End sudah dilakukan untuk Bulan dan Tahun yang dipilih';
                break;
            
            case 'approved':
                $result['message']  = 'Masih terdapat transaksi yang belum di Approval';
                break;
                
            case 'reconcile':
                $result['message']  = 'Masih terdapat transaksi yang belum di Reconcile';
                break;                
        }
        
        echo json_encode($result);                
        die();
    }
    
    public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status']       = false;
        
        if($modus == 'Insert' || $modus == 'Update' || $modus == 'Delete'){
            $result['message']  = get_notification_transaksi($this->name, $modus, 0);
        }
        else{
            $result['message']  = get_notification_transaksi('Akun', 'journal', $modus);                
        }
        
        echo json_encode($result);                
        die();
    }
}