<?php

/* 	
 * 	Author 	: Fachri
 * 	Tanggal : 03-07-2015	
 * 	Revisi 	: 
 */

class M_other_income extends CI_Model {

    public $table = "at_otherincome";
    public $detail = "at_oincomedetail";
    public $branch = "am_branch";
    public $journal = "at_oinjournal";
    public $account = "at_compaccountgl";
    public $reconcile = "at_bankreconcille";
    public $acc_gl = "am_accountgl";
    public $sub_type = "am_accountsubtype";
    public $bank = "am_bank";
    public $currency = "am_currency";
    public $period = "at_periodend";
    public $employee = "am_employee";
    public $department = "am_department";

    /* ======================penomeran transaksi new======================================================= */

    function check_code_exist($new_oi_number) {
        $query = $this->db->get_where($this->table, array('OIncomeNumber' => $new_oi_number), 1, 0);

        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function create_oi_number($date = '') {
        $branch = $this->session->userdata('branch');

        if ($date != '') {
            $month = date('m', strtotime($date));
            $year = date('y', strtotime($date));
        } else {
            $month = date('m');
            $year = date('y');
        }

        $oi_number = $branch . "/" . $month . $year . "OI/";

        $this->db->_protect_identifiers = false;
        $this->db->select('(CASE 
                              WHEN MAX(CONVERT(SUBSTR(OIncomeNumber, -3),signed)) IS NULL then 1
                              ELSE MAX(CONVERT(SUBSTR(OIncomeNumber, -3),signed)) + 1 END) as New_Number');
        $this->db->like('OIncomeNumber', $oi_number);
        $query = $this->db->get($this->table);
        $this->db->_protect_identifiers = true;

        $num = $query->row()->New_Number;
        $long = strlen($num);

        if ($long == 1) {
            $number = '00' . $num;
        } elseif ($long == 2) {
            $number = '0' . $num;
        } else {
            $number = $num;
        }

        $new_oi_number = $oi_number . $number;

        while ($this->check_code_exist($new_oi_number)) {
            $num++;
            $long = strlen($num);

            if ($long == 1) {
                $number = '00' . $num;
            } elseif ($long == 2) {
                $number = '0' . $num;
            } else {
                $number = $num;
            }

            $new_oi_number = $oi_number . $number;
        }

        return $new_oi_number;
    }

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

    function get_all() {
        /* =========================lemparan parah dari custom.js untuk searching_data_transaksi===================== */
        $param = $this->input->post('param');
        /* ====================================end=================================================================== */

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

        $DateFrom = isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
        $DateTo = isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
        $TransStatus = isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
        $BranchCode = isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
        /* ============================================end============================================================ */

        /* ======================================scrol view 1-150======================================= */
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $beginning = ($page - 1) * $rows;
        $end = $page * $rows;
        /* ============================================================================================== */

        /* ==========================================by session======================================================= */
        $sess_company = $this->session->userdata('company');
        $sess_branch = $this->session->userdata('branch');
        $sess_branch_status = $this->session->userdata('branch_status');
        /* =========================================================================================================== */

        $this->db->select('at_otherincome.BranchCode as cpay_branch, am_accountgl.AccountName, at_otherincome.OIncomeNumber,
						   at_otherincome.OIncomeDate, at_otherincome.OInTotalAmount, at_otherincome.TransStatus as PaymentStatus,
						   at_otherincome.OIncomeDesc, am_branch.BranchName, am_employee.EmployeeName as Created');
        $this->db->from($this->table);
        $this->db->join('am_branch', 'am_branch.BranchCode = at_otherincome.BranchCode');
        $this->db->join('am_accountgl', 'am_accountgl.AccountNumber = ' . $this->table . '.BankPayment');
        $this->db->join('am_employee', $this->table . '.CreatedBy=am_employee.EmployeeCode', 'LEFT');

        /* ===================================find by number dan desc========================================================= */
        if ($Number != "") {
            $this->db->like('at_otherincome.OIncomeNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('at_otherincome.OIncomeDesc', $Desc);
        }
        /* =============================================end=================================================================== */

        /* ===================================find by branch code========================================================= */
        /*
          get data dari  combobox find di view
         */
        if ($BranchCode != "") {
            $this->db->where('at_otherincome.BranchCode', $BranchCode);
        } else {
            /*
              inisialisasi untuk loading pertama page branch info
             */
            //----------------kondisi by company-------------------------------------//
            /*
              branch status 0 = HO
              branch status 1 = depo/branch
              jangan lupa sesion data di atas untuk setiap kondisi
              jangan lupa tambahin case when trans status
             */
            $this->db->where('at_otherincome.BranchCode', $sess_branch);
            //-----------------------end-------------------------------------------------//
        }
        /* =======================================================end======================================================== */

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

        /* =====================================================find by status================================================== */
        if ($TransStatus != '') {
            $this->db->where_in('at_otherincome.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('at_otherincome.TransStatus', array(0, 1, 4, 5, 6, 7, 8));
        }
        /* =======================================================end======================================================== */

        /* ==============================================sort tabel asc========================================================== */
        $this->db->order_by($this->table . '.TransStatus', 'ASC');
        $this->db->order_by($this->table . '.OIncomeNumber', 'ASC');
        /* ===============================end================================================================================= */
        $query = $this->db->limit($end, $beginning);
        $query = $this->db->get();
        return $query->result_array();
    }

    function get_bank_account() {
        $CurrencyCode = $this->input->get('CurrencyCode');

        $this->db->select('ac.AccountNumber,ag.AccountName,ab.BankOutCode,ab.BankInCode, 
			ar.CurrencyCode,ar.CurrencyName,ar.CurrencyRate');

        $this->db->from($this->account . ' as ac');
        $this->db->join($this->acc_gl . ' as ag', 'ac.AccountNumber=ag.AccountNumber', 'INNER');
        $this->db->join($this->bank . ' as ab', 'ab.BankID=ag.BankID', 'INNER');
        $this->db->join($this->currency . ' as ar', 'ag.CurrencyCode=ar.CurrencyCode', 'INNER');
        $this->db->join($this->sub_type . ' as sub', 'ag.AccountSubTypeID=sub.AccountSubTypeID', 'INNER');

        $this->db->where('ar.CompanyCode', $this->session->userdata('company'));
        $this->db->where('ac.BranchCode', $this->session->userdata('branch'));
        $this->db->where('ac.GLSaldoYears', date('Y'));
        $this->db->where('sub.AccountTypeName', 'Bank');
        $this->db->where('ag.AccountChild', 1);
        $this->db->where('ac.TransStatus', 2);

        return $this->db->get()->result();
    }

    function get_account_by_company($company_code) {
        $branch_code = $this->session->userdata('branch');
        $account_no = isset($_POST['AccountNo']) ? mysql_real_escape_string($_POST['AccountNo']) : '';
        $account_name = isset($_POST['AccountName']) ? mysql_real_escape_string($_POST['AccountName']) : '';

        $this->db->select('ag.AccountNumber,ag.AccountName');
        $this->db->from($this->account . ' as ac');
        $this->db->join($this->acc_gl . ' as ag', 'ac.AccountNumber = ag.AccountNumber');
        $this->db->join($this->sub_type . ' as sub', 'sub.AccountSubTypeID = ag.AccountSubTypeID');

        $this->db->where('ac.TransStatus', 2);
        $this->db->where('ag.AccountChild !=', 0);
        $this->db->where('ac.CompanyCode', $company_code);
        $this->db->where('ac.BranchCode', $branch_code);
        $this->db->where('ac.GLSaldoYears', date('Y'));
        $this->db->where_in('sub.AccountTypeName', array('Hutang Bank', 'Bank Garansi Customer', 'Hutang Leasing', 'Prive', 'Hutang Pemegang Saham', 'Modal', 'Other Revenue'));

        if ($account_no != '') {
            $this->db->like('ag.AccountNumber', $account_no);
        }

        if ($account_name != '') {
            $this->db->like('ag.AccountName', $account_name);
        }

        $this->db->group_by('ag.AccountName');

        $query = $this->db->get();
        return $query->result();
    }

    function get_accountnumber($account_name) {
        $query = $this->db->get_where('am_accountgl', array('AccountName' => $account_name));
        return $query->result();
    }

    function insert_group($data) {
        $this->db->insert($this->table, $data);
    }

    function insert_detail($data_detail) {
        $this->db->insert($this->detail, $data_detail);
    }

    function insert_journal($data) {
        $this->db->insert($this->journal, $data);
    }

    function update_group($data, $id) {
        $this->db->update($this->table, $data, array('OIncomeNumber' => $id));
    }

    function update_detail($data, $id) {
        $this->db->update($this->detail, $data, array('OIncomDetailID' => $id));
    }

    function delete_journal($id) {
        $this->db->delete($this->journal, array('OIncomeNumber' => $id));
    }

    function status_finished($app_finished, $id) {
        $this->db->where('OIncomeNumber', $id);
        $this->db->update($this->table, $app_finished);
    }

    function get_payment($id) {
        $this->db->select('gr.*,em.DepartmentCode');
        $this->db->from($this->table . ' as gr');
        $this->db->join($this->employee . ' as em', 'em.EmployeeCode=gr.CreatedBy', 'inner');
        $this->db->where('gr.OIncomeNumber', $id);
        $query = $this->db->get();
        return $query->result();
    }

    function get_payment_detail($payment_number) {
        $this->db->select($this->detail . '.OIncomeAmount,' . $this->detail . '.OIncomeMemo,am_accountgl.AccountNumber,am_accountgl.AccountName,
							' . $this->detail . '.OIncomDetailID,');
        $this->db->from($this->detail);
        $this->db->join('am_accountgl', 'am_accountgl.AccountNumber = ' . $this->detail . '.OInAccountNumber', 'INNER');
        $this->db->where($this->detail . '.OIncomeNumber', $payment_number);
        $query = $this->db->get();
        return $query->result();
    }

    function get_detail($id) {
        $this->db->select($this->table . ".*," . $this->branch . ".BranchName, am_accountgl.AccountName");
        $this->db->join($this->branch, $this->branch . ".BranchCode=" . $this->table . ".BranchCode", "INNER");
        $this->db->join("am_accountgl", "am_accountgl.AccountNumber=" . $this->table . ".BankPayment", "INNER");
        $query = $this->db->get_where($this->table, array('OIncomeNumber' => $id));

        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return false;
        }
    }

    function get_journal_by_number($Number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_oinjournal.*,am_accountgl.AccountNumber,am_accountgl.AccountName");
        $this->db->join("am_accountgl", "am_accountgl.AccountNumber=at_oinjournal.OInAccountNumber", "INNER");
        $this->db->order_by('at_oinjournal.OIncomeNumber', 'DESC');
        $query = $this->db->get_where($this->journal, array('OIncomeNumber' => $Number));
        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

    function delete_detail($detail_id) {
        $this->db->where('OIncomDetailID', $detail_id);
        $this->db->delete($this->detail);
    }

    function suspend($data_suspend, $no_other_income) {
        $this->db->where('OIncomeNumber', $no_other_income);
        $this->db->update($this->table, $data_suspend);
    }

    function update_to_reverse_other_income($txt_payment_no, $data_reversed) {
        $this->db->where('OIncomeNumber', $txt_payment_no);
        $this->db->update($this->table, $data_reversed);
    }

    function get_all_to_print($data_filter) {
        /* =================================post dari find di kiri==================================================== */
        $BranchCode     = $data_filter['cmb_branch'];
        $Number         = $data_filter['txt_IDNumber'];
        $Desc           = $data_filter['txt_Description'];
        $DateFrom       = $data_filter['txt_DateFrom'];
        $DateTo         = $data_filter['txt_DateTo'];
        $TransStatus    = $data_filter['chk_TransStatus'];
        /* ============================================end============================================================ */

        /* ==========================================by session======================================================= */
        $sess_company = $this->session->userdata('company');
        $sess_branch = $this->session->userdata('branch');
        $sess_branch_status = $this->session->userdata('branch_status');
        /* =========================================================================================================== */

        $this->db->select('at_otherincome.BranchCode as cpay_branch, am_accountgl.AccountName, at_otherincome.OIncomeNumber,
						   at_otherincome.OIncomeDate, at_otherincome.OInTotalAmount, at_otherincome.TransStatus as PaymentStatus,
						   at_otherincome.OIncomeDesc, am_branch.BranchName, am_employee.EmployeeName as Created');
        $this->db->from($this->table);
        $this->db->join('am_branch', 'am_branch.BranchCode = at_otherincome.BranchCode');
        $this->db->join('am_accountgl', 'am_accountgl.AccountNumber = ' . $this->table . '.BankPayment');
        $this->db->join('am_employee', $this->table . '.CreatedBy=am_employee.EmployeeCode', 'LEFT');

        /* ===================================find by number dan desc========================================================= */
        if ($Number != "") {
            $this->db->like('at_otherincome.OIncomeNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('at_otherincome.OIncomeDesc', $Desc);
        }
        /* =============================================end=================================================================== */

        /* ===================================find by branch code========================================================= */
        /*
          get data dari  combobox find di view
         */
        if ($BranchCode != "") {
            $this->db->where('at_otherincome.BranchCode', $BranchCode);
        } else {
            /*
              inisialisasi untuk loading pertama page branch info
             */
            //----------------kondisi by company-------------------------------------//
            /*
              branch status 0 = HO
              branch status 1 = depo/branch
              jangan lupa sesion data di atas untuk setiap kondisi
              jangan lupa tambahin case when trans status
             */
            $this->db->where('at_otherincome.BranchCode', $sess_branch);
            //-----------------------end-------------------------------------------------//
        }
        /* =======================================================end======================================================== */

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

        /* =====================================================find by status================================================== */
        if (!empty($TransStatus)) {
            $this->db->where_in('at_otherincome.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('at_otherincome.TransStatus', array(0, 1, 4, 5, 6, 7, 8));
        }
        /* =======================================================end======================================================== */

        /* ==============================================sort tabel asc========================================================== */
        $this->db->order_by($this->table . '.TransStatus', 'ASC');
        $this->db->order_by($this->table . '.OIncomeNumber', 'ASC');
        /* ===============================end================================================================================= */
        $query = $this->db->get();
        return $query->result_array();
    }
    function get_all_to_print_LAMA($sess_branch) {
        $this->db->select('at_otherincome.BranchCode as oi_branch,am_accountgl.AccountName,at_otherincome.OIncomeNumber,at_otherincome.OIncomeDate,
						at_otherincome.OInTotalAmount,at_otherincome.TransStatus as PaymentStatus,at_otherincome.OIncomeDesc,am_branch.BranchName');
        $this->db->from($this->table);
        $this->db->join('am_branch', 'am_branch.BranchCode = at_otherincome.BranchCode');
        $this->db->join('am_accountgl', 'am_accountgl.AccountNumber = ' . $this->table . '.BankPayment');
        $this->db->where($this->table . '.BranchCode', $sess_branch);

        $query = $this->db->get();
        return $query->result();
    }

    function get_company_by_branch($sess_branch) {
        $this->db->select('CompanyName,BranchName');
        $this->db->from('am_company');
        $this->db->join('am_branch', 'am_branch.CompanyCode = am_company.CompanyCode', 'inner');
        // $this->db->join($this->table,$this->table.'.BranchCode = am_branch.BranchCode','inner');
        $this->db->where('am_branch.BranchCode', $sess_branch);
        $query = $this->db->get();
        return $query->row();
    }

    /* ==============================funngsi get detail untuk print preview================================= */

    function get_detail_print($Oi_Number) {

        $this->db->select('cp.*, am_acctgl.AccountName, am_br.BranchName, prepared.EmployeeName as nm_prepared, mng.EmployeeName as nm_manager');
        $this->db->from($this->table . ' as cp');
        $this->db->join('at_compaccountgl as at_acctgl', 'at_acctgl.AccountNumber=cp.BankPayment', 'INNER');
        $this->db->join('am_accountgl as am_acctgl', 'at_acctgl.AccountNumber=am_acctgl.AccountNumber', 'INNER');
        $this->db->join('am_branch as am_br', 'am_br.BranchCode=at_acctgl.BranchCode', 'INNER');
        $this->db->join('am_employee as prepared', 'prepared.EmployeeCode=cp.CreatedBy', 'LEFT');
        $this->db->join('am_employee as mng', 'mng.EmployeeCode=cp.AppLevel1Code', 'LEFT');
        $this->db->where('OIncomeNumber', $Oi_Number);
        $this->db->where('(case when am_br.BranchStatus = 0 then at_acctgl.PLStatus in (0, 1) else at_acctgl.PLStatus = 1 end)');
        $this->db->where('at_acctgl.GLSaldoYears', date('Y'));
        $this->db->where('am_acctgl.AccountChild', 1);
        $this->db->where('am_acctgl.TransStatus', 2);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return false;
        }
    }

    // Daswan get detail item print
    function get_detail_item_print($OIncomeNumber) {
        $this->db->select($this->detail . '.OIncomeAmount,' . $this->detail . '.OIncomeMemo,am_accountgl.AccountNumber,am_accountgl.AccountName,' . $this->detail . '.OIncomDetailID');
        $this->db->from($this->detail);
        $this->db->join('am_accountgl', 'am_accountgl.AccountNumber = ' . $this->detail . '.OInAccountNumber', 'INNER');
        $this->db->where($this->detail . '.OIncomeNumber', $OIncomeNumber);
        $query = $this->db->get();
        return $query->result_array();
    }

    function delete_reconcile($TransNumber) {
        $this->db->where('TransNumber', $TransNumber);
        $this->db->delete($this->reconcile);
    }

    function check_period_end($periodend) {
        $this->db->select('PeriodEnd');
        $this->db->from($this->period);
        $this->db->where('PeriodEnd', $periodend);

        $query = $this->db->get()->result_array();

        if (count($query) > 0) {
            return true;
        } else {
            return false;
        }
    }

    function insert_transsaction($trans_data) {

        $this->db->trans_start();

        /* ================= insert group transaction ============================== */
        $this->insert_group($trans_data['insert_group']['data']);

        for ($x = 0; $x < count($trans_data['insert_detail']['data']); $x++) {
            $this->insert_detail($trans_data['insert_detail']['data'][$x]);
        }

        for ($x = 0; $x < count($trans_data['insert_journal']['data']); $x++) {
            $this->insert_journal($trans_data['insert_journal']['data'][$x]);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

    function update_transsaction($trans_data) {

        $this->db->trans_start();

        $this->update_group($trans_data['update_group']['data'], $trans_data['update_group']['TransNumber']);

        for ($x = 0; $x < count($trans_data['update_detail']['data']); $x++) {
            $this->update_detail($trans_data['update_detail']['data'][$x], $trans_data['update_detail']['OIncomDetailID'][$x]);
        }

        if ($trans_data['delete_detail']['total'] > 0) {
            for ($x = 0; $x < count($trans_data['delete_detail']['OIncomDetailID']); $x++) {
                $this->delete_detail($trans_data['delete_detail']['OIncomDetailID'][$x]);
            }
        }

        $this->delete_journal($trans_data['delete_journal']['TransNumber']);

        for ($x = 0; $x < count($trans_data['insert_journal']['data']); $x++) {
            $this->insert_journal($trans_data['insert_journal']['data'][$x]);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

    function approve_transsaction($trans_data) {

        $this->db->trans_start();

        $this->update_group($trans_data['approve_data']['data'], $trans_data['approve_data']['TransNumber']);

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return false;
        } else {
            return true;
        }
    }

    function suspend_transsaction($trans_data) {

        $this->db->trans_start();

        $this->suspend($trans_data['suspend_data']['data'], $trans_data['suspend_data']['TransNumber']);

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

    function reverse_transsaction($trans_data) {

        $this->db->trans_start();

        $this->update_to_reverse_other_income($trans_data['reverse_data']['TransNumber'], $trans_data['reverse_data']['data']);
        $this->delete_reconcile($trans_data['delete_reconcile']['TransNumber']);

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

}
