<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/*  Author : Ferry / Tanggal : 15-06-2015	
 *  Revisi : 
 */

class Bank_reconcile extends CI_Controller {

    public $menu_id = 156;
    public $menu_model = array('m_menu', 'm_bank_reconcile', 'file/m_new_company');
    public $name = "Bank Reconcile";
    public $jobtitle_status = array('1');

    public function __construct() {
        parent::__construct();
        $this->load->model($this->menu_model);


        //untuk cek login dan menu apakah bisa diakses oleh user yang login
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);

            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    $this->load->helper('message_helper');
                    $this->load->helper('status');
                    $this->load->helper('convert_date_helper');
                    $this->load->helper('custom_string_helper');
                    $this->load->model('login/m_login');
                    $is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
                    if($is_login){

                    }else{
                        $username       = $this->session->userdata('username');
                        $session_id     = $this->session->userdata('session_id');
                        $this->m_login->delete_session($username,$session_id);
                        $this->session->sess_destroy();

                        $uri_func = $this->uri->segment(3);
                        if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
                            redirect(base_url() . 'login', 'refresh');
                        }else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
                            $result['status']   = 'session';
                            $result['message']  = get_notification('session_destroy',0);
                            echo json_encode($result);
                            die();
                        }
                    }
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    // public function get_last_reconcile_date(){
    //     $account_number = isset($this->input->post('acc_number'))?$this->input->post('acc_number'):null;
    //     $last_date      = $this->m_bank_reconcile->get_last_reconcile_date($account_number);
    // }

    public function index() {
        //untuk ambil data dari session dan hak akses
        $group_menu = $this->session->userdata('group_menu');

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

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

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/bank_reconcile/v_bank_reconcile', $data);
        $this->load->view('v_footer');
    }

    public function add() {
        //untuk ambil data dari session dan hak akses
        $group_menu = $this->session->userdata('group_menu');

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

        //$data['br_number']	= $this->m_bank_reconcile->create_br_number();
        //$data['last_date']  = $this->m_bank_reconcile->get_last_reconcile_date();
        //echo $this->db->last_query();
        //panggil model hak akses untuk autoriti
        $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/bank_reconcile/v_new_bank_reconcile', $data);
        $this->load->view('v_footer');
    }

    public function insert_group($detail, $branch_code, $bank_account, $bren_date, $bren_last_date, $currency_code) {

        foreach ($detail as $row) {

            $TransDate = $row->Trans_Date;
            $TransNumber = $row->Trans_Number;
            $SaldoDebet = $row->Deposit;
            $SaldoCredit = $row->WithDrawal;
            //$Trans_Type         = $row->Trans_Type;

            $ReconcileStatus = ($row->Status_Reconcile) == "Yes" ? 1 : 0;

            $ReconcileBook = ($row->Status_Rebook == "Yes") ? 1 : 0;
            $ReconcileDate = $bren_date;
            $ReconCreatedBy = $this->session->userdata("username");
            $ReconCreatedAt = date("Y-m-d");

            /* ======================= get rate_currency ========================= */
            //$CurrencyRate       = $this->m_bank_reconcile->get_currency_rate($TransNumber,$Trans_Type);

            $data_reconcile = array(
                'BranchCode' => $branch_code,
                'TransDate' => $TransDate,
                'TransNumber' => $TransNumber,
                'BankAccount' => $bank_account,
                'SaldoDebet' => $SaldoDebet,
                'SaldoCredit' => $SaldoCredit,
                'CurrencyRate' => 0,
                'ReconcileStatus' => 0,
                'ReconcileBook' => $ReconcileBook,
                // 'ReconcileDate'         => $ReconcileDate,
                'ReconCreatedBy' => $ReconCreatedBy,
                'ReconCreatedAt' => $ReconCreatedAt,
                'TransStatus' => 4,
                'LastUser' => $this->session->userdata("username")
            );

            /* ========================= cek status insert or not ========================== */
            $cek_status = $this->m_bank_reconcile->cek_status_reconcilebook($TransNumber, $bank_account);

            if ($cek_status == false) {

                if ($ReconcileBook == 1) {
                    $this->m_bank_reconcile->insert($data_reconcile);
                    //echo $this->db->last_query();
                }
            } else {

                $data_rebook = array('ReconcileBook' => $ReconcileBook);

                if ($ReconcileStatus == 0) {
                    $this->m_bank_reconcile->update_rebook($TransNumber, $bank_account, $SaldoDebet, $data_rebook);
                    //echo $this->db->last_query();
                }
            }
        }
    }

    public function insert() {
        $branch_code = $this->session->userdata('branch');
        $bank_account = $this->input->post('cbg_bank_account');

        // $bren_number            = $this->input->post('txt_bren_no');
        // $new_balance            = $this->input->post('txt_new_balance');
        // $calculated_balance     = $this->input->post('txt_calculated_balance');
        // $out_of_balance         = $this->input->post('txt_out_of_balance');

        $txt_date = $this->input->post('txt_bren_date');
        $bren_date = date("Y-m-d", strtotime($txt_date));
        $bren_last_date = $this->input->post('txt_bren_last_date');
        $currency_code = $this->input->post('hdn_currency_code');

        $total_clear = $this->input->post('txt_total_clear');
        $total_outstanding = $this->input->post('txt_total_outstanding');

        $detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);

        $this->db->trans_begin();

        /* =============================== insert group ======================================= */
        $this->insert_group($detail, $branch_code, $bank_account, $bren_date, $bren_last_date, $currency_code);
        //echo $this->db->last_query();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = false;
            $result['message'] = get_notification('insert', 0);
        } else {

            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('insert', 1);
        }

        echo json_encode($result);
    }

    /* ===================Approv Manager===================================================================== */

    function approved_mgr() {
        $branch_code = $this->session->userdata('branch');
        $bank_account = $this->input->post('cbg_bank_account');



        $detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);
        $bren_date = date("Y-m-d", strtotime($this->input->post('txt_bren_date')));

        // $detail_from_db_post    = $this->input->post('detail_from_db');        
        // $detail_from_db         = json_decode($detail_from_db_post,true);


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

        foreach ($detail as $row) {

            $TransNumber = $row->Trans_Number;

            $ReconcileStatus = ($row->Status_Reconcile) == "Yes" ? 1 : 0;

            $ReconcileBook = ($row->Status_Rebook == "Yes") ? 1 : 0;

            $data_approval = array(
                'BranchCode' => $branch_code,
                'ReconcileStatus' => 1,
                'ReconcileDate' => $bren_date,
                'ReconcileBook' => 0,
                "TransStatus" => 2,
                "AppLevel1Status" => 1,
                "AppLevel1Code" => $this->session->userdata('username'),
                "AppLevel1Date" => date('Y-m-d'),
                "LastUser" => $this->session->userdata('username')
            );

            if (($ReconcileStatus == 0) and ( $ReconcileBook == 1)) {
                $this->m_bank_reconcile->update_approval_reconcile($TransNumber, $bank_account, $data_approval);
                //echo $this->db->last_query();
            }
        }

        if ($this->db->trans_status() === TRUE) {
            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('approval', 1);
        } else {
            $this->db->trans_rollback();
            $result['status'] = false;
            $result['message'] = get_notification('approval', 0);
        }

        /* ============================= End Transac =================================== */

        echo json_encode($result);
    }

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

    public function reversed_data() {
        /* ===================================Deklarasi Variabel untuk proses insert atau update=================================== */
        $detail_post = $this->input->post('id');
        $arr_detail = explode("=", $detail_post);
        $bank_account = $arr_detail[1];
        $detail = json_decode($arr_detail[0]);

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

        foreach ($detail as $row) {

            $TransNumber = $row->Trans_Number;

            $ReconcileStatus = ($row->Status_Reconcile) == "Yes" ? 1 : 0;

            $ReconcileBook = ($row->Status_Rebook == "Yes") ? 1 : 0;

            $data_reverse = array(
                'ReconcileStatus' => 0,
                'ReconcileDate' => 0,
                'ReconcileBook' => 0,
                "TransStatus" => 4,
                "AppLevel1Status" => 0,
                //"AppLevel1Code"     => $this->session->userdata('username'),
                // "AppLevel1Date"     => date('Y-m-d'),
                "LastUser" => $this->session->userdata('username')
            );

            $this->m_bank_reconcile->update_reverse_reconcile($TransNumber, $bank_account, $data_reverse);
        }

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

        /* ============================= End Transac =================================== */

        echo json_encode($result);
    }

    public function edit() {
        //untuk ambil data dari session dan hak akses
        $group_menu = $this->session->userdata('group_menu');

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

        //panggil model hak akses untuk autoriti
        $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
        $bren_number = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());
        $data['detail'] = $this->m_bank_reconcile->get_bank_reconcile($bren_number);

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/bank_reconcile/v_edit_bank_reconcile', $data);
        $this->load->view('v_footer');
    }

    public function suspend_data() {
        $bren_number = $this->input->post('id');
        $data = $this->m_bank_reconcile->get_bank_reconcile($bren_number);

        if ($data->AppLevel1Status != 1) {
            $this->db->trans_begin();

            $data_br = array(
                'TransStatus' => $this->session->userdata('jobtitle_status') == 0 ? 9 : 3,
                'LastUser' => $this->session->userdata("username")
            );

            $result_edit = $this->m_bank_reconcile->update($data_br, $bren_number);
            if ($result_edit == 0) {
                $this->trans_rollback('suspend');
            }

            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('suspend', 1);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend', 0);
        }

        echo json_encode($result);
    }

    public function approval() {
        $bren_number = $this->input->post('BRenNumber');
        $detail_post = $this->input->post('Detail');
        $detail = json_decode($detail_post);

//        print_r($detail); die();

        if (in_array($this->session->userdata("jobtitle_status"), $this->jobtitle_status)) {
            $this->db->trans_begin();

            //Update ReconcileStatus = 1 for each table based on Transaction Number
            foreach ($detail as $row) {
                $trans_number = $row->Trans_Number;
                $trans_type = $row->Trans_Type;

                if ($row->Status == 'Yes') {
                    switch ($trans_type) {
                        case 'PPay':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_purchasepayment', 'PPayNumber', $trans_number);
                            break;

                        case 'SRec':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_salesreceipt', 'SRecNumber', $trans_number);
                            break;

                        case 'CDep':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_cashdeposit', 'CDepNumber', $trans_number);
                            break;

                        case 'BSweep':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_banksweep', 'BSweepNumber', $trans_number);
                            break;

                        case 'ADebt':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_afiliasidebt', 'ADebtNumber', $trans_number);
                            break;

                        case 'AIns':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_afiliasiinstallment', 'AInsNumber', $trans_number);
                            break;

                        case 'EDebt':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_employeedebt', 'EDebtNumber', $trans_number);
                            break;

                        case 'EIns':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_employeeinstallment', 'EInsNumber', $trans_number);
                            break;

                        case 'EIns':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_employeeinstallment', 'EInsNumber', $trans_number);
                            break;

                        case 'TCash':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_transfercash', 'TCashNumber', $trans_number);
                            break;

                        case 'EPReal':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_epaymentreal', 'EPRealNumber', $trans_number);
                            break;

                        case 'JVch':
                            $result_app = $this->m_bank_reconcile->update_reconcile_status('at_journalvoucher', 'JVchNumber', $trans_number);
                            break;
                    }

                    if ($result_app == 0) {
                        $this->trans_rollback('update');
                    }
                }
            }

            //Upate TransStatus = 2 (Finished) at Bank Reconcile Table
            $data_br = array(
                'TransStatus' => 2,
                'AppLevel1Status' => 1,
                'AppLevel1Code' => $this->session->userdata("username"),
                'AppLevel1Date' => date("Y-m-d"),
                'LastUser' => $this->session->userdata("username")
            );

            $result_app = $this->m_bank_reconcile->update($data_br, $bren_number);
            if ($result_app == 0) {
                $this->trans_rollback('update');
            }

            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('approval', 1);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('approval', 0);
        }

        echo json_encode($result);
    }

    public function to_preview($obj_string = null) {
        $company_code = $this->session->userdata('company');
        $data['company'] = $this->m_new_company->get_detail($company_code);
//        $data['list'] = $this->m_bank_reconcile->get_all();

        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
        
        $data_filter            = arrayParamInUrlToStr($obj_string); 
        $data['list']           = $this->m_bank_reconcile->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('list/cash_and_bank/bank_reconcile/v_print_bank_reconcile', $data);
        $this->load->view('v_footer');
    }
    public function to_preview_LAMA() {
        $company_code = $this->session->userdata('company');
        $data['company'] = $this->m_new_company->get_detail($company_code);
        $data['list'] = $this->m_bank_reconcile->get_all();

        $this->load->view('v_header');
        $this->load->view('list/cash_and_bank/bank_reconcile/v_print_bank_reconcile', $data);
        $this->load->view('v_footer');
    }

    public function ajax() {
        echo json_encode($this->m_bank_reconcile->get_all());
    }

    public function ajax_bank_account() {
        $result = $this->m_bank_reconcile->get_bank_account();
        echo json_encode($result);
    }

    public function ajax_item() {
        $account_number = $this->input->post('BankAccount');
        $Reconcile_Status = $this->input->post('Rec_Status');
        $CurrencyCode = $this->input->post('Currency');
        $Date_Rec = Date('Y-m-d', strtotime($this->input->post('Date_Rec')));

        if (!empty($account_number)) {
            $get_last_date = $this->m_bank_reconcile->get_last_reconcile_date($account_number);
            //echo $this->db->last_query();
            if ($get_last_date != false) {
                // echo 1;
                // $cek_in_database    = $this->m_bank_reconcile->cek_in_reconcile($account_number);
                $av_transaction = $this->m_bank_reconcile->get_detail_item_from_av($account_number, $get_last_date, $Date_Rec, $Reconcile_Status, $CurrencyCode);
                //echo $this->db->last_query();
            } else {
                //echo 2;
                // $cek_in_reconcile   = $this->m_bank_reconcile->cek_in_reconcile($account_number);
                $av_transaction = $this->m_bank_reconcile->get_detail_item_from_av($account_number, null, $Date_Rec, $Reconcile_Status, $CurrencyCode);
                //echo $this->db->last_query();
            }

            echo json_encode($av_transaction);
        } else {
            echo '[]';
        }
    }

    public function ajax_item_for_edit() {
        $bren_number = $this->input->post('BRenNumber');
        $bank_account = $this->input->post('BankAccount');
        $trans_status = $this->input->post('TransStatus');

        if (!empty($bren_number) && !empty($bank_account)) {
            if (in_array($trans_status, array(2, 3, 9))) {
                $result = $this->m_bank_reconcile->get_detail_item_for_edit_status($bren_number, $bank_account);
            } else {
                $result = $this->m_bank_reconcile->get_detail_item_for_edit($bren_number, $bank_account);
            }

            echo json_encode($result);
        } else {
            echo '[]';
        }
    }

    public function get_bren_number() {
        $date = $this->input->post('date') == '' ? date('d-m-Y') : $this->input->post('date');
        $bren_number = $this->m_bank_reconcile->create_br_number($date);

        $result['status'] = true;
        $result['number'] = $bren_number;

        echo json_encode($result);
    }

    public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status'] = false;
        $result['message'] = get_notification_transaksi($this->name, $modus, 0);

        echo json_encode($result);
        die();
    }

}
