<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Invoice extends MY_Controller{
    public function index(){
        $data = "";
        $this->load->view($this->router->fetch_class()."/index", $data);
    }
    
    public function edit($id=""){
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        $data['id'] = $id != ""? $id:0;
        
        $this->load->view($this->router->fetch_class()."/edit", $data);
    }
    
    public function load_edit(){
        $this->load->model("invoice_model");
        $this->load->model("invitem_model");
        $this->load->model("tradein_model");
        $this->load->model("tradeitem_model");

        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        $data = array();
        
        //Access---
        $access_array = $this->fm->get_access(array(14, 15, 16, 67, 68));
        $data['can_create'] = isset($access_array[14]);
        $data['can_edit'] = isset($access_array[15]);
        $data['can_delete'] = isset($access_array[16]);
        $data['can_create_tradein'] = isset($access_array[67]);
        $data['can_delete_tradein'] = isset($access_array[68]);
        //---------
        
        $user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;
        $data['userpkkey'] = $user->PKKEY;

        $data['sub_array'] = array();

        if($this->input->post('REFNO') != "0"){
            
            $additional_join = ""; 
            $additional_join .= "LEFT JOIN GOLD ON GOLD.CODE = <T>.GOLD";
            $data_array = $this->invoice_model->get_data(array(
                'condition' => "<T>.REFNO = '".$this->fm->str_esc($post['REFNO'], 1)."'",
                '' => "",
                'additional_select' => "GOLD.BAL AS GOLD_BAL",
                'additional_join' => $additional_join,
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];

                $this->load->model("User_model");

                $additional_join = ""; 
                $additional_join .= "LEFT JOIN ITEM ON ITEM.CODE = <T>.ITEM";
                $data['sub_array'] = $this->invitem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "",
                    '' => "",
                    'additional_select' => "ITEM.NAME AS ITEM_NAME",
                    'additional_join' => $additional_join,
                ));

                $tradein_array = $this->tradein_model->get_data(array(
                    'condition' => "<T>.RECEIPT = '".$data['data']->REFNO."'",
                    '' => "",
                ));

                if(count($tradein_array) > 0){
                    $data['tradein_data'] = $tradein_array[0];

                    $data['tradein_sub_array'] = $this->tradeitem_model->get_data(array(
                        'condition' => "<T>.REFNO = '".$data['tradein_data']->REFNO."'",
                        'sort' => "",
                        '' => "",
                    ));

                     //Total trade in
                    $tradein = $this->tradeitem_model->get_data(array(
                        'select' => "<T>.GOLDPRICE",
                        'condition' => "<T>.REFNO = '".$data['tradein_data']->REFNO."'",
                    ));

                    $tradein_total = array();
                    foreach($tradein as $lv){
                        array_push($tradein_total, $lv->GOLDPRICE);
                    }
                    $data['tradein_total'] = array_sum($tradein_total);
                }

                //Calculate total
                $item = $this->invitem_model->get_data(array(
                    'select' => "<T>.LABOUR, <T>.GST, <T>.AMT",
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                ));

                //Total Item Labour
                $item_total = array();
                foreach($item as $lv){
                    array_push($item_total, $lv->LABOUR);
                }
                $data['item_total'] = array_sum($item_total);

                //Total Item GST
                $item_gst = array();
                foreach($item as $lv){
                    array_push($item_gst, $lv->GST);
                }
                $data['item_gst'] = array_sum($item_gst);

                //Total Item Amount
                $item_amt = array();
                foreach($item as $lv){
                    array_push($item_amt, $lv->AMT);
                }
                $data['item_amt'] = array_sum($item_amt);

            }
        }

        $this->load->model("debtor_model");
        $data['all_debtor'] = $this->debtor_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("tt_model");
        $data['all_tt'] = $this->tt_model->get_data( array(
            'sort' => "<T>.TT",
            '' => "",
        ));

        $this->load->model("staff_model");
        $data['all_staff'] = $this->staff_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("gold_model");
        $data['all_gold'] = $this->gold_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("taxcode_model");
        $data['all_taxcode'] = $this->taxcode_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("item_model");
        $data['all_item'] = $this->item_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("unit_model");
        $data['all_unit'] = $this->unit_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("paytype_model");
        $data['all_paytype'] = $this->paytype_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("tradein_model");
        $data['all_tradein'] = $this->tradein_model->get_data( array(
            'sort' => "<T>.REFNO",
            '' => "",
        ));

        if(($data['can_create'] && $this->input->post('REFNO') == "0") || (isset($data['data']))){
            $this->load->view($this->router->fetch_class()."/load_edit", $data);
            return;
        }
        
        header("HTTP/1.1 500 Internal Server Error");
        header("Content-Type: application/json; charset=UTF-8");
        return;
    }

    public function update(){
        $this->load->model("invoice_model");
        $this->load->model("invitem_model");
        $this->load->model("tradein_model");
        $this->load->model("tradeitem_model");
        $this->load->model("debtor_model");
        $this->load->model("gold_model");

        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        $main_post = array();
        $sub_post = array();
        foreach($post as $index=>$value){
            if(! in_array($index, array('DEL_SUB_PKKEY'))){
                if(substr($index, 0, strlen("SUB_")) == "SUB_"){
                    $sub_post[$index] = $value;
                }
                else{
                    $main_post[$index] = $value;
                }
            }
        }


        if($return = $this->invoice_model->save($main_post)){
            $invoice_pkkey = $return['pk'];
        
            if(isset($sub_post['SUB_PKKEY'])){
                foreach($sub_post['SUB_PKKEY'] as $x=>$sub_pkkey){
                    unset($sub_data);

                    $sub_data['REFNO'] = $invoice_pkkey;
                    if($sub_pkkey != "")$sub_data['PKKEY'] = $sub_pkkey;
                    if(isset($post['SUB_ITEM'][$x])) $sub_data['ITEM'] = $post['SUB_ITEM'][$x];
                    if(isset($post['SUB_DESCRIPT'][$x])) $sub_data['DESCRIPT'] = $post['SUB_DESCRIPT'][$x];
                    if(isset($post['SUB_INCH'][$x])) $sub_data['INCH'] = $post['SUB_INCH'][$x];
                    if(isset($post['SUB_LENGTH'][$x])) $sub_data['LENGTH'] = $post['SUB_LENGTH'][$x];
                    if(isset($post['SUB_PCS'][$x])) $sub_data['PCS'] = $post['SUB_PCS'][$x];
                    if(isset($post['SUB_QTY'][$x])) $sub_data['QTY'] = $post['SUB_QTY'][$x];
                    if(isset($post['SUB_UNIT'][$x])) $sub_data['UNIT'] = $post['SUB_UNIT'][$x];
                    if(isset($post['SUB_PRICE'][$x])) $sub_data['PRICE'] = $post['SUB_PRICE'][$x];
                    if(isset($post['SUB_LABOUR'][$x])) $sub_data['LABOUR'] = $post['SUB_LABOUR'][$x];
                    if(isset($post['SUB_TAXCODE'][$x])) $sub_data['TAXCODE'] = $post['SUB_TAXCODE'][$x];
                    if(isset($post['SUB_PERCEN'][$x])) $sub_data['PERCEN'] = $post['SUB_PERCEN'][$x];
                    if(isset($post['SUB_GST'][$x])) $sub_data['GST'] = $post['SUB_GST'][$x];
                    if(isset($post['SUB_AMT'][$x])) $sub_data['AMT'] = $post['SUB_AMT'][$x];
                    if(isset($post['SUB_INCLUSIVE'][$x])) $sub_data['INCLUSIVE'] = $post['SUB_INCLUSIVE'][$x];
                    if(isset($post['UNIQID'])) $sub_data['UNIQID'] = $post['UNIQID'];

                    $return = $this->invitem_model->save($sub_data);
                    
                }
            }

            // if(isset($sub_post['SUB_TRADEIN_PKKEY'])){
            //  foreach($sub_post['SUB_TRADEIN_PKKEY'] as $x=>$sub_tradein_pkkey){
            //      unset($sub_tradein_data);

            //      $sub_tradein_data['REFNO'] = $invoice_pkkey;
            //      if($sub_tradein_pkkey != "")$sub_tradein_data['REFNO'] = $sub_tradein_pkkey;
            //      if(isset($post['SUB_TRADEIN_GOLD'][$x])) $sub_tradein_data['GOLD'] = $post['SUB_TRADEIN_GOLD'][$x];
   //                  if(isset($post['SUB_TRADEIN_WEIGHT'][$x])) $sub_tradein_data['WEIGHT'] = $post['SUB_TRADEIN_WEIGHT'][$x];
   //                  if(isset($post['SUB_TRADEIN_RATE'][$x])) $sub_tradein_data['RATE'] = $post['SUB_TRADEIN_RATE'][$x];

            //      $return = $this->tradeitem_model->save($sub_tradein_data);
                    
            //  }
            // }

            if(isset($post['DEL_SUB_PKKEY'])){
                foreach($post['DEL_SUB_PKKEY'] as $del_pkkey){
                    $this->invitem_model->remove($del_pkkey);
                }
            }

            // if(isset($post['DEL_SUB_TRADEIN_PKKEY'])){
            //  foreach($post['DEL_SUB_TRADEIN_PKKEY'] as $del_pkkey){
            //      $this->tradeitem_model->remove($del_pkkey);
            //  }
            // }
        }

        if(isset($post['DEBTOR_GOLD']) && $post['DEBTOR_GOLD'] != ""){   
            if($post['TRADEIN_REFNO_HIDDEN'] != ""){
                $TRADEIN_REFNO = $post['TRADEIN_REFNO_HIDDEN'];
            }else{
                $TRADEIN_REFNO = $post['TRADEIN_REFNO'];
            }
            
            $tradein_array = $this->tradein_model->get_data(array(
                'condition' => "<T>.REFNO = '".$TRADEIN_REFNO."'",
            ));

            foreach($tradein_array as $v){
                unset($data_tradein);
                $data_tradein['REFNO'] = $v->REFNO;
                $data_tradein['BAL'] = $post['DEBTOR_GOLD'];
                //print_r($data_debtor);return;

                $this->tradein_model->save($data_tradein);
            }
        }

        if(isset($post['GOLD_BAL'])){
            $gold_array = $this->gold_model->get_data(array(
                'condition' => "<T>.CODE = '".$post['GOLD']."'",
            ));

            foreach($gold_array as $v){
                unset($data_gold);
                $data_gold['CODE'] = $post['GOLD'];
                $data_gold['BAL'] = $post['GOLD_BAL'];
                //print_r($data_gold);return;

                $this->gold_model->save($data_gold);
            }
        }

        // if(isset($post['WEIGHT'])){
        //     $weight_array = $this->debtor_model->get_data(array(
        //         'condition' => "<T>.CODE = '".$post['DEBTOR']."'",
        //     ));

        //     foreach($debtor_array as $v){
        //         unset($data_debtor);
        //         $data_debtor['CODE'] = $post['DEBTOR'];
        //         $data_debtor['DEBTOR_GOLD'] = $post['DEBTOR_GOLD'];
        //         //print_r($data_debtor);return;

        //         $this->debtor_model->save($data_debtor);
        //     }
        // }

        if(isset($post['TRADE_IN_TOTAL'])){
            $tradein_array = $this->tradein_model->get_data(array(
                'condition' => "<T>.RECEIPT = '".$post['REFNO']."'",
            ));

            foreach($tradein_array as $v){
                unset($data_tradein);
                $data_tradein['REFNO'] = $v->REFNO;
                $data_tradein['AMOUNT'] = $post['TRADE_IN_TOTAL'];

                $this->tradein_model->save($data_tradein);
            }
        }
        
        if($return['pk'] != "" && isset($post['UNIQID'])){
            $uniqid_array = $this->invitem_model->get_data(array(
                'condition' => "<T>.UNIQID = '".$post['UNIQID']."'",
            ));

            foreach($uniqid_array as $v){
                unset($data_uniqid);
                $data_uniqid['PKKEY'] = $v->PKKEY;
                $data_uniqid['REFNO'] = $invoice_pkkey;

                $this->invitem_model->save($data_uniqid);
            }
        }
        
        if($return['error'] == ""){
            $action = ! isset($post['REFNO'])? "Create":"Update";
            $this->session->set_flashdata('success', $action." Successful!");
        }
        else{
            $this->session->set_flashdata('error', $return['error']);
        }
        
        if(isset($post['REFNO'])){
            $redirect_params = "";
            $redirect_params .= "/edit/".$post['REFNO'];
            redirect(base_url($this->router->fetch_class().$redirect_params));
        }else{
            redirect(base_url($this->router->fetch_class()."?".$this->session->flashdata($this->router->fetch_class().'_page_filter')));
        }
    }

    public function update_tradein(){
        $this->load->model("tradein_model");
        $this->load->model("tradeitem_model");
        $this->load->model("invoice_model");
        $this->load->model("debtor_model");

        $post = $this->input->post();
        //print_r($post);return;
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------

        unset($data);
        if(isset($post['SUB_TRADEIN_REFNO']) && $post['SUB_TRADEIN_REFNO'] != ""){
            $data['REFNO'] = $post['SUB_TRADEIN_REFNO'];
        }
        if(isset($post['INVOICE'])) $data['RECEIPT'] = $post['INVOICE'];
        if(isset($post['SUB_TRADEIN_DATE'])) $data['DATE'] = $post['SUB_TRADEIN_DATE'];
        if(isset($post['SUB_TRADEIN_DEBTOR'])) $data['DEBTOR'] = $post['SUB_TRADEIN_DEBTOR'];
        if(isset($post['SUB_TRADEIN_TT'])) $data['TT'] = $post['SUB_TRADEIN_TT'];
        if(isset($post['SUB_TRADEIN_STAFF'])) $data['STAFF'] = $post['SUB_TRADEIN_STAFF'];
        if(isset($post['SUB_TRADEIN_REMARK'])) $data['PARTICULAR'] = $post['SUB_TRADEIN_REMARK']; 
        if(isset($post['SUB_TRADEIN_TOTAL_TRADEIN'])) $data['TRADEIN_W'] = $post['SUB_TRADEIN_TOTAL_TRADEIN']; 

        $return = $this->tradein_model->save($data);
        
        if($return['error'] == ""){
            if(isset($post['SUB_TRADEIN_PKKEY'])){
                foreach($post['SUB_TRADEIN_PKKEY'] as $x=>$sub_tradein_pkkey){
                    unset($sub_data);
                    $sub_data['REFNO'] = $return['pk'];
                    if($sub_tradein_pkkey != "") $sub_data['PKKEY'] = $sub_tradein_pkkey;
                    if(isset($post['SUB_TRADEIN_GOLD'][$x])) $sub_data['GOLD'] = $post['SUB_TRADEIN_GOLD'][$x];
                    if(isset($post['SUB_TRADEIN_DESCRIPT'][$x])) $sub_data['DESCRIPT'] = $post['SUB_TRADEIN_DESCRIPT'][$x];
                    if(isset($post['SUB_TRADEIN_WEIGHT'][$x])) $sub_data['WEIGHT'] = $post['SUB_TRADEIN_WEIGHT'][$x];
                    if(isset($post['SUB_TRADEIN_RATE'][$x])) $sub_data['RATE'] = $post['SUB_TRADEIN_RATE'][$x];
                    if(isset($post['SUB_TRADEIN_GOLDPRICE'][$x])) $sub_data['GOLDPRICE'] = $post['SUB_TRADEIN_GOLDPRICE'][$x]; 

                    $this->tradeitem_model->save($sub_data);
                }

            }

            if(isset($post['DEL_SUB_TRADEIN_PKKEY'])){
                foreach($post['DEL_SUB_TRADEIN_PKKEY'] as $del_pkkey){
                    $this->tradeitem_model->remove($del_pkkey);
                }
            }
        }

        if(isset($post['SUB_TRADEIN_TOTAL_TRADEIN'])){
            $data['TRADEIN_W'] = $post['SUB_TRADEIN_TOTAL_TRADEIN'];
            $data['REFNO'] = $post['INVOICE'];
            $this->invoice_model->save($data);     
        }

        if(isset($post['SUB_TRADEIN_DEBTOR'])){
            $data['CODE'] = $post['SUB_TRADEIN_DEBTOR'];
            $data['TRADEIN_REFNO'] = $return['pk'];
            $data['DEBTOR_GOLD'] = $post['SUB_TRADEIN_TOTAL_TRADEIN'];
            $this->debtor_model->save($data);     
        }

        if($return['error'] == ""){
            $action = ! isset($post['INVOICE'])? "Create":"Update";
            $this->session->set_flashdata('success', $action." Successful!");
        }
        else{
            $this->session->set_flashdata('error', $return['error']);
        }
        
        if($post['INVOICE'] != ""){
            $redirect_params = "";
            $redirect_params .= "/edit/".$post['INVOICE'];
            redirect(base_url($this->router->fetch_class().$redirect_params));
        }else{
            redirect(base_url($this->router->fetch_class()."?".$this->session->flashdata($this->router->fetch_class().'_page_filter')));
        }
    }

    public function load_item_images(){
        $this->load->model("item_attachment_model");

        $post = $this->input->post();

        $pkkey = "";
        $condition = "";
        if($this->input->post('id') != ""){
            $condition = $this->fm->append($condition, "<T>.ITEM = '".$post['id']."' ");
        }
        
        $data = $this->item_attachment_model->get_data( array(
            'condition' => $condition,
        ));
        
        if(count($data) > 0){
            $pkkey = $data[0]->PKKEY;
        }
        echo $pkkey;
    }

    public function get_item_detail(){
        $this->load->model("item_model");

        $post = $this->input->post();

        $info = "";
        $condition = "";

        if($this->input->post('id') != ""){
            $condition = $this->fm->append($condition, "<T>.CODE = '".$post['id']."' ");
            
            $additional_join = ""; 
            $additional_join .= "LEFT JOIN TAXCODE ON TAXCODE.CODE = <T>.TAXCODE";
            $data = $this->item_model->get_data( array(
                'condition' => $condition,
                'select' => "<T>.CODE, <T>.NAME, <T>.DESCRIPT, <T>.SALES_AMT, <T>.TAXCODE, TAXCODE.PERCEN",
                'sort' => "<T>.CODE DESC",
                'limit' => "1",
                'additional_join' => $additional_join,

            ));
        }

        echo json_encode($data);
    }

    public function get_gold_detail(){
        $this->load->model("gold_model");

        $post = $this->input->post();

        $info = "";
        $condition = "";

        if($this->input->post('id') != ""){
            $condition = $this->fm->append($condition, "<T>.CODE = '".$post['id']."' ");
            
            $additional_join = ""; 
            $additional_join .= "LEFT JOIN TAXCODE ON TAXCODE.CODE = <T>.TAXCODE";
            $data = $this->gold_model->get_data( array(
                'condition' => $condition,
                'select' => "<T>.CODE, <T>.TAXCODE, TAXCODE.PERCEN, <T>.RATE, <T>.DESCRIPT, <T>.BAL AS GOLD_BAL",
                'sort' => "<T>.CODE DESC",
                'limit' => "1",
                'additional_join' => $additional_join,

            ));
        }

        echo json_encode($data);
    }

    public function get_tradein_detail(){
        $this->load->model("tradein_model");

        $post = $this->input->post();

        $info = "";
        $condition = "";

        if($this->input->post('id') != ""){
            $condition = $this->fm->append($condition, "<T>.REFNO = '".$post['id']."' ");
            $data = $this->tradein_model->get_data( array(
                'condition' => $condition,
                'select' => "<T>.BAL",
                'sort' => "<T>.REFNO DESC",
                'limit' => "1",
            ));
        }

        echo json_encode($data);
    }

    public function get_debtor(){
        $this->load->model("debtor_model");

        $post = $this->input->post();

        $info = "";
        $condition = "";

        if($this->input->post('id') != ""){
            $condition = $this->fm->append($condition, "<T>.CODE = '".$post['id']."' ");
            
            $additional_join = ""; 
            $additional_join .= "LEFT JOIN TRADEIN ON TRADEIN.DEBTOR = <T>.CODE";
            $data = $this->debtor_model->get_data( array(
                'condition' => $condition,
                'select' => "TRADEIN.REFNO, TRADEIN.BAL, TRADEIN.TRADEIN_W",
                'additional_join' => $additional_join,

            ));
        }

        echo json_encode($data);
    }
    
    // public function update(){
 //        $this->load->model("invoice_model");
 //        $this->load->model("invitem_model");

 //        $post = $this->input->post();
 //        // print_r($post);return;

 //        //To prevent loss---
 //        $this->fm->keep_all_page_filter();
 //        //------------------

 //       $redirect_params = "";
        
 //            unset($data);
 //            if(isset($post['REFNO']) && $post['REFNO'] != ""){
 //                $data['REFNO'] = $post['REFNO'];
 //            }
 //            if(isset($post['DATE'])) $data['DATE'] = $post['DATE'];
 //            if(isset($post['DEBTOR'])) $data['DEBTOR'] = $post['DEBTOR'];
 //            if(isset($post['STAFF'])) $data['STAFF'] = $post['STAFF'];
 //            if(isset($post['TT'])) $data['TT'] = $post['TT'];
 //            if(isset($post['PARTICULAR'])) $data['PARTICULAR'] = $post['PARTICULAR'];
 //            if(isset($post['UNIQID'])) $data['UNIQID'] = $post['UNIQID'];
    
 //            $return = $this->invoice_model->save($data);
            
 //            if($return['error'] == ""){
 //                if(isset($post['sub_pkkey'])){

 //                    foreach($post['sub_pkkey'] as $x=>$sub_pkkey){
 //                        unset($sub_data);
 //                        if($sub_pkkey != "") $sub_data['REFNO'] = $sub_pkkey;
 //                        if(isset($post['REFNO'])) $sub_data['REFNO'] = $return['pk'];
 //                        if(isset($post['SUB_ITEM'][$x])) $sub_data['ITEM'] = $post['SUB_ITEM'][$x];
 //                        if(isset($post['SUB_DESCRIPT'][$x])) $sub_data['DESCRIPT'] = $post['SUB_DESCRIPT'][$x];
 //                        if(isset($post['SUB_INCH'][$x])) $sub_data['INCH'] = $post['SUB_INCH'][$x];
 //                        if(isset($post['SUB_PCS'][$x])) $sub_data['PCS'] = $post['SUB_PCS'][$x];
 //                        if(isset($post['SUB_QTY'][$x])) $sub_data['QTY'] = $post['SUB_QTY'][$x];
 //                        if(isset($post['SUB_UNIT'][$x])) $sub_data['UNIT'] = $post['SUB_UNIT'][$x];
 //                        if(isset($post['SUB_PRICE'][$x])) $sub_data['PRICE'] = $post['SUB_PRICE'][$x];
 //                        if(isset($post['SUB_LABOUR'][$x])) $sub_data['LABOUR'] = $post['SUB_LABOUR'][$x];
 //                        if(isset($post['SUB_TAXCODE'][$x])) $sub_data['TAXCODE'] = $post['SUB_TAXCODE'][$x];
 //                        if(isset($post['SUB_PERCEN'][$x])) $sub_data['PERCEN'] = $post['SUB_PERCEN'][$x];
 //                        if(isset($post['SUB_GST'][$x])) $sub_data['GST'] = $post['SUB_GST'][$x];
 //                        if(isset($post['SUB_AMT'][$x])) $sub_data['AMT'] = $post['SUB_AMT'][$x];
 //                        if(isset($post['UNIQID'])) $sub_data['UNIQID'] = $post['UNIQID'];
                        
 //                        $this->invitem_model->save($sub_data);
 //                    }

 //                }

 //                if(isset($post['DEL_SUB_PKKEY'])){
 //                    foreach($post['DEL_SUB_PKKEY'] as $del_pkkey){
 //                    $this->invitem_model->remove($del_pkkey);
 //                }
 //            }
 //        }

 //        if($return['pk'] != "" && isset($post['UNIQID'])){
 //            $uniqid_array = $this->invitem_model->get_data(array(
 //                'condition' => "<T>.UNIQID = '".$post['UNIQID']."'",
 //            ));

 //            foreach($uniqid_array as $v){
 //                unset($data_uniqid);
 //                $data_uniqid['REFNO'] = $v->REFNO;
 //                $data_uniqid['REFNO'] = $return['pk'];

 //                $this->invitem_model->edit($data_uniqid);
 //            }
 //        }

 //        if($return['error'] == ""){
 //            $action = ! isset($post['REFNO'])? "Create":"Update";
 //            $this->session->set_flashdata('success', $action." Successful!");
 //        }
 //        else{
 //            $this->session->set_flashdata('error', $return['error']);
 //        }
        
 //        if($post['REFNO'] != ""){
 //            $redirect_params = "";
 //            $redirect_params .= "/edit/".$post['REFNO'];
 //            redirect(base_url($this->router->fetch_class().$redirect_params));
 //        }else{
 //            redirect(base_url($this->router->fetch_class()."?".$this->session->flashdata($this->router->fetch_class().'_page_filter')));
 //        }
 //    }

    public function get_tax(){
        $this->load->model("taxcode_model");

        $post = $this->input->post();

        $tax = "";
        $condition = "";
        if($this->input->post('SUB_TAXCODE') != ""){
            $condition = $this->fm->append($condition, "<T>.CODE = '".$post['SUB_TAXCODE']."' ");
        }
        
        $data = $this->taxcode_model->get_data( array(
            'condition' => $condition,
        ));
        
        if(count($data) > 0){
            $tax = $data[0]->PERCEN;
        }
        echo $tax;
    }

    public function get_tax_gold(){
        $this->load->model("taxcode_model");

        $post = $this->input->post();

        $tax = "";
        $condition = "";
        if($this->input->post('TAXCODE') != ""){
            $condition = $this->fm->append($condition, "<T>.CODE = '".$post['TAXCODE']."' ");
        }
        
        $data = $this->taxcode_model->get_data( array(
            'condition' => $condition,
        ));
        
        if(count($data) > 0){
            $tax = $data[0]->PERCEN;
        }
        echo $tax;
    }

    // public function get_debtor_gold(){
    //     $this->load->model("debtor_model");

    //     $post = $this->input->post();

    //     $gold = "";
    //     $condition = "";
    //     if($this->input->post('DEBTOR') != ""){
    //         $condition = $this->fm->append($condition, "<T>.CODE = '".$post['DEBTOR']."' ");
    //     }
        
    //     $data = $this->debtor_model->get_data( array(
    //         'condition' => $condition,
    //     ));
        
    //     if(count($data) > 0){
    //         $gold = $data[0]->DEBTOR_GOLD;
    //     }
    //     echo $gold;
    // }

    public function get_debtor_gold(){
        $this->load->model("debtor_model");

        $post = $this->input->post();

        $info = "";
        $condition = "";

        if($this->input->post('id') != ""){
            $condition = $this->fm->append($condition, "<T>.CODE = '".$post['id']."' ");
            
            $data = $this->debtor_model->get_data( array(
                'condition' => $condition,
                'select' => "<T>.CODE, <T>.TRADEIN_REFNO, <T>.DEBTOR_GOLD",
                'sort' => "<T>.CODE DESC",
                'limit' => "1",

            ));
        }

        echo json_encode($data);
    }
    
    public function delete(){
        $this->load->model("invoice_model");
        $this->load->model("invitem_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        $pk = $this->invoice_model->sql_get_pk();
        if(isset($post[$pk]) && $this->invoice_model->remove($post[$pk])){
            $sub_array = $this->invitem_model->get_data(array(
                'condition' => "<T>.REFNO = '".$post[$pk]."' ",
            ));
            if(count($sub_array) > 0){
                foreach($sub_array as $sub){
                    $this->invitem_model->remove($sub->PKKEY);
                }
            }
            
            $this->session->set_flashdata('success', "Delete Successful!");
        }
        else{
            $this->session->set_flashdata('error', "Delete Failed!");
        }
        
        redirect(base_url($this->router->fetch_class()."?".$this->session->flashdata($this->router->fetch_class().'_page_filter')));
    }

    public function delete_tradein(){
        $this->load->model("tradein_model");
        $this->load->model("tradeitem_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        if(isset($post['SUB_TRADEIN_REFNO']) && $this->tradein_model->remove($post['SUB_TRADEIN_REFNO'])){
            $sub_array = $this->tradeitem_model->get_data(array(
                'condition' => "<T>.REFNO = '".$post['SUB_TRADEIN_REFNO']."' ",
            ));
            if(count($sub_array) > 0){
                foreach($sub_array as $sub){
                    $this->tradeitem_model->remove($sub->PKKEY);
                }
            }
            
            $this->session->set_flashdata('success', "Delete Successful!");
        }
        else{
            $this->session->set_flashdata('error', "Delete Failed!");
        }
        
        redirect(base_url($this->router->fetch_class()."?".$this->session->flashdata($this->router->fetch_class().'_page_filter')));
    }
    
    public function check_unique(){
        $this->load->model("invoice_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        if($this->input->post('unique') != ""){
            $condition = "<T>.REFNO = '".$this->fm->str_esc($post['unique'], 1)."'";
            if(isset($post['pk'])) $condition .= " AND <T>.<PK> != '".$post['pk']."'";
            $data_array = $this->invoice_model->get_data(array(
                'condition' => $condition,
            ));
            
            if(count($data_array) == 0){
                echo "1";
            }
        }
    }

    public function load_print(){
        $this->load->model("invoice_model");
        $this->load->model("invitem_model");
        $this->load->model("company_profile_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------

        $data = array();
        $user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;

        if($this->input->post('REFNO') != ""){

            $additional_join = ""; 
            $additional_join .= "LEFT JOIN DEBTOR ON DEBTOR.CODE = <T>.DEBTOR";
            $data_array = $this->invoice_model->get_data(array(
                'condition' => "<T>.<PK> = '".$this->fm->str_esc($post['REFNO'], 1)."'",
                'additional_select' => "DEBTOR.NAME AS DEBTOR_NAME, DEBTOR.ADD1 AS DEBTOR_ADD1",
                'additional_join' => $additional_join,  
              
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];
                
                $additional_join = ""; 
                $additional_join .= "LEFT JOIN INVOICE ON INVOICE.REFNO = <T>.REFNO";
                $additional_join .= " LEFT JOIN ITEM ON ITEM.CODE = <T>.ITEM";
                $data['list'] = $this->invitem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "<T>.REFNO",
                    'additional_select' => "ITEM.NAME AS ITEM_NAME",
                    'additional_join' => $additional_join,  
                    '' => "",
                ));

                //Total Item Labour
                $item = $this->invitem_model->get_data(array(
                    'select' => "<T>.LABOUR, <T>.GST, <T>.AMT",
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                ));

                $item_total = array();
                foreach($item as $lv){
                    array_push($item_total, $lv->LABOUR);
                }
                $data['item_total'] = array_sum($item_total);

                //Total Item GST
                $item_gst = array();
                foreach($item as $lv){
                    array_push($item_gst, $lv->GST);
                }
                $data['item_gst'] = array_sum($item_gst);

                //Total Item Amount
                $item_amt = array();
                foreach($item as $lv){
                    array_push($item_amt, $lv->AMT);
                }
                $data['item_amt'] = array_sum($item_amt);

                //Company Profile
                $company = $this->company_profile_model->get_data(array(
                    'condition' => "",
                ));
                $data['company'] = $company[0];
                
                $this->load->view($this->router->fetch_class()."/load_print", $data);
                return;
            }
        }
        
        header("HTTP/1.1 500 Internal Server Error");
        header("Content-Type: application/json; charset=UTF-8");
        return;
    }

    public function load_print_en(){
        $this->load->model("invoice_model");
        $this->load->model("invitem_model");
        $this->load->model("company_profile_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------

        $data = array();
        $user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;

        if($this->input->post('REFNO') != ""){

            $additional_join = ""; 
            $additional_join .= "LEFT JOIN DEBTOR ON DEBTOR.CODE = <T>.DEBTOR";
            $data_array = $this->invoice_model->get_data(array(
                'condition' => "<T>.<PK> = '".$this->fm->str_esc($post['REFNO'], 1)."'",
                'additional_select' => "DEBTOR.NAME AS DEBTOR_NAME, DEBTOR.ADD1 AS DEBTOR_ADD1",
                'additional_join' => $additional_join,  
              
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];
                
                $additional_join = ""; 
                $additional_join .= "LEFT JOIN INVOICE ON INVOICE.REFNO = <T>.REFNO";
                $additional_join .= " LEFT JOIN ITEM ON ITEM.CODE = <T>.ITEM";
                $data['list'] = $this->invitem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "<T>.REFNO",
                    'additional_select' => "ITEM.NAME AS ITEM_NAME",
                    'additional_join' => $additional_join,  
                    '' => "",
                ));

                //Total Item Labour
                $item = $this->invitem_model->get_data(array(
                    'select' => "<T>.LABOUR, <T>.GST, <T>.AMT",
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                ));

                $item_total = array();
                foreach($item as $lv){
                    array_push($item_total, $lv->LABOUR);
                }
                $data['item_total'] = array_sum($item_total);

                //Total Item GST
                $item_gst = array();
                foreach($item as $lv){
                    array_push($item_gst, $lv->GST);
                }
                $data['item_gst'] = array_sum($item_gst);

                //Total Item Amount
                $item_amt = array();
                foreach($item as $lv){
                    array_push($item_amt, $lv->AMT);
                }
                $data['item_amt'] = array_sum($item_amt);

                //Company Profile
                $company = $this->company_profile_model->get_data(array(
                    'condition' => "",
                ));
                $data['company'] = $company[0];
                
                $this->load->view($this->router->fetch_class()."/load_print_en", $data);
                return;
            }
        }
        
        header("HTTP/1.1 500 Internal Server Error");
        header("Content-Type: application/json; charset=UTF-8");
        return;
    }

    public function load_print_no_header(){
        $this->load->model("invoice_model");
        $this->load->model("invitem_model");
        $this->load->model("company_profile_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------

        $data = array();
        $user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;

        if($this->input->post('REFNO') != ""){

            $additional_join = ""; 
            $additional_join .= "LEFT JOIN DEBTOR ON DEBTOR.CODE = <T>.DEBTOR";
            $data_array = $this->invoice_model->get_data(array(
                'condition' => "<T>.<PK> = '".$this->fm->str_esc($post['REFNO'], 1)."'",
                'additional_select' => "DEBTOR.NAME AS DEBTOR_NAME, DEBTOR.ADD1 AS DEBTOR_ADD1",
                'additional_join' => $additional_join,  
              
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];
                
                $additional_join = ""; 
                $additional_join .= "LEFT JOIN INVOICE ON INVOICE.REFNO = <T>.REFNO";
                $additional_join .= " LEFT JOIN ITEM ON ITEM.CODE = <T>.ITEM";
                $data['list'] = $this->invitem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "<T>.REFNO",
                    'additional_select' => "ITEM.NAME AS ITEM_NAME",
                    'additional_join' => $additional_join,  
                    '' => "",
                ));

                //Total Item Labour
                $item = $this->invitem_model->get_data(array(
                    'select' => "<T>.LABOUR, <T>.GST, <T>.AMT",
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                ));

                $item_total = array();
                foreach($item as $lv){
                    array_push($item_total, $lv->LABOUR);
                }
                $data['item_total'] = array_sum($item_total);

                //Total Item GST
                $item_gst = array();
                foreach($item as $lv){
                    array_push($item_gst, $lv->GST);
                }
                $data['item_gst'] = array_sum($item_gst);

                //Total Item Amount
                $item_amt = array();
                foreach($item as $lv){
                    array_push($item_amt, $lv->AMT);
                }
                $data['item_amt'] = array_sum($item_amt);

                //Company Profile
                $company = $this->company_profile_model->get_data(array(
                    'condition' => "",
                ));
                $data['company'] = $company[0];
                
                $this->load->view($this->router->fetch_class()."/load_print_no_header", $data);
                return;
            }
        }
        
        header("HTTP/1.1 500 Internal Server Error");
        header("Content-Type: application/json; charset=UTF-8");
        return;
    }

    public function load_print_en_no_header(){
        $this->load->model("invoice_model");
        $this->load->model("invitem_model");
        $this->load->model("company_profile_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------

        $data = array();
        $user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;

        if($this->input->post('REFNO') != ""){

            $additional_join = ""; 
            $additional_join .= "LEFT JOIN DEBTOR ON DEBTOR.CODE = <T>.DEBTOR";
            $data_array = $this->invoice_model->get_data(array(
                'condition' => "<T>.<PK> = '".$this->fm->str_esc($post['REFNO'], 1)."'",
                'additional_select' => "DEBTOR.NAME AS DEBTOR_NAME, DEBTOR.ADD1 AS DEBTOR_ADD1",
                'additional_join' => $additional_join,  
              
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];
                
                $additional_join = ""; 
                $additional_join .= "LEFT JOIN INVOICE ON INVOICE.REFNO = <T>.REFNO";
                $additional_join .= " LEFT JOIN ITEM ON ITEM.CODE = <T>.ITEM";
                $data['list'] = $this->invitem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "<T>.REFNO",
                    'additional_select' => "ITEM.NAME AS ITEM_NAME",
                    'additional_join' => $additional_join,  
                    '' => "",
                ));

                //Total Item Labour
                $item = $this->invitem_model->get_data(array(
                    'select' => "<T>.LABOUR, <T>.GST, <T>.AMT",
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                ));

                $item_total = array();
                foreach($item as $lv){
                    array_push($item_total, $lv->LABOUR);
                }
                $data['item_total'] = array_sum($item_total);

                //Total Item GST
                $item_gst = array();
                foreach($item as $lv){
                    array_push($item_gst, $lv->GST);
                }
                $data['item_gst'] = array_sum($item_gst);

                //Total Item Amount
                $item_amt = array();
                foreach($item as $lv){
                    array_push($item_amt, $lv->AMT);
                }
                $data['item_amt'] = array_sum($item_amt);

                //Company Profile
                $company = $this->company_profile_model->get_data(array(
                    'condition' => "",
                ));
                $data['company'] = $company[0];
                
                $this->load->view($this->router->fetch_class()."/load_print_en_no_header", $data);
                return;
            }
        }
        
        header("HTTP/1.1 500 Internal Server Error");
        header("Content-Type: application/json; charset=UTF-8");
        return;
    }

    public function load_print_tradein(){
        $this->load->model("tradein_model");
        $this->load->model("tradeitem_model");
        $this->load->model("company_profile_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------

        $data = array();
        $user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;

        if($this->input->post('REFNO') != ""){

            $additional_join = ""; 
            $additional_join .= "LEFT JOIN DEBTOR ON DEBTOR.CODE = <T>.DEBTOR";
            $data_array = $this->tradein_model->get_data(array(
                'condition' => "<T>.<PK> = '".$this->fm->str_esc($post['REFNO'], 1)."'",
                'additional_select' => "DEBTOR.NAME AS DEBTOR_NAME, DEBTOR.ADD1 AS DEBTOR_ADD1",
                'additional_join' => $additional_join,
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];
                
                $additional_join = ""; 
                $additional_join .= "LEFT JOIN TRADEIN ON TRADEIN.REFNO = <T>.REFNO";
                $data['list'] = $this->tradeitem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "<T>.REFNO",
                    'additional_select' => "",
                    'additional_join' => $additional_join,  
                    '' => "",
                ));

                //Company Profile
                $company = $this->company_profile_model->get_data(array(
                    'condition' => "",
                ));
                $data['company'] = $company[0];
                
                $this->load->view($this->router->fetch_class()."/load_print_tradein", $data);
                return;
            }
        }
        
        header("HTTP/1.1 500 Internal Server Error");
        header("Content-Type: application/json; charset=UTF-8");
        return;
    }
    
    public function load_data(){
        $this->load->model("invoice_model");
        $this->load->model("invitem_model");

        $post = $this->input->post();
        
//      print_r($post);
        
        //Config---
        $config['page'] = (int)$this->input->post('PAGE') > 0? (int)$post['PAGE']:1;
        $config['cur_page'] = $config['page'];
        $config['page'] -= 1;
        $config['per_page'] = (int)$this->input->post('PP') > 0? (int)$post['PP']:$this->per_page_array[0];
        $config['previous_btn'] = TRUE;
        $config['next_btn'] = TRUE;
        $config['first_btn'] = TRUE;
        $config['last_btn'] = TRUE;
        //---------
        
        $condition = "";
            
        //Search---
        if($this->input->post('REFNO') != ""){
            $condition = $this->fm->append($condition, "<T>.REFNO LIKE '%".$this->fm->str_esc($post['REFNO'], 1)."%'");
        }

        
        //---------
        
        $data['header_array'] = array(
            array(
                'description' => "#",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "",
            ),

            array(
                'description' => "Ref.No",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.REFNO DESC",
            ),

            array(
                'description' => "Date",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.DATE",
            ),

            array(
                'description' => "Debtor",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.DEBTOR",
            ),

            array(
                'description' => "Transaction Type",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.TT",
            ),

            array(
                'description' => "Staff",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.STAFF",
            ),

            array(
                'description' => "Action",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "",
            ),
        );
        
        $sort = "";
        if($this->input->post('S') != ""){
            $decrypted_s = $this->fm->decrypt($post['S']);
            $sort = $this->input->post('SD') != "1"? $decrypted_s:$this->fm->sort_inverse($decrypted_s);
        }
        
        if($sort == ""){
            foreach($data['header_array'] as $v){
                if(isset($v['sort']) && $v['sort'] != ""){
                    $sort = $v['sort'];
                    break;
                }
            }
        }
        
        $data['count'] = $this->invoice_model->data_count(array(
            'condition' => $condition,
        ));
        
        $max_page = ceil($data['count'] / $config['per_page']);
        if($max_page <= 0) $max_page = 1;
        if($config['cur_page'] > $max_page){
            $config['cur_page'] = $max_page;
            $config['page'] = $max_page - 1;
        }
        $config['start'] = $config['page'] * $config['per_page'];

        $additional_join = ""; 
        $additional_join .= "LEFT JOIN TT ON TT.TT = <T>.TT";
        $additional_join .= " LEFT JOIN STAFF ON STAFF.CODE = <T>.STAFF";
        $additional_join .= " LEFT JOIN DEBTOR ON DEBTOR.CODE = <T>.DEBTOR";
        $data['list'] = $this->invoice_model->get_data(array(
            'condition' => $condition,
            'limit' => $config['per_page'],
            'offset' => $config['start'],
            'sort' => $sort,
            'additional_select' => "TT.TTNAME, STAFF.NAME AS STAFF_NAME, DEBTOR.NAME AS DEBTOR_NAME, DEBTOR.ADD1 AS DEBTOR_ADD1",
            'additional_join' => $additional_join,
        ));
        $data['config'] = $config;
        
        //Access---
        $access_array = $this->fm->get_access(array(14, 15, 16, 67, 68));
        $data['can_create'] = isset($access_array[14]);
        $data['can_edit'] = isset($access_array[15]);
        $data['can_delete'] = isset($access_array[16]);
        $data['can_create_tradein'] = isset($access_array[67]);
        $data['can_delete_tradein'] = isset($access_array[68]);
        //---------
        
        //Store Footprint---
        if($this->record_footprint) $this->footprint_model->record($this->router->fetch_class()."/".$this->router->fetch_method(), isset($_SERVER['QUERY_STRING'])? $_SERVER['QUERY_STRING']:"", isset($_POST)? $_POST:array());
        //------------------
        
        //Set parameter to avoid Filter Data lost---
        $this->session->set_flashdata($this->router->fetch_class().'_page_filter', $_SERVER['QUERY_STRING']);
        //------------------------------------------
    
        $this->load->view($this->router->fetch_class()."/load_data", $data);
    }
}