<?php

class M_Vendors extends CI_Model {

    // deklarasi nama table
    public $table = "am_vendor";
    public $branch = "am_branch";
    public $currency = "am_currency";
    public $pord_detail_dp = "at_pordetaildp";

    // Function View	
    function view_all() {
        $this->db->select('*');
        $this->db->from($this->table);
        $query = $this->db->get();

        return $query;
    }

    // Function get
    function get_all() {
        $status = array(0, 1);

        /* ===========================declar post by find================================================ */
        $Code = ($this->input->post('VendorCode')) ? $this->input->post('VendorCode') : '';
        $Name = ($this->input->post('VendorName')) ? $this->input->post('VendorName') : '';

        $CompanyCode = ($this->input->post('CompanyCode')) ? $this->input->post('CompanyCode') : '';
        $BranchCode = $this->input->post('BranchCode') ? $this->input->post('BranchCode') : '';
        $TransStatus = ($this->input->post('TransStatus')) ? $this->input->post('TransStatus') : '';
        $CurrencyCode = ($this->input->post('CurrencyCode')) ? $this->input->post('CurrencyCode') : '';
        /* ========================================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('am_vendor.VendorCode, am_vendor.VendorName, am_vendor.PhoneNumber, 
                           am_vendor.OutStanding, am_vendor.ContactPerson, am_currency.CurrencyName,am_city.CityName,am_termspayment.TermDesc,
                           am_vendor.TransStatus as Status');
        $this->db->from($this->table);
        $this->db->join('am_currency', 'am_currency.CurrencyCode = am_vendor.CurrencyCode');
        $this->db->join('am_city', 'am_city.CityCode = am_vendor.VendorCity','left');
		$this->db->join('am_termspayment', 'am_termspayment.TermsPaymentID = am_vendor.TermsPaymentID');

        /*
          get data dari  combobox find di view
         */
        if ($BranchCode != "") {
            $this->db->where('am_vendor.BranchCode', $BranchCode);
            $this->db->where('am_currency.CompanyCode', $CompanyCode);
        } else {
            /*
              inisialisasi untuk loading pertama page branch info
             */
            //----------------kondisi 1 untuk branch-------------------------------------//
            /*
              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('am_vendor.BranchCode', $sess_branch);
            $this->db->where('am_currency.CompanyCode', $sess_company);
            //-----------------------end-------------------------------------------------//
        }

        if ($Code != "") {
            $this->db->like('am_vendor.VendorCode', $Code);
        }
        if ($Name != "") {
            $this->db->like('am_vendor.VendorName', $Name);
        }
        if ($CurrencyCode != "") {
            $this->db->where('am_vendor.CurrencyCode', $CurrencyCode);
        }

        if ($TransStatus != '') {
            $this->db->where_in('am_vendor.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('am_vendor.TransStatus', $status);
        }

        $query = $this->db->order_by('am_vendor.VendorCode', 'ASC');
        $query = $this->db->limit($end, $beginning);
        $query = $this->db->get();
        $result = $query->result();
        return $result;
    }

    function get_all_to_print($data_filter) {
        $status = array(0, 1);
        /* ===========================declar post by find================================================ */        
        $CompanyCode    = $data_filter['cmb_company'];
        $BranchCode     = $data_filter['cmb_branch'];
        $Code           = $data_filter['txt_VendorCode'];
        $Name           = $data_filter['txt_VendorName'];
        $TransStatus    = $data_filter['chk_TransStatus'];
        $CurrencyCode   = $data_filter['cmb_CurrencyCode'];
        /* ========================================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('am_vendor.VendorCode, am_vendor.VendorName, am_vendor.PhoneNumber, 
                           am_vendor.OutStanding, am_vendor.ContactPerson, am_currency.CurrencyName,
                           am_vendor.TransStatus as Status');
        $this->db->from($this->table);
        $this->db->join('am_currency', 'am_currency.CurrencyCode = am_vendor.CurrencyCode');

        /* get data dari  combobox find di view */
        if ($BranchCode != "") {
            $this->db->where('am_vendor.BranchCode', $BranchCode);
            $this->db->where('am_currency.CompanyCode', $CompanyCode);
        } else {
            /*
              inisialisasi untuk loading pertama page branch info
             */
            //----------------kondisi 1 untuk branch-------------------------------------//
            /*
              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('am_vendor.BranchCode', $sess_branch);
            $this->db->where('am_currency.CompanyCode', $sess_company);
            //-----------------------end-------------------------------------------------//
        }

        if ($Code != "") {
            $this->db->like('am_vendor.VendorCode', $Code);
        }
        if ($Name != "") {
            $this->db->like('am_vendor.VendorName', $Name);
        }
        if ($CurrencyCode != "") {
            $this->db->where('am_vendor.CurrencyCode', $CurrencyCode);
        }

        if (!empty($TransStatus)) {
            $this->db->where_in('am_vendor.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('am_vendor.TransStatus', $status);
        }

        $query = $this->db->order_by('am_vendor.VendorCode', 'ASC');
        $query = $this->db->get();
        $result = $query->result();
        return $result;
    }
    function check_code_exist($txt_vendorno) {
        $query = $this->db->get_where($this->table, array('VendorCode' => $txt_vendorno), 1, 0);

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

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

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    function insert_purchase_invoice($data_purchase_invoice) {
        $this->db->insert('at_purchaseinvoice', $data_purchase_invoice);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            //$this->db->trans_commit();
            return 1;
        }
    }

    function insert_detail($data_detail_pi) {
        $this->db->insert('at_pinvdetail', $data_detail_pi);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            //$this->db->trans_commit();
            return 1;
        }
    }

    function update($data, $vendor_code, $branch_code) {
        $this->db->update($this->table, $data, array('VendorCode' => $vendor_code, 'BranchCode' => $branch_code));

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

    function update_purchase_invoice($data_update_total, $key, $branchCode) {
        $this->db->update('at_purchaseinvoice', $data_update_total, array('OldPInvNumber' => $key, 'BranchCode' => $branchCode));

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

    function update_appfinis($update_appfinis, $key_3, $branchCode) {
        $this->db->update('at_purchaseinvoice', $update_appfinis, array('OldPInvNumber' => $key_3, 'BranchCode' => $branchCode));

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

    function suspend($data, $id) {
        $this->db->update($this->table, $data, array('VendorCode' => $id));

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

    function get_terms_by_row($terms_id) {
        $this->db->select('*');
        $this->db->from('am_termspayment');
        $this->db->where('TermspaymentID', $terms_id);
        $query = $this->db->get();
        $result = $query->row();

        return $result;
    }

    function get_inventories($Item_code) {
        $sess_branch = $this->session->userdata('branch');
        $this->db->select('am_item.ItemCode, am_item.ItemCategoryID');
        $this->db->from('at_inventories');
        $this->db->join('am_item', 'at_inventories.ItemCode = am_item.ItemCode');
        $this->db->where('at_inventories.ItemCode', $Item_code);
        $this->db->where('at_inventories.BranchCode', $sess_branch);
        $query = $this->db->get();

        return $query->row();
    }

    function get_by_id($vendor_code) {
        $this->db->select('am_vendor.*, am_vendor.TransStatus as TransVendor, am_currency.CurrencyCode');
        $this->db->from($this->table);
        $this->db->join('am_currency', 'am_vendor.CurrencyCode = am_currency.CurrencyCode');
        $this->db->where($this->table . '.VendorCode', $vendor_code);
        $query = $this->db->get();

        return $query->row();
    }

    function get_saldo_by_id($id) {
        $this->db->select('OutStanding, SaldoDPBalance,SaldoDPReturn, SaldoDPPaid, SaldoDPUsed, OutStandingFiscal, BranchCode');
        $this->db->from($this->table);
        $this->db->where($this->table . '.VendorCode', $id);
        $query = $this->db->get();

        return $query->result();
    }

    function get_all_by_no($vendor_code) {
        $this->db->select('TransStatus, OutStanding');
        $this->db->from($this->table);
        $this->db->where($this->table . '.VendorCode', $vendor_code);
        $query = $this->db->get();

        return $query->result();
    }

    function get_no_pi($key_2) {
        $this->db->select('PInvNumber');
        $this->db->from('at_purchaseinvoice');
        $this->db->where('at_purchaseinvoice.OldPInvNumber', $key_2);
        $query = $this->db->get();

        return $query->row();
    }

    function get_last_vendor_code($sess_branch) {
        $this->db->select_max('VendorCode');
        $this->db->from($this->table);
        $this->db->where($this->table . '.BranchCode', $sess_branch);
        $query = $this->db->get();

        return $query->result();
    }

    function get_company() {
        $this->db->select('CompanyName');
        $this->db->from('am_company');
        $this->db->where('am_company.CompanyCode', $this->session->userdata('company'));
        $query = $this->db->get();

        return $query->row();
    }

    function preview_all_by_search($sess_company, $sess_branch, $sess_branch_status) {
        $this->db->select($this->table . '.*,am_currency.CurrencyName');
        $this->db->from($this->table);
        $this->db->join('am_currency', 'am_currency.CurrencyCode = ' . $this->table . '.CurrencyCode');
        $this->db->join('am_branch', 'am_branch.BranchCode = ' . $this->table . '.BranchCode');

        if ($sess_branch_status == 0) {
            $this->db->where($this->branch . '.CompanyCode', $sess_company);
        }

        if ($sess_branch_status == 1) {
            $this->db->where($this->table . '.BranchCode', $sess_branch);
        }

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

    function get_vendor_status($vendor_code) {
        $this->db->select('VendorStatus');
        $this->db->from('am_vendor');

        $this->db->where('VendorCode', $vendor_code);
        $query = $this->db->get();

        return $query->row();
    }

    function insert_transsaction($trans_data) {

        $this->db->trans_start();

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

        $this->db->trans_complete();

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

    function update_transsaction($trans_data) {

        $this->db->trans_start();

        /* ====================== update group ==================== */
        $this->update($trans_data['update_group']['data'], $trans_data['update_group']['TransNumber'], $trans_data['update_group']['branch']);

        for ($x = 0; $x < $trans_data['detail_pi']['total']; $x++) {
            $this->insert_purchase_invoice($trans_data['insert_purchase_invoice']['data'][$x]);
            $this->insert_detail($trans_data['insert_detail']['data'][$x]);
            $this->m_purchase_invoice->insert_payment($trans_data['insert_payment']['data'][$x]);

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

            $this->m_purchase_invoice->update_payment($trans_data['update_payment']['data'][$x], $trans_data['update_payment']['key'][$x]);
            $this->update_purchase_invoice($trans_data['update_purchase_invoice']['data'][$x], $trans_data['update_purchase_invoice']['key'][$x], $trans_data['update_purchase_invoice']['branch'][$x]);
            $this->update_appfinis($trans_data['update_appfinis']['data'][$x], $trans_data['update_appfinis']['key'][$x], $trans_data['update_appfinis']['branch'][$x]);
        }

        for ($x = 0; $x < $trans_data['detail_dp']['total']; $x++) {
            $this->m_period_end->insert_group_jvb($trans_data['insert_dp_group']['data'][$x]);
            $this->insert_pord_detail_dp($trans_data['insert_pord_detail_dp']['data'][$x]);

            for ($i = 0; $i < count($trans_data['insert_dp_detail'][$x]['data']); $i++) {
                $this->m_period_end->insert_detail_jvb($trans_data['insert_dp_detail'][$x]['data'][$i]);
                $this->m_period_end->insert_journal_jvb($trans_data['insert_dp_journal'][$x]['data'][$i]);
            }

            $this->m_period_end->update_group_jvb($trans_data['update_group_jv']['TransNumber'][$x], $trans_data['update_group_jv']['data'][$x]);
        }

        /* ===================== end insert journal =============================== */
        $this->db->trans_complete();

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

    function insert_pord_detail_dp($data_pord_detail_dp) {
        $this->db->insert($this->pord_detail_dp, $data_pord_detail_dp);
    }

}
