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

class Brinvoicemodeltest3 extends CI_Model {

    function __construct()
    {
        parent::__construct();
        date_default_timezone_set('Asia/Hong_Kong');
        $this->load->model('BrservicesModel', 'services_model');
        $this->load->model('BrYearModel', 'years_model');
        $this->load->model('Brshopmodel', 'shop_model');
        $this->load->model('Bremployeemodel', 'employee_model');
        $this->load->model('Brcustomermodel', 'customer_model');
        
    }
    
    //added invoicemodel function
    function invoice_exists(){
        return true;
    }
    function check_invoice_exists($invoice_id){
        $this->db->where('id', $invoice_id);
        $this->db->where('delete_time', NULL);
        $query = $this->db->get('brinvoice');
        if($query->num_rows() == 1){
            return true;
        } else {
            return false;
        }
    }
    function insertInvoice($inputdata){

        $customerCheck=false;
        //if empty user_id, insert new customer
        if(empty($inputdata['userId'])){
            
            $code=$this->customer_model->getLastCustomerId($this->session->userdata('currentshop'));

              $data = array(
                'code' => $code ,
                'display_name' => $inputdata['display_name'] ,
                'gender'=>'',
                'dob'=>'',
                'mobile' => $inputdata['mobile'] ,
                'district_id'=>'',
                'area_id'=>'',
                'zone'=>'',
                'address'=>'',
                'join_date'=>'',
                'shop_id'=>$this->session->userdata('currentshop'),
                'skin_improve'=>array(),
                'referred_mobile'=>'',
                'remark'=>'',
                'need_purchase_service'=>'',
                'service_id'=>'',
                'purchased_date'=>'',
                'purchased_qty'=>'',
                'available_qty'=>'',
                'remark2'=>'',
                'promotion_code'=>'',
                'first_registered_tenant_no'=>$this->session->userdata('currentshop'),
                'concurrent_registered_tenant_no'=>$this->session->userdata('currentshop'),
                'level'=>'',
                'isTemp'=>'',
                'channelSelectID'=>'',
                'prefer_pic'=>'',
                'bodyoptionother_text'=>'',
                'faceoptionother_text'=>'',
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );

            $this->customer_model->insertCustomer($data);

            //get customer id
            $newuser_id =$this->customer_model->getCustomerIdByMobile($inputdata['mobile']);

            //end get customer id
            if(!empty($newuser_id)){
                $customerCheck=true;
                $inputdata['userId']=$newuser_id;
            }
            else{
                //cannot enter customer id
                $customerCheck=false;
            }
        }//if(empty($userId)){

        if(!empty($inputdata['userId'])){
            $customerCheck=true;
        }//if(!empty($inputdata['userId'])){

        //end insert new customer 

        //****customer may be not addable because duplicate mobile     

        //if customer check passed, add invoice    

        $totalAmount=0;

        for ($i=0; $i < sizeof($inputdata['product_id_array']); $i++) { 
            $discountRate=1;
            if($inputdata['product_discount_array'][$i]!=0){
                $discountRate=1-($inputdata['product_discount_array'][$i]/100);
            }
            $rowAmount=$inputdata['product_price_array'][$i] *$inputdata['product_qty_array'][$i]*$discountRate;
            $totalAmount=$totalAmount+round($rowAmount);
        }//for ($i=0; $i < sizeof($inputdata['product_id_array']); $i++) {


        $totalPaidAmount=$inputdata['payment_amount_1'] +$inputdata['payment_amount_2'];

        $invoice_status='open';
        if($totalPaidAmount>=$totalAmount){
            $invoice_status='paid';
        }
        //if invoice paid only add one invoice
        //if invoice open add A invoice and B invoice
        //A invoice will be paid
        //B invoice will be leaving amount

        //invoice date
        $invoicedateTimeObject= DateTime::createFromFormat('Y-m-d', $inputdata['invoice_date']);
        $invoicedate =$invoicedateTimeObject->getTimestamp();
        //end invoice date

        $issued_name=$this->getLastInvoiceId($inputdata['shopId'] );
        if( $invoice_status=='paid' ){
            $insertAmount=$totalAmount;
            $loopamount=1;
        }
        elseif( $invoice_status=='open' ){
            $insertAmount=$totalPaidAmount; 
            $leavingAmount= $totalAmount  -$totalPaidAmount;
            $loopamount=2;
        }
        $invoicelist=array();
        $firstInvoiceId="";

        for($y=0;$y<$loopamount;$y++){

         // $i==0 mean first invoice
         // $i==1 mean second partial invoice

            if($y==0){
                $showamount=$insertAmount;
            }
            if($y==1){
                $showamount=$leavingAmount;
            }    
            if($y==0){
                $showinvoice_status='paid';
            }
            if($y==1){
                $showinvoice_status='open';
            }
            if($y==0 && $invoice_status=='paid'){
                $showisseud_name=$issued_name;
                $partialpayment=0;
                $parentid="";
            }
            if($y==0 && $invoice_status=='open'){
                $showisseud_name=$issued_name."A";
                $partialpayment=1;
                $parentid="";
            }
            if($y==1 && $invoice_status=='open'){
                $showisseud_name=$issued_name."B";
                $partialpayment=1;
                $parentid=$insert_id;//which is second loop  of below
                //first insert invoice id
            }
         $data = array(
            'user_id' => $inputdata['userId'] ,
            'therapist_id' => $inputdata['pic_1'] ,
            'consultant_id' => $inputdata['consultant_1'] ,
            'issued_name' => $showisseud_name ,
            'total_amount_due' => $showamount,
            'invoice_status' => $showinvoice_status,
            'status' =>1,
            'shopId' => $inputdata['shopId'] ,
            // 'created_by'=>
            // updated_by
            'display' => 0 ,// 0 stand for display, 1 stand for not display
            'parent_id' => $parentid ,
            'partialpayment' =>$partialpayment,
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );
           // date_default_timezone_set('UTC');
           //$this->db->set('issued_date', time(), FALSE);

           $this->db->set('issued_date', $invoicedate, FALSE);
           

           $this->db->set('update_time', time(), FALSE);
           $this->db->set('create_time', time(), FALSE);
           $query=$this->db->insert('brinvoice', $data);


           //insert invoice item
           $insert_id = $this->db->insert_id();
           if($y==0){
            //for insert useritem to add first invoice id
            $firstInvoiceId=$insert_id;
           }
           for ($i=0; $i < sizeof($inputdata['product_id_array']); $i++) { 

            $discountRate=1;
            if($inputdata['product_discount_array'][$i]!=0){
                $discountRate=1-($inputdata['product_discount_array'][$i]/100);
            }


             $serviceRow= $this->services_model->getServices($inputdata['product_id_array'][$i]);
             $rowAmount=round($inputdata['product_price_array'][$i] *$inputdata['product_qty_array'][$i]*$discountRate);

            $inputRemark=null;
            if(!empty($inputdata['product_remark_array'][$i])){
                $inputRemark=$inputdata['product_remark_array'][$i];
            }

             $data = array(
            'invoice_id' => $insert_id ,
            'item_id' => $inputdata['product_id_array'][$i] ,
            'item_name' => $serviceRow->name ,
            'price' => $inputdata['product_price_array'][$i] ,
            'qty' => $inputdata['product_qty_array'][$i] ,
            'discount' => $inputdata['product_discount_array'][$i],
            'amount' => $rowAmount,
            'remark' => $inputRemark
            // item_status
            // 'status' =>1,
            // 'shopId' => $inputdata['shopId'] ,
            // // 'created_by'=>
            // // updated_by
            // 'display' => 0 ,// 0 stand for display, 1 stand for not display
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );
             $query=$this->db->insert('brinvoice_item', $data);


           }//for ($i=0; $i < sizeof($inputdata['product_id_array']); 
           //end insert invoice item


           //add payment
          // $i==0 mean first invoice
         // $i==1 mean second partial invoice

            if($y==0){
                $showpayment_amount1=$inputdata['payment_amount_1'];
                $showpayment_type1=$inputdata['payment_type_1'];
            
            }
            if($y==1){
                 $showpayment_amount1="";
                 $showpayment_type1=""; 
            }
           // add payment 1
           $data = array(
            'invoice_id' => $insert_id ,
            'payment_amount' => $showpayment_amount1 ,
            'payment_type' => $showpayment_type1  ,
        
            // item_status
            // 'status' =>1,
            // 'shopId' => $inputdata['shopId'] ,
            // // 'created_by'=>
            // // updated_by
            // 'display' => 0 ,// 0 stand for display, 1 stand for not display
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );


           // $this->db->set('payment_date', time(), FALSE);
            $this->db->set('payment_date', $invoicedate, FALSE);
             $query=$this->db->insert('brpurchase_payment', $data);

           //end payment 1


             if($y==0){
                $showpayment_amount2=$inputdata['payment_amount_2'];
                $showpayment_type2=$inputdata['payment_type_2'];
            
            }
            if($y==1){
                 $showpayment_amount2="";
                 $showpayment_type2=""; 
            }
            // add payment 2
            $data = array(
            'invoice_id' => $insert_id ,
            'payment_amount' => $showpayment_amount2 ,
            'payment_type' => $showpayment_type2  ,
        
            // item_status
            // 'status' =>1,
            // 'shopId' => $inputdata['shopId'] ,
            // // 'created_by'=>
            // // updated_by
            // 'display' => 0 ,// 0 stand for display, 1 stand for not display
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );
           // $this->db->set('payment_date', time(), FALSE);

           $this->db->set('payment_date', $invoicedate, FALSE);
             $query=$this->db->insert('brpurchase_payment', $data);

           //end payment 2
           //end add payment

           // }//if($i==0){ end //only first invoice insert payment method
                
            array_push($invoicelist,$insert_id);     
        }//for($i=0;$i<=$loopamount;$i++){        

           //add user service
           // input invoice id
             for ($i=0; $i < sizeof($inputdata['product_id_array']); $i++) {
                // echo "product_add_ticker_array";
                // echo $inputdata['product_add_ticker_array'][$i];
                // 1 means checked at invoice
                // 0 means not checed at invoice
                if($inputdata['product_add_ticker_array'][$i]==1){

                    //for input remark
                    $inputRemark=null;
                    if(!empty($inputdata['product_remark_array'][$i])){
                             $inputRemark=$inputdata['product_remark_array'][$i];
                    }
                    //end for input remark   


                    $category_id=$this->services_model->getCategoryid($inputdata['product_id_array'][$i]);

                    date_default_timezone_set('Asia/Hong_Kong');

                    $discountRate=1;
                    if($inputdata['product_discount_array'][$i]!=0){
                      $discountRate=$inputdata['product_discount_array'][$i]/100;
                     }


                    $rowAmount=round($inputdata['product_price_array'][$i] *$inputdata['product_qty_array'][$i]*$discountRate);
                    $data= array(
                    


                    'category_id'=>$category_id,
                    'user_id' => $inputdata['userId'] ,
                    'service_id' => $inputdata['product_id_array'][$i] ,
                    'purchased_date' =>  time(),
                    'unit_price' =>$inputdata['product_price_array'][$i],
                    'purchased_price' => $rowAmount,
                    // 'fullName' => $data['inputadminname'] ,
                    'purchased_qty' => $inputdata['product_qty_array'][$i] ,
                    'available_qty' => $inputdata['product_qty_array'][$i] ,
                    'status' => 1 ,
                    'display' => 0 ,
                    'invoice_id' => $firstInvoiceId ,
                    'remark' => $inputRemark,
                    );
                    $this->db->set('update_time', time(), FALSE);
                    $this->db->set('create_time', time(), FALSE);

                     $query=$this->db->insert('brservice_user', $data);

                }//if($inputdata['product_add_ticker_array'][$i]==true){

                

              

             }//for ($i=0; $i < sizeof($inputdata['product_id_array']); $i++) {   



           //end add user service


           // return $insert_id;
           return $invoicelist;
    }//function insertInvoice($data){

    function updateInvoicePayment($inputdata){

        date_default_timezone_set('Asia/Hong_Kong');
        $paymentdateTimeObject= DateTime::createFromFormat('Y-m-d', $inputdata['paymentdate']);
        $paymentdate =$paymentdateTimeObject->getTimestamp();

        //check payment equal invoice amount
        //if payment amount not equal invoice amount
        //slip payment to A/B invoice or B/C invoice

        $invoiceDetailList=$this->getInvoiceWithDetail($inputdata['invoiceid']);
        // echo "total amount due";
        // echo $invoiceDetailList[0]['total_amount_due'];

        $totalAmount=$invoiceDetailList[0]['total_amount_due'];

        $totalPaidAmount=$inputdata['payment_amount_1'] +$inputdata['payment_amount_2'];

        $invoice_status='open';
        if($totalPaidAmount>=$totalAmount){
            $invoice_status='paid';
        }
        //update payment 1 & payment 2
            //update payment 1
            $data = array(
            'payment_amount' => $inputdata['payment_amount_1']  ,
            'payment_type' => $inputdata['payment_type_1']  ,
            );
            $this->db->set('update_time', time(), FALSE);

            //added update payment date at 2020-11-13
            $this->db->set('payment_date', $paymentdate, FALSE);
            //end added update payment date at 2020-11-13

           // $this->db->set('receipt_date', time(), FALSE);
            $this->db->where('id',$inputdata['payment_id_1']);
           $query=$this->db->update('brpurchase_payment', $data);
           //end update payment 1

           //update payment 2
            $data = array(
            'payment_amount' => $inputdata['payment_amount_2']  ,
            'payment_type' => $inputdata['payment_type_2']  ,
            );
            $this->db->set('update_time', time(), FALSE);

            //added update payment date at 2020-11-13
            $this->db->set('payment_date', $paymentdate, FALSE);
            //end added update payment date at 2020-11-13

           // $this->db->set('receipt_date', time(), FALSE);
            $this->db->where('id',$inputdata['payment_id_2']);
           $query=$this->db->update('brpurchase_payment', $data);
           //end update payment 2
        //end update payment 1 & payment 2

        if($invoice_status=='paid'){
            //no need to slip invoice
            //just update to paid invoice
            $data = array(
            'invoice_status' => 'paid' ,
            
            );

           // date_default_timezone_set('UTC');
           $this->db->set('update_time', time(), FALSE);

           //added update payment date at 2020-11-13
            $this->db->set('issued_date', $paymentdate, FALSE);
            //end added update payment date at 2020-11-13


           // $this->db->set('receipt_date', time(), FALSE);
            $this->db->where('id',$inputdata['invoiceid']);
           $query=$this->db->update('brinvoice', $data);
           $invoicelist=array();
           array_push($invoicelist,$inputdata['invoiceid']);
           return $invoicelist;
        }//if($invoice_status=='paid'){

        if($invoice_status=='open'){
            //slip invoice and return array of two
            //update current invoice to paid and paid amount
            //add one more invoice with items of same current 

            
            //update current invoice to paid and change the amount to paid amount
            $data = array(
            'invoice_status' => 'paid' ,
            'total_amount_due' =>$totalPaidAmount,
            );

           // date_default_timezone_set('UTC');
           $this->db->set('update_time', time(), FALSE);

           //added update payment date at 2020-11-13
            $this->db->set('issued_date', $paymentdate, FALSE);
            //end added update payment date at 2020-11-13

           // $this->db->set('receipt_date', time(), FALSE);
            $this->db->where('id',$inputdata['invoiceid']);
           $query=$this->db->update('brinvoice', $data);
            //end update current invoice to paid and change the amount to paid amount

           //add one more invoice with items of same current
           $leavingAmount= $totalAmount  -$totalPaidAmount;
           $inputisseud_name=$invoiceDetailList[0]['issued_name'];
           //limit to only 26 slip invoice can do 

           $invoiceNum=substr($inputisseud_name, 0, -1);
           $lastInvoiceChar=substr($inputisseud_name, -1); 
           $nextInvoiceChar=++$lastInvoiceChar;

           //add a invoice
            $data = array(
            'user_id' => $invoiceDetailList[0]['user_id'] ,
            'therapist_id' => $invoiceDetailList[0]['therapist_id'] ,
            'consultant_id' => $invoiceDetailList[0]['consultant_id'] ,
            'issued_name' => $invoiceNum.$nextInvoiceChar ,
            'total_amount_due' => $leavingAmount,
            'invoice_status' =>'open',
            'status' =>1,
            'shopId' => $invoiceDetailList[0]['shopId'] ,
            // 'created_by'=>
            // updated_by
            'display' => 0 ,// 0 stand for display, 1 stand for not display
            'parent_id' => $invoiceDetailList[0]['parent_id'] ,
            'partialpayment' =>$invoiceDetailList[0]['partialpayment'],
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );
           // date_default_timezone_set('UTC');
           //$this->db->set('issued_date', time(), FALSE);

           //added update payment date at 2020-11-13
            $this->db->set('issued_date', $paymentdate, FALSE);
            //end added update payment date at 2020-11-13


           $this->db->set('update_time', time(), FALSE);
           $this->db->set('create_time', time(), FALSE);
           $query=$this->db->insert('brinvoice', $data);

           //end add a invoice

           //add invoice item
           $invoiceitemlist=$this->getInvoiceItemDetail($inputdata['invoiceid']);
           //insert invoice item
           $insert_id = $this->db->insert_id();
           foreach($invoiceitemlist as $invoiceitemRow){

            // $discountRate=1;
            // if($inputdata['product_discount_array'][$i]!=0){
            //     $discountRate=$inputdata['product_discount_array'][$i]/100;
            // }


            //  $serviceRow= $this->services_model->getServices($inputdata['product_id_array'][$i]);
            //  $rowAmount=round($inputdata['product_price_array'][$i] *$inputdata['product_qty_array'][$i]*$discountRate);

             $data = array(
            'invoice_id' => $insert_id ,
            'item_id' => $invoiceitemRow->item_id ,
            'item_name' => $invoiceitemRow->item_name ,
            'price' => $invoiceitemRow->price ,
            'qty' => $invoiceitemRow->qty ,
            'discount' => $invoiceitemRow->discount,
            'amount' => $invoiceitemRow->amount,
            'item_status' => $invoiceitemRow->item_status
            // item_status
            // 'status' =>1,
            // 'shopId' => $inputdata['shopId'] ,
            // // 'created_by'=>
            // // updated_by
            // 'display' => 0 ,// 0 stand for display, 1 stand for not display
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );
             $query=$this->db->insert('brinvoice_item', $data);


           }//foreach($invoiceitemlist as $invoiceitemRow){
           //end insert invoice item
           //end add invoice item


              //add payment
          // $i==0 mean first invoice
         // $i==1 mean second partial invoice

        
                 $showpayment_amount1="";
                 $showpayment_type1=""; 
      
           // add payment 1
           $data = array(
            'invoice_id' => $insert_id ,
            'payment_amount' => $showpayment_amount1 ,
            'payment_type' => $showpayment_type1  ,
        
            // item_status
            // 'status' =>1,
            // 'shopId' => $inputdata['shopId'] ,
            // // 'created_by'=>
            // // updated_by
            // 'display' => 0 ,// 0 stand for display, 1 stand for not display
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );
           //$this->db->set('payment_date', time(), FALSE);
           //added update payment date at 2020-11-13
            $this->db->set('payment_date', $paymentdate, FALSE);
            //end added update payment date at 2020-11-13


             $query=$this->db->insert('brpurchase_payment', $data);

           //end payment 1



                 $showpayment_amount2="";
                 $showpayment_type2=""; 
      
            // add payment 2
            $data = array(
            'invoice_id' => $insert_id ,
            'payment_amount' => $showpayment_amount2 ,
            'payment_type' => $showpayment_type2  ,
        
            // item_status
            // 'status' =>1,
            // 'shopId' => $inputdata['shopId'] ,
            // // 'created_by'=>
            // // updated_by
            // 'display' => 0 ,// 0 stand for display, 1 stand for not display
            // 'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );
           //$this->db->set('payment_date', time(), FALSE);

           //added update payment date at 2020-11-13
            $this->db->set('payment_date', $paymentdate, FALSE);
            //end added update payment date at 2020-11-13

             $query=$this->db->insert('brpurchase_payment', $data);

           //end payment 2
           //end add payment

           //end add one more invoice with items of same current

            //return two invoice number
             $invoicelist= array();
             array_push($invoicelist,$inputdata['invoiceid']); 
             array_push($invoicelist,$insert_id); 

            //end return two invoice number
             return $invoicelist;
        }//if($invoice_status=='open'){

    }//function updateInvoicePayment($data){
     function getLastInvoiceId($shopid){
        $year=$this->years_model->getFinancialYear();
        $shortYear=substr( $year, -2);

        $shopRow=$this->shop_model->getShopbyid($shopid);
        $shortcode=$shopRow->shortcode;

        $invoiceHead='IN'.$shortcode.'-'.$shortYear.'-';


        
        $this->db->select("*");
        $this->db->from('brinvoice');
        $this->db->like('issued_name', $invoiceHead);
        $this->db->where('shopId', $shopid);
         $this->db->order_by('issued_name', 'DESC');    
        $issued_name = $this->db->get()->row()->issued_name;

        $invoice_num = substr($issued_name, -6);
        $invoice_num = $invoice_num+1;

        $printInvoicenum=str_pad($invoice_num, 6, '0', STR_PAD_LEFT);

        $printInvoice=$invoiceHead.$printInvoicenum;

        return $printInvoice;
    }//function getCustServiceByRowId($id){
    function getReceiptRow($invoiceid){
        //get receipt number by invoice id
        //if null, get last receipt number 
        //and update all payment with lastest receipt number
        $this->db->select("receipt_num,receipt_date");
        $this->db->from('brpurchase_payment');
        $this->db->where('invoice_id', $invoiceid);
        $this->db->order_by('id', 'DESC');    
        $receipt_row = $this->db->get()->row();
        $receipt_num=$receipt_row->receipt_num;
        if(!empty($receipt_num)){
            return $receipt_row;
        }
        else{
            $shopid=$this->getShopIdByInvoiceId($invoiceid);
            $receiptid=$this->getLastReceiptId($shopid);
            $this->updateReceiptNum($invoiceid,$receiptid);

            //get updated row
            $this->db->select("receipt_num,receipt_date");
            $this->db->from('brpurchase_payment');
            $this->db->where('invoice_id', $invoiceid);
            $this->db->order_by('id', 'DESC');    
            $receipt_row = $this->db->get()->row();

            //end get updated row


            return $receipt_row;
        }//else{



    }//function getReceiptNum($invoiceid){
    function getShopIdByInvoiceId($invoiceid){
        $this->db->select("shopId");
        $this->db->from('brinvoice');
        $this->db->where('id', $invoiceid);   
        $shopId = $this->db->get()->row()->shopId;
        return $shopId;
    }//function getShopIdByInvoiceId($invoiceid){
    function getLastReceiptId($shopid){
        $year=$this->years_model->getFinancialYear();
        $shortYear=substr( $year, -2);

        $shopRow=$this->shop_model->getShopbyid($shopid);
        $shortcode=$shopRow->shortcode;

        $invoiceHead='RE'.$shortcode.'-'.$shortYear.'-';


        
        $this->db->select("*");
        $this->db->from('brpurchase_payment');
        $this->db->like('receipt_num', $invoiceHead);
        // $this->db->where('shopId', $shopid);
         $this->db->order_by('receipt_num', 'DESC');    
        $receipt_num = $this->db->get()->row()->receipt_num;

        $receipt_num = substr($receipt_num, -6);
        $receipt_num = $receipt_num+1;

        $printReceiptnum=str_pad($receipt_num, 6, '0', STR_PAD_LEFT);

        $printReceipt=$invoiceHead.$printReceiptnum;

        return $printReceipt;
    }//function getCustServiceByRowId($id){
    function updateReceiptNum($invoiceid,$receiptid){
        $data = array(
            'receipt_num' => $receiptid ,
            
            );

           // date_default_timezone_set('UTC');
           $this->db->set('update_time', time(), FALSE);
           $this->db->set('receipt_date', time(), FALSE);
            $this->db->where('invoice_id',$invoiceid);
           $query=$this->db->update('brpurchase_payment', $data);

           return $query;
    }
    function getInvoiceAll($shopid)
    {
        
        $this->db->from('brinvoice');
        // $this->db->where(array('show' => 1));
        $this->db->where('delete_time', NULL);   
        $this->db->where('shopId',$shopid);   
        // $this->db->order_by('rank');
        $this->db->order_by('issued_date','DESC');
        $query = $this->db->get();
        return $query->result();
     


    }

    function getInvoiceAllWithDetail($shopid)
    {
        $this->db->select("brinvoice.id,brinvoice.issued_date,brinvoice.issued_name,cust.display_name,cust.chi_name,cust.mobile,brinvoice.total_amount_due,brinvoice.invoice_status,brinvoice.user_id");
        
        $this->db->from('brinvoice');
        $this->db->join ( 'brcustomer as cust', 'cust.id = brinvoice.user_id');
        // $this->db->where(array('show' => 1));
        $this->db->where('brinvoice.delete_time', NULL);   
        $this->db->where('brinvoice.shopId',$shopid);   
        // $this->db->order_by('rank');
        $this->db->order_by('issued_date','DESC');
        $query = $this->db->get();
        $invoicelist= $query->result();
        //

        //get total payment list of all invoice
            $this->db->select("payment_amount,invoice_id");
            $this->db->from('brpurchase_payment');
            $this->db->where('delete_time', NULL);   
            //$this->db->where('invoice_id',$invoicerow->id);  
            $query = $this->db->get();
            $totalpaymentlist= $query->result();
        //end get total payment list of all invoice

        $data=array();
        foreach ($invoicelist as $invoicerow) { 
            $datarow=array();
            $datarow['id']= $invoicerow->id;
            $datarow['user_id']= $invoicerow->user_id;
            $datarow['chi_name']= $invoicerow->chi_name;
            $datarow['issued_date']= $invoicerow->issued_date;
            $datarow['issued_name']= $invoicerow->issued_name;
            $datarow['display_name']= $invoicerow->display_name;
            $datarow['mobile']= $invoicerow->mobile;
            $datarow['total_amount_due']= $invoicerow->total_amount_due;
            $datarow['invoice_status']= $invoicerow->invoice_status;


            //calculate total payment
            $totalPaid=0;
            // $this->db->select("payment_amount");
            // $this->db->from('brpurchase_payment');
            // $this->db->where('delete_time', NULL);   
            // $this->db->where('invoice_id',$invoicerow->id);  
            // $query = $this->db->get();
            // $paymentlist= $query->result();
            // foreach ($paymentlist as $paymentrow) { 
            //     $totalPaid=$totalPaid+$paymentrow->payment_amount;
            // }//foreach ($paymentlist as $paymentrow) { 
            foreach ($totalpaymentlist as $paymentrow) {  
                if($paymentrow->invoice_id==$invoicerow->id){
                    $totalPaid=$totalPaid+$paymentrow->payment_amount;
                }   
            }

            $missedAmount=$datarow['total_amount_due']-$totalPaid;

            $datarow['missedAmount']= $missedAmount;


            //end calculate total payment 
            array_push($data,$datarow);
        }//foreach ($invoicelist as $invoicerow) {
        return $data;
    }

    function getInvoiceAllShopWithDetail($shopid, $secondshopid){
        $this->db->select("brinvoice.id,brinvoice.issued_date,brinvoice.issued_name,cust.display_name,cust.chi_name,cust.mobile,brinvoice.total_amount_due,brinvoice.invoice_status,brinvoice.user_id");
        
        $this->db->from('brinvoice');
        $this->db->join ( 'brcustomer as cust', 'cust.id = brinvoice.user_id');
        // $this->db->where(array('show' => 1));
        $this->db->where('brinvoice.delete_time', NULL);   
        $this->db->where('brinvoice.shopId',$shopid);   
        $this->db->or_where('brinvoice.shopId',$secondshopid); //added line to search second shop
        // $this->db->order_by('rank');
        $this->db->order_by('issued_date','DESC');
        $query = $this->db->get();
        $invoicelist= $query->result();
        //
        //get total payment list of all invoice
            $this->db->select("payment_amount,invoice_id");
            $this->db->from('brpurchase_payment');
            $this->db->where('delete_time', NULL);   
            //$this->db->where('invoice_id',$invoicerow->id);  
            $query = $this->db->get();
            $totalpaymentlist= $query->result();
        //end get total payment list of all invoice

        $data=array();
        foreach ($invoicelist as $invoicerow) { 
            $datarow=array();
            $datarow['id']= $invoicerow->id;
            $datarow['user_id']= $invoicerow->user_id;
            $datarow['chi_name']= $invoicerow->chi_name;
            $datarow['issued_date']= $invoicerow->issued_date;
            $datarow['issued_name']= $invoicerow->issued_name;
            $datarow['display_name']= $invoicerow->display_name;
            $datarow['mobile']= $invoicerow->mobile;
            $datarow['total_amount_due']= $invoicerow->total_amount_due;
            $datarow['invoice_status']= $invoicerow->invoice_status;


            //calculate total payment
            $totalPaid=0;
            // $this->db->select("payment_amount");
            // $this->db->from('brpurchase_payment');
            // $this->db->where('delete_time', NULL);   
            // $this->db->where('invoice_id',$invoicerow->id);  
            // $query = $this->db->get();
            // $paymentlist= $query->result();
            // foreach ($paymentlist as $paymentrow) { 
            //     $totalPaid=$totalPaid+$paymentrow->payment_amount;
            // }//foreach ($paymentlist as $paymentrow) { 
            foreach ($totalpaymentlist as $paymentrow) {  
                if($paymentrow->invoice_id==$invoicerow->id){
                    $totalPaid=$totalPaid+$paymentrow->payment_amount;
                }   
            }
            $missedAmount=$datarow['total_amount_due']-$totalPaid;

            $datarow['missedAmount']= $missedAmount;


            //end calculate total payment 
            array_push($data,$datarow);
        }//foreach ($invoicelist as $invoicerow) {
        return $data;
    }//function getInvoiceAllShopWithDetail($shopid, $secondshopid){


    function getInvoiceWithDetail($invoiceId){
        $this->db->select("brinvoice.id,brinvoice.parent_id,brinvoice.partialpayment,brinvoice.invoice_status,brinvoice.issued_date,brinvoice.issued_name,cust.display_name,cust.chi_name,cust.mobile,brinvoice.total_amount_due,brinvoice.invoice_status,brinvoice.user_id,bshop.name as shopname,brinvoice.therapist_id,brinvoice.consultant_id,brinvoice.parent_id,brinvoice.partialpayment,brinvoice.shopId");
        
        $this->db->from('brinvoice');
        $this->db->join ( 'brcustomer as cust', 'cust.id = brinvoice.user_id');
        $this->db->join ( 'bshop as bshop', 'bshop.id = brinvoice.shopId');
        // $this->db->where(array('show' => 1));
        // $this->db->where('brinvoice.delete_time', NULL);   
        $this->db->where('brinvoice.id',$invoiceId);   
        // $this->db->order_by('rank');
        // $this->db->order_by('issued_date','DESC');
        $query = $this->db->get();
        $invoicelist= $query->result();


        $data=array();
        foreach ($invoicelist as $invoicerow) { 
            $datarow=array();
            $datarow['id']= $invoicerow->id;
            $datarow['user_id']= $invoicerow->user_id;
            $datarow['issued_date']= $invoicerow->issued_date;
            $datarow['issued_name']= $invoicerow->issued_name;
            $datarow['display_name']= $invoicerow->display_name;
            $datarow['chi_name']= $invoicerow->chi_name;
            $datarow['mobile']= $invoicerow->mobile;
            $datarow['total_amount_due']= $invoicerow->total_amount_due;
            $datarow['invoice_status']= $invoicerow->invoice_status;
            $datarow['shopname']= $invoicerow->shopname;
            $datarow['therapist_id']= $invoicerow->therapist_id;
            $employeeRow=$this->employee_model->getEmployee($datarow['therapist_id']);
            $datarow['therapist_name']="";
            if(!empty($employeeRow->chi_name)){
            $datarow['therapist_name']=$employeeRow->chi_name;
            }
            $datarow['consultant_id']= $invoicerow->consultant_id;
            $employeeRow=$this->employee_model->getEmployee($datarow['consultant_id']);

            $datarow['consultant_name']="";
            if(!empty($employeeRow->chi_name)){
                $datarow['consultant_name']=$employeeRow->chi_name;
            }
            
            $datarow['parent_id']= $invoicerow->parent_id;
            $datarow['partialpayment']= $invoicerow->partialpayment;
            $datarow['shopId']= $invoicerow->shopId;
         //end calculate total payment 
            array_push($data,$datarow);
        }//foreach ($invoicelist as $invoicerow) {
        return $data;

    }
    function getInvoiceItemDetail($invoiceId){
        $this->db->select("*");
        $this->db->from('brinvoice_item');
        // $this->db->where(array('show' => 1));
        $this->db->where('delete_time', NULL);   
        $this->db->where('invoice_id',$invoiceId);   
        // $this->db->order_by('rank');
        $this->db->order_by('id','ASC');
        $query = $this->db->get();
        return $query->result();
        // $itemlist=$query->result();

        //  $data=array();
        // foreach ($itemlist as $itemrow) { 
        //     $datarow=array();
        //     $datarow['id']= $itemrow->id;
        //     $datarow['invoice_id']= $itemrow->user_id;
        //     $datarow['item_id']= $itemrow->item_id;
        //     $datarow['item_name']= $itemrow->item_name;
        //     $datarow['item_timeslot']= $itemrow->item_timeslot;
        //     $datarow['price']= $itemrow->price;
        //     $datarow['qty']= $itemrow->qty;
        //     $datarow['discount']= $itemrow->discount;
        //     $datarow['amount']= $itemrow->amount;
        //     $datarow['item_status']= $itemrow->item_status;
        //     $datarow['create_time']= $itemrow->create_time;
        //     $datarow['create_by']= $itemrow->create_by;
        //     $datarow['update_time']= $itemrow->update_time;
        //     $datarow['updated_by']= $itemrow->updated_by;
        //     $datarow['delete_time']= $itemrow->delete_time;
        //  //end calculate total payment 
        //     array_push($data,$datarow);
        // }//foreach ($invoicelist as $invoicerow) {
        // return $data;
    }
    function countOneMonthInvoice($shopid){
        $first_minute = mktime(0, 0, 0, date("n"), 1);
        $last_minute = mktime(23, 59, 59, date("n"), date("t"));

        // $times  = array();
        // for($month = 1; $month <= 12; $month++) {
        //   $first_minute = mktime(0, 0, 0, $month, 1);
        //   $last_minute = mktime(23, 59, 59, $month, date('t', $first_minute));
        //   $times[$month] = array($first_minute, $last_minute);
        // }

          $this->db->select('SUM(total_amount_due) as sum');
         $this->db->from('brinvoice');
         $this->db->where('issued_date >=', $first_minute);
        $this->db->where('issued_date <=', $last_minute);
        $this->db->where('delete_time', NULL);
        $this->db->where('shopId', $shopid);
        // $this->db->where('startdate', date("Y-m-d"));
        // $this->db->where('shop_id',$id);
        // $this->db->order_by('startdate DESC');
        $query = $this->db->get();
        return $query->row()->sum;
    }  
    function countOneMonthInvoiceById($shopid,$userid){
        $first_minute = mktime(0, 0, 0, date("n"), 1);
        $last_minute = mktime(23, 59, 59, date("n"), date("t"));

        // $times  = array();
        // for($month = 1; $month <= 12; $month++) {
        //   $first_minute = mktime(0, 0, 0, $month, 1);
        //   $last_minute = mktime(23, 59, 59, $month, date('t', $first_minute));
        //   $times[$month] = array($first_minute, $last_minute);
        // }

          $this->db->select('SUM(total_amount_due) as sum');
         $this->db->from('brinvoice');
         $this->db->where('issued_date >=', $first_minute);
        $this->db->where('issued_date <=', $last_minute);
        $this->db->group_start();
        $this->db->where('therapist_id',$userid);
        $this->db->or_where('consultant_id',$userid);
        $this->db->group_end();
        $this->db->where('delete_time', NULL);
        $this->db->where('shopId', $shopid);
        // $this->db->where('startdate', date("Y-m-d"));
        // $this->db->where('shop_id',$id);
        // $this->db->order_by('startdate DESC');
        $query = $this->db->get();
        return $query->row()->sum;
    }        
    function countOneMonthPayment($shopId) {
       $first_minute = mktime(0, 0, 0, date("n"), 1);
        $last_minute = mktime(23, 59, 59, date("n"), date("t"));


        $this->db->select('SUM(payment_amount) as sum');
        $this->db->from('brpurchase_payment as puchase');
        $this->db->join('brinvoice as invoice', 'invoice.id=puchase.invoice_id');
         $this->db->where('payment_date >=', $first_minute);
        $this->db->where('payment_date <=', $last_minute);
        $this->db->where('invoice.delete_time', NULL);
        $this->db->where('invoice.shopId', $shopId);
        // $this->db->where('shopId', $shopId);
        // // $this->db->where('shop_id',$id);
        // $this->db->group_start();
        // $this->db->where('pic_1',$userid);
        // $this->db->or_where('pic_2',$userid);
        // $this->db->group_end();
        // $this->db->where('startdate', date("Y-m-d"));
        // $this->db->order_by('startdate DESC');
         $query = $this->db->get();

        return $query->row()->sum;
    }
     function countOneMonthPaymentById($shopId,$userid) {
       $first_minute = mktime(0, 0, 0, date("n"), 1);
        $last_minute = mktime(23, 59, 59, date("n"), date("t"));


        $this->db->select('SUM(payment_amount) as sum');
        $this->db->from('brpurchase_payment as puchase');
        $this->db->join('brinvoice as invoice', 'invoice.id=puchase.invoice_id');
         $this->db->where('payment_date >=', $first_minute);
        $this->db->where('payment_date <=', $last_minute);
         $this->db->group_start();
        $this->db->where('invoice.therapist_id',$userid);
        $this->db->or_where('invoice.consultant_id',$userid);
        $this->db->group_end();
        $this->db->where('invoice.delete_time', NULL);
         $this->db->where('invoice.shopId', $shopId);
        // $this->db->where('shopId', $shopId);
        // // $this->db->where('shop_id',$id);
        // $this->db->group_start();
        // $this->db->where('pic_1',$userid);
        // $this->db->or_where('pic_2',$userid);
        // $this->db->group_end();
        // $this->db->where('startdate', date("Y-m-d"));
        // $this->db->order_by('startdate DESC');
         $query = $this->db->get();
         
        return $query->row()->sum;
    }

   
    function countCustomerOrderPrecent(){

       // $datetime = DateTime::createFromFormat('Y/m/d h:i A', $datetime);
       // $timestamp = $datetime->getTimestamp();
       //one month before

      $oneMonthBefore = date("Y-m-d", strtotime( date( "Y-m-d", strtotime( date("Y-m-d") ) ) . "-1 month" ) );
      $onemonthdatetime = DateTime::createFromFormat('Y-m-d', $oneMonthBefore);

      $first_minute = $onemonthdatetime->getTimestamp();
      $last_minute = mktime(23, 59, 59, date("n"), date("t"));


       $this->db->select('COUNT(id) as sum');
        $this->db->from('brcustomer as puchase');
        // $this->db->join('brinvoice as invoice', 'invoice.id=puchase.invoice_id');
         $this->db->where('create_time >=', $first_minute);
        $this->db->where('create_time <=', $last_minute);
        //  $this->db->group_start();
        // $this->db->where('invoice.therapist_id',$userid);
        // $this->db->or_where('invoice.consultant_id',$userid);
        // $this->db->group_end();
        // $this->db->where('invoice.delete_time', NULL);
        //  $this->db->where('invoice.shopId', $shopId);
        // $this->db->where('shopId', $shopId);
        // // $this->db->where('shop_id',$id);
        // $this->db->group_start();
        // $this->db->where('pic_1',$userid);
        // $this->db->or_where('pic_2',$userid);
        // $this->db->group_end();
        // $this->db->where('startdate', date("Y-m-d"));
        // $this->db->order_by('startdate DESC');
         $query = $this->db->get();
         
        // return $query->row()->sum;
        // return $query->row()->sum;

        $totalNewCust=$query->row()->sum;

        $this->db->select('COUNT(id) as sum');
        $this->db->from('brcustomer as cust');
        // $this->db->join('brinvoice as invoice', 'invoice.id=puchase.invoice_id');
         $this->db->where('create_time >=', $first_minute);
        $this->db->where('create_time <=', $last_minute);
        // $this->db->where('EXISTS (SELECT user_id FROM  brservice_user WHERE invoice_id != NULL AND  cust.id= brservice_user.user_id)', '', FALSE);

        $this->db->where('cust.id in','(SELECT user_id FROM  brservice_user WHERE invoice_id IS NOT NULL)', false);

        //  $this->db->group_start();
        // $this->db->where('invoice.therapist_id',$userid);
        // $this->db->or_where('invoice.consultant_id',$userid);
        // $this->db->group_end();
        // $this->db->where('invoice.delete_time', NULL);
        //  $this->db->where('invoice.shopId', $shopId);
        // $this->db->where('shopId', $shopId);
        // // $this->db->where('shop_id',$id);
        // $this->db->group_start();
        // $this->db->where('pic_1',$userid);
        // $this->db->or_where('pic_2',$userid);
        // $this->db->group_end();
        // $this->db->where('startdate', date("Y-m-d"));
        // $this->db->order_by('startdate DESC');
         $query = $this->db->get();
         
        // return $query->row()->sum;
        // return $query->row()->sum;

        $totalNewCustHaveInvoice=$query->row()->sum;
        $outprecent=($totalNewCustHaveInvoice/$totalNewCust)*100;
        return round($outprecent,0);
        // return $this->db->last_query();

        // return $first_minute;
        // return 123;


    }//function countCustomerOrderPrecent(){
     function countCustomerOrderPrecentById($shopid,$employeeid){

       // $datetime = DateTime::createFromFormat('Y/m/d h:i A', $datetime);
       // $timestamp = $datetime->getTimestamp();
       //one month before

       $oneMonthBefore = date("Y-m-d", strtotime( date( "Y-m-d", strtotime( date("Y-m-d") ) ) . "-1 month" ) );
      $onemonthdatetime = DateTime::createFromFormat('Y-m-d', $oneMonthBefore);

      $first_minute = $onemonthdatetime->getTimestamp();
      $last_minute = mktime(23, 59, 59, date("n"), date("t"));


       $this->db->select('COUNT(id) as sum');
        $this->db->from('brcustomer as cust');
        // $this->db->join('brinvoice as invoice', 'invoice.id=puchase.invoice_id');
         $this->db->where('create_time >=', $first_minute);
        $this->db->where('create_time <=', $last_minute);
           $this->db->group_start();
        $this->db->where('cust.id in','(SELECT user_id FROM  brinvoice WHERE therapist_id ='.$employeeid.')', false);
        $this->db->or_where('cust.id in','(SELECT user_id FROM  brinvoice WHERE consultant_id ='.$employeeid.')', false);
         $this->db->group_end();
        //  $this->db->group_start();
        // $this->db->where('invoice.therapist_id',$userid);
        // $this->db->or_where('invoice.consultant_id',$userid);
        // $this->db->group_end();
        // $this->db->where('invoice.delete_time', NULL);
        //  $this->db->where('invoice.shopId', $shopId);
        // $this->db->where('shopId', $shopId);
        // // $this->db->where('shop_id',$id);
        // $this->db->group_start();
        // $this->db->where('pic_1',$userid);
        // $this->db->or_where('pic_2',$userid);
        // $this->db->group_end();
        // $this->db->where('startdate', date("Y-m-d"));
        // $this->db->order_by('startdate DESC');
         $query = $this->db->get();
         
        // return $query->row()->sum;
        // return $query->row()->sum;

        $totalNewCust=$query->row()->sum;

        $this->db->select('COUNT(id) as sum');
        $this->db->from('brcustomer as cust');
        // $this->db->join('brinvoice as invoice', 'invoice.id=puchase.invoice_id');
         $this->db->where('create_time >=', $first_minute);
        $this->db->where('create_time <=', $last_minute);
        // $this->db->where('EXISTS (SELECT user_id FROM  brservice_user WHERE invoice_id != NULL AND  cust.id= brservice_user.user_id)', '', FALSE);

        $this->db->where('cust.id in','(SELECT user_id FROM  brservice_user WHERE invoice_id IS NOT NULL)', false);
        $this->db->group_start();
        $this->db->where('cust.id in','(SELECT user_id FROM  brinvoice WHERE therapist_id ='.$employeeid.')', false);
        $this->db->or_where('cust.id in','(SELECT user_id FROM  brinvoice WHERE consultant_id ='.$employeeid.')', false);
         $this->db->group_end();

        //  $this->db->group_start();
        // $this->db->where('invoice.therapist_id',$userid);
        // $this->db->or_where('invoice.consultant_id',$userid);
        // $this->db->group_end();
        // $this->db->where('invoice.delete_time', NULL);
        //  $this->db->where('invoice.shopId', $shopId);
        // $this->db->where('shopId', $shopId);
        // // $this->db->where('shop_id',$id);
        // $this->db->group_start();
        // $this->db->where('pic_1',$userid);
        // $this->db->or_where('pic_2',$userid);
        // $this->db->group_end();
        // $this->db->where('startdate', date("Y-m-d"));
        // $this->db->order_by('startdate DESC');
         $query = $this->db->get();
         
        // return $query->row()->sum;
        // return $query->row()->sum;

        $totalNewCustHaveInvoice=$query->row()->sum;
        $outprecent=0;
        if($totalNewCust!=0){  //skip division zero
          $outprecent=($totalNewCustHaveInvoice/$totalNewCust)*100;
        }
        
        return round($outprecent,0);
        // return $totalNewCust;
        // return $totalNewCustHaveInvoice;
        // return $this->db->last_query();

        // return $first_minute;
        // return 123;



    }//function countCustomerOrderPrecentById(){ 

    function countNewCustomerInvoiceAmount($shopid){




       // $datetime = DateTime::createFromFormat('Y/m/d h:i A', $datetime);
       // $timestamp = $datetime->getTimestamp();
       //one month before

      $oneMonthBefore = date("Y-m-d", strtotime( date( "Y-m-d", strtotime( date("Y-m-d") ) ) . "-1 month" ) );
      $onemonthdatetime = DateTime::createFromFormat('Y-m-d', $oneMonthBefore);

      $first_minute = $onemonthdatetime->getTimestamp();
      $last_minute = mktime(23, 59, 59, date("n"), date("t"));

        $this->db->select('SUM(total_amount_due) as sum');
$this->db->from('brinvoice as invoice');
      $this->db->where('invoice.user_id in','(SELECT id FROM  brcustomer WHERE create_time >= '.$first_minute.' AND create_time<='.$last_minute.')', false);
        $this->db->where('invoice.delete_time', NULL);  
        $this->db->where('invoice.shopId', $shopid);  
       




         $query = $this->db->get();
         
        // return $query->row()->sum;
        // return $query->row()->sum;

        $totalNewInvoice=$query->row()->sum;



        return round($totalNewInvoice,0);
        // return $this->db->last_query();

        // return $first_minute;
        // return 123;


    }//function countCustomerOrderPrecent(){

    function countNewCustomerInvoiceAmountById($shopid,$employeeid){




       // $datetime = DateTime::createFromFormat('Y/m/d h:i A', $datetime);
       // $timestamp = $datetime->getTimestamp();
       //one month before

      $oneMonthBefore = date("Y-m-d", strtotime( date( "Y-m-d", strtotime( date("Y-m-d") ) ) . "-1 month" ) );
      $onemonthdatetime = DateTime::createFromFormat('Y-m-d', $oneMonthBefore);

      $first_minute = $onemonthdatetime->getTimestamp();
      $last_minute = mktime(23, 59, 59, date("n"), date("t"));

        $this->db->select('SUM(total_amount_due) as sum');
$this->db->from('brinvoice as invoice');
      $this->db->where('invoice.user_id in','(SELECT id FROM  brcustomer WHERE create_time >= '.$first_minute.' AND create_time<='.$last_minute.')', false);
        $this->db->where('invoice.delete_time', NULL);  
        $this->db->where('invoice.shopId', $shopid);  
          $this->db->group_start();
        $this->db->where('therapist_id',$employeeid);
        $this->db->or_where('consultant_id',$employeeid);
         $this->db->group_end();  



         $query = $this->db->get();
         
        // return $query->row()->sum;
        // return $query->row()->sum;

        $totalNewInvoice=$query->row()->sum;



        return round($totalNewInvoice,0);
        // return $this->db->last_query();

        // return $first_minute;
        // return 123;


    }//function countCustomerOrderPrecent(){

    function checkItemDetailInService($invoiceItemDetailList){
        $checkedList=array();
        foreach($invoiceItemDetailList as $invoiceItemDetailRow){
            // array_push($checkedList,$invoiceItemDetailRow->invoice_id);

            //add check is invoice partial payment/
            //if partial payment replace with parent invoice id
            $searchInvoice="";
            if($this->isPartialPaymentChild($invoiceItemDetailRow->invoice_id)==true){
                $searchInvoice=$this->getParentId($invoiceItemDetailRow->invoice_id);
            }
            else{
                 $searchInvoice=$invoiceItemDetailRow->invoice_id;
            }
            // $this->db->where('invoice_id', $invoiceItemDetailRow->invoice_id);
            $this->db->where('invoice_id', $searchInvoice);
            $this->db->where('service_id', $invoiceItemDetailRow->item_id);
            $this->db->where('delete_time', NULL); 
            $query = $this->db->get('brservice_user');
            if($query->num_rows() == 1){
                array_push($checkedList,1);
            } else {
                array_push($checkedList,0);
            }


        }//foreach($invoiceItemDetailList as $invoiceItemDetailRow){
        return $checkedList;
    }
    function getParentId($invoiceid){
            //get receipt number by invoice id
            //if null, get last receipt number 
            //and update all payment with lastest receipt number
            $this->db->select("parent_id");
            $this->db->from('brinvoice');
            $this->db->where('id', $invoiceid); 
            $invoicerow = $this->db->get()->row();
            $parent_id=$invoicerow->parent_id;
            return $parent_id;
    }
    function isPartialPaymentChild($invoiceId){
            $this->db->where('partialpayment', 1);
            $this->db->where('parent_id!=', 0);
            $this->db->where('id', $invoiceId);
            // $this->db->where('delete_time', NULL); 
            $query = $this->db->get('brinvoice');
            if($query->num_rows() == 1){
                return true;
            }
            else{
                return false;
            }
    }
    function isPartialPayment($invoiceId){
            $this->db->where('partialpayment', 1);
            // $this->db->where('parent_id!=', 0);
            $this->db->where('id', $invoiceId);
            // $this->db->where('delete_time', NULL); 
            $query = $this->db->get('brinvoice');
            if($query->num_rows() == 1){
                return true;
            }
            else{
                return false;
            }
    }

    function getInvoicePayment($invoiceId){
        // payment

            $this->db->select("*");
            $this->db->from('brpurchase_payment');
            $this->db->where('delete_time', NULL);   
            $this->db->where('invoice_id',$invoiceId); 
            $this->db->order_by('payment_date','DESC'); 
            $query = $this->db->get();

           return $query->result();     

            //end payment 
    }

     function getRefundData($invoiceId){
        // refund

            $this->db->select("*");
            $this->db->from('brpurchase_refund');
            $this->db->where('delete_time', NULL);   
            $this->db->where('invoice_id',$invoiceId); 
            $this->db->order_by('refund_date','DESC'); 
            $query = $this->db->get();

           return $query->result();     

            //end refund 
    }

        function getRefundRow($invoiceid){
            //get receipt number by invoice id
            //if null, get last receipt number 
            //and update all payment with lastest receipt number
            $this->db->select("refund_num,refund_date,refund_amount");
            $this->db->from('brpurchase_refund');
            $this->db->where('invoice_id', $invoiceid);
            $this->db->order_by('id', 'DESC');    
            $refund_row = $this->db->get()->row();
            $refund_num=$refund_row->refund_num;
            if(!empty($refund_num)){
                return $refund_row;
            }
            else{
                $shopid=$this->getShopIdByInvoiceId($invoiceid);
                $refundid=$this->getLastRefundId($shopid);
                $this->updateRefundNum($invoiceid,$refundid);

                //get updated row
                $this->db->select("refund_num,refund_date,refund_amount");
                $this->db->from('brpurchase_refund');
                $this->db->where('invoice_id', $invoiceid);
                $this->db->order_by('id', 'DESC');    
                $refund_row = $this->db->get()->row();

                //end get updated row


                return $refund_row;
            }//else{



        }//function getRefundRow($invoiceid){
    function updateRefundNum($invoiceid,$refundid){
        $data = array(
            'refund_num' => $refundid ,
            
            );

           // date_default_timezone_set('UTC');
           $this->db->set('update_time', time(), FALSE);
           $this->db->set('refund_date', time(), FALSE);
            $this->db->where('invoice_id',$invoiceid);
           $query=$this->db->update('brpurchase_refund', $data);

           return $query;
    }
    function getLastRefundId($shopid){
        $year=$this->years_model->getFinancialYear();
        $shortYear=substr( $year, -2);

        $shopRow=$this->shop_model->getShopbyid($shopid);
        $shortcode=$shopRow->shortcode;

        $invoiceHead='RE'.$shortcode.'-'.$shortYear.'-';


        
        $this->db->select("*");
        $this->db->from('brpurchase_refund');
        $this->db->like('refund_num', $invoiceHead);
        // $this->db->where('shopId', $shopid);
         $this->db->order_by('refund_num', 'DESC');    
        $refund_num = $this->db->get()->row()->id;

        echo $this->db->last_query();

        $refund_num = substr($refund_num, -7);
        //remove last character R
        $refund_num =substr($refund_num, 0, -1);
        //end remove last character R

        $refund_num = $refund_num+1;

        $printRefundnum=str_pad($refund_num, 6, '0', STR_PAD_LEFT);

        $printRefund=$invoiceHead.$printRefundnum.'R';

        return $printRefund;
    }//function getLastRefundId($id){ 

    function deleteInvoice($inputdata){
        $invoice_id=$inputdata['invoice_id'];
        $this->db->trans_begin();

        // $this->db->query('AN SQL QUERY...');
        // $this->db->query('ANOTHER QUERY...');
        // $this->db->query('AND YET ANOTHER QUERY...');

        //delete invoice table
        $this->db->set('delete_time', time(), FALSE);
        $this->db->where('id', $invoice_id);
        $query=$this->db->update('brinvoice');
        // return $query;
        //end delete invoice table

        //delete invoice item
        $this->db->set('delete_time', time(), FALSE);
        $this->db->where('invoice_id', $invoice_id);
        $query=$this->db->update('brinvoice_item');
        //end delete invoice table

        //delete payment
        $this->db->set('delete_time', time(), FALSE);
        $this->db->where('invoice_id', $invoice_id);
        $query=$this->db->update('brpurchase_payment');
        //end delete payment

        //delete refund
        $this->db->set('delete_time', time(), FALSE);
        $this->db->where('invoice_id', $invoice_id);
        $query=$this->db->update('brpurchase_refund');
        //end delete refund

        //clear added package to 0
        //if it is original invoice or the begining A of partial payment,
        //set userservice quantity to 0 and set delete time to not Null

        $clearUserService=false;
        if($this->isPartialPayment($invoice_id)==false){
            //orginal invoice
            $clearUserService=true;
        }
        else{
            if($this->isPartialPaymentChild($invoice_id)==false){
                //the begining A of partial
                $clearUserService=true;
            }
        }

        if($clearUserService==true){
                $this->db->set('available_qty', 0);
                $this->db->set('delete_time', time(), FALSE);
                $this->db->where('invoice_id', $invoice_id);
                $query=$this->db->update('brservice_user');
        }//if($clearUserService==true){

        //end clear added package to 0




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


    }    
    //end added invoicemodel function
    function getShopAll()
    {
        
        $this->db->from('bshop');
        // $this->db->where(array('show' => 1));
        $this->db->where(array('deleted' => 0));
        // $this->db->order_by('rank');

        $query = $this->db->get();
        return $query->result();
    }
    function getAllShop()
    {
        
        $this->db->from('bshop');
        // $this->db->where(array('show' => 1));
        $this->db->where(array('deleted' => 0));
        // $this->db->order_by('rank');
        $query = $this->db->get();
        return $query->result();
    }
    function getShopbyid($id){
        $this->db->from('bshop');
        $this->db->where('id',$id);
        $this->db->where(array('deleted' => 0));
        $row=$this->db->get()->row();
        return $row;
    }
    function shopcode_exists($code){
        $this->db->where('LOWER(shortcode)', $code);
        $this->db->where(array('deleted' => 0));
        $query = $this->db->get('bshop');
        if($query->num_rows() == 1){
            return false;
        } else {
            return true;
        }
    }
    function shopCodeExistByID($shortcode,$id){
        $this->db->where('LOWER(shortcode)', $shortcode);
        $this->db->where(array('deleted' => 0));
        $this->db->where('id !=' , $id);
        $query = $this->db->get('bshop');
        if($query->num_rows() == 1){
            return false;
        } else {
            return true;
        }
    }
    function insertShop($inputdata){
           $data = array(
            'shortcode' => $inputdata['shortcode'] ,
            'code' => $inputdata['code'] ,
            'name' => $inputdata['name'] ,
            'status' => 1 ,
            'display' => 0 ,// 0 stand for display, 1 stand for not display
            'deleted' => 0 , //0 stand for not deleted, 1 stand for deleted
            );
           date_default_timezone_set('UTC');
           $this->db->set('update_time', time(), FALSE);
           $this->db->set('create_time', time(), FALSE);
           $query=$this->db->insert('bshop', $data);

           return $query;
    }
    function updateShop($inputdata){
              $data = array(
            'shortcode' => $inputdata['shortcode'] ,
            'code' => $inputdata['code'] ,
            'name' => $inputdata['name'] ,
            'status' => 1 ,
         );
        date_default_timezone_set('UTC');
        
        $this->db->set('update_time', time(), FALSE);

        $this->db->where('id', $inputdata['id']);
 
        $query=$this->db->update('bshop', $data);
        return $query;
    }
    function deleteShop($id){ 
        $data = array(
            
            );
       $this->db->set('deleted', 1, FALSE);
       $this->db->where('id', $id);
       $query=$this->db->update('bshop', $data);

       return $query;
    }//function deleteAdmin($id){
     function getShopcode($id){
        $this->db->from('bshop');
        $this->db->where('id',$id);
        $shortcode=$this->db->get()->row()->shortcode;
        return $shortcode."0000";
    }
    function getShopcodeHead($id){
        $this->db->from('bshop');
        $this->db->where('id',$id);
        $shortcode=$this->db->get()->row()->shortcode;
        return $shortcode;
    }
    function getSkinImprove(){
        //may be change the table name
        $this->db->from('mas_skin_improve');
        $this->db->order_by('id');
        $query = $this->db->get();
        return $query->result();
    }
   


    function getBannerAll()
    {
        
        $this->db->from('tblFolders');
        // $this->db->where(array('show' => 1));
        // $this->db->order_by('rank');
        $query = $this->db->get();
        return $query->result();
    }

    // function getAdmindata(){
    //     $this->db->select('id,login, fullName, update_time');
    //     $query = $this->db->get('adminUsers');
    //     return $query->result();
    // }
    // function record_count(){
    //     $this->db->select('id');
    //     $this->db->where('level1', '0');
    //     $this->db->where('level2', NULL);
    //     $query = $this->db->get('tblFolders');
    //     return $query->num_rows();
    // }
    // function count_all_folders(){
    //     $this->db->select('id');
    //     $query = $this->db->get('tblFolders');
    //     return $query->num_rows();    
    // }   
    // function getflodercount($id){
    //     $this->db->select('id');
    //     $this->db->where('level1', $id);
    //     // $this->db->where('level2!=', NULL);
    //     $query = $this->db->get('tblFolders');
    //     return $query->num_rows();    
    // }    

    // function getfolderdata($perpage,$page){
    //     $this->db->select('id,name,level1, update_time');
    //     $offset=$page* $perpage;
    //     $this->db->where('level1', 0);
    //     $this->db->limit($perpage, $offset);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // }


    // function getlevel1data($id)
    // {
    //     $this->db->select('id,name,level1, update_time');
    //     $this->db->where('level1', $id);
    //     $this->db->where('level2', NULL);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // }
    // function getlevel2data($id)
    // {
    //     $this->db->select('id,name,level1, update_time');
    //     $this->db->where('level2', $id);
    //     $this->db->where('level3', NULL);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // }
    // function getlevel3data($id){
    //     $this->db->select('id,name,level1, update_time');
    //     $this->db->where('level3', $id);
    //     $this->db->where('level4', NULL);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // }
    // function getlevel4data($id){
    //     $this->db->select('id,name,level1, update_time');
    //     $this->db->where('level4', $id);
    //     $this->db->where('level5', NULL);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // }

    // //get all folder data for rightend
    // function getallfolderdata(){
    //     $this->db->select('id,name,level1,level2,level3,level4, update_time');
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // }    
    // function getalllevel1datainclude($id)
    // {
    //     $this->db->select('id,name,level1,level2,level3,level4, update_time');
    //     $this->db->where('level1', $id);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // } 
    // function getalllevel2datainclude($id)
    // {
    //     $this->db->select('id,name,level1,level2,level3,level4, update_time');
    //     $this->db->where('level2', $id);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // } 
    // function getalllevel3datainclude($id)
    // {
    //     $this->db->select('id,name,level1,level2,level3,level4, update_time');
    //     $this->db->where('level3', $id);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // }    

    // //end get all folder data for rightend

    // function getAdmindateByid($id){
    //     $this->db->select('id,login, companyName,fullName,tel, update_time');
    //     $this->db->where('id', $id);
    //     $query = $this->db->get('tblFolders');
    //     return $query->result();
    // }

    
    // function getFolderName($id){
    //     $this->db->select('name');
    //     $this->db->where('id', $id);
    //     $query = $this->db->get('tblFolders');
    //     if ($query->num_rows() > 0) {
    //         // return $query->first_row();
    //          $row = $query->row(); 
    //         return $row->name;
    //     }
    //     return "";
    // }

    // function insertFolder($data){
    //     // 'inputadminname'=>$inputadminname,
    //     //         'inputloginname'=>$inputloginname,
    //     //         'inputPassword'=>$inputPassword,
    //     $data = array(
    //         'name' => $data['inputflodername'] ,
    //         'level1' => '0' ,
            
    //      );
    //      $this->db->set('update_time', 'NOW()', FALSE);
    //      $query=$this->db->insert('tblFolders', $data);
    //      return $query;
    // }
    // function insertLevelFolder($data){
    //     // 'inputadminname'=>$inputadminname,
    //     //         'inputloginname'=>$inputloginname,
    //     //         'inputPassword'=>$inputPassword,
    //     if($data['addlevel']==1){
    //         $data = array(
    //             'name' => $data['inputflodernamelevel'] ,
    //             'level1' => '0' ,
                
    //          );
    //     }
    //     if($data['addlevel']==2){
    //         $data = array(
    //             'name' => $data['inputflodernamelevel'] ,
    //             'level1' => $data['addlevelid'] ,
                
    //          );
    //     }
        
        
    //      $this->db->set('update_time', 'NOW()', FALSE);
    //      $query=$this->db->insert('tblFolders', $data);
    //      return $query;
    // }
    // function insertLevelOneFolder($name,$level){
    //     $data = array(
    //         'name' => $name ,
    //         'level1' => '0' ,
            
    //      );
    //      $this->db->set('update_time', 'NOW()', FALSE);
    //      $query=$this->db->insert('tblFolders', $data);
    //      return $query;
        
    // }
    // function insertLevelTwoFolder($name,$addlevel,$addlevelid){
    //     $data = array(
    //         'name' => $name ,
    //         'level1' => $addlevelid ,
            
    //      );
    //      $this->db->set('update_time', 'NOW()', FALSE);
    //      $query=$this->db->insert('tblFolders', $data);
    //      return $query;
    // }
    // function insertLevelThreeFolder($name,$addlevel,$addlevelid,$secondvalues){
    //     $data = array(
    //         'name' => $name ,
    //         'level1' => $addlevelid ,
    //         'level2' => $secondvalues ,
    //      );
    //      $this->db->set('update_time', 'NOW()', FALSE);
    //      $query=$this->db->insert('tblFolders', $data);
    //      return $query;
    // }

    // function insertLevelFourFolder($name,$addlevel,$addlevelid,$thirdvalues){
    //     $secondlevelid=$this->findLevelThreeid($thirdvalues);
    //     $data = array(
    //         'name' => $name ,
    //         'level1' => $addlevelid ,
    //         'level2' => $secondlevelid ,
    //         'level3' => $thirdvalues ,
    //      );
    //      $this->db->set('update_time', 'NOW()', FALSE);
    //      $query=$this->db->insert('tblFolders', $data);
    //      return $query;
    // }
    // function insertLevelMonthWeekFolder($values,$addlevel,$addlevelid,$secondvalues){
    //     $montharray = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct","Nov","Dec");
    //     $weekarray =  array("Week 1", "Week 2", "Week 3", "Week 4", "Week 5");
    //     foreach($montharray as $month){
    //         if($this->folder_levelThreeexists(strtolower($month),$addlevel,$addlevelid,$secondvalues)==true){
    //              $data = array(
    //             'name' =>  $month ,
    //             'level1' => $addlevelid ,
    //             'level2' => $secondvalues ,
    //          );
    //          $this->db->set('update_time', 'NOW()', FALSE);
    //          $query=$this->db->insert('tblFolders', $data);
    //          $lastinsertid = $this->db->insert_id();
    //          foreach ($weekarray as $week) {

    //              $data = array(
    //             'name' =>  $week ,
    //             'level1' => $addlevelid ,
    //             'level2' => $secondvalues ,
    //             'level3' => $lastinsertid ,
    //              );
    //             $this->db->set('update_time', 'NOW()', FALSE);
    //              $query=$this->db->insert('tblFolders', $data);
    //          }

    //         }//if(folder_levelThreeexists($month,$addlevel,$addlevelid,$secondvalues)==false){
    //     }//foreach($montharray as $month){
    //     return $query;
    // }

    // function updateAdmin($input){
    //     // 'inputadminname'=>$inputadminname,
    //     //         'inputloginname'=>$inputloginname,
    //     //         'inputPassword'=>$inputPassword,
        
    //     if(empty($input['inputPassword'])){
    //         $data = array(
    //             'login' => $input['inputloginname'] ,
    //             'companyName' => $input['inputcompanynameedit'],
    //             'fullName' => $input['inputfullnameedit'], 
    //             'tel' => $input['inputteledit']  
                
    //          );
    //     }
    //     else{
    //         $data = array(
    //             'login' => $input['inputloginname'] ,
    //             'companyName' => $input['inputcompanynameedit'],
    //             'fullName' => $input['inputfullnameedit'], 
    //             'tel' => $input['inputteledit']  ,
    //             'pwd' => $input['inputPassword'] 
    //          );
    //     }
        
    //      $this->db->set('update_time', 'NOW()', FALSE);

    //      $this->db->where('id', $input['id']);
    //      $query=$this->db->update('tblFolders', $data);
    //      return $query;
    // }

    // function deleteAdmin($id){
    //     $this->db->where('id', $id);
    //     $query = $this->db->get('tblFolders');
    //     $row = $query->row(); 

    //     //check level of delete
    //     $deleteLevel=0;
    //     if($row->level4 ==NULL  && $row->level3!=NULL){
    //         $deleteLevel=4;
    //     }
    //     if($row->level3 ==NULL  && $row->level2!=NULL){
    //         $deleteLevel=3;
    //     }
    //     if($row->level2 ==NULL  && $row->level1!=NULL && $row->level1!=0){
    //         $deleteLevel=2;
    //     }
    //     if( $row->level1==0){
    //         $deleteLevel=1;
    //     }

    //     //end check level of delete
    //     if($deleteLevel==4){
    //         $this->db->where('id', $id);
    //         $query = $this->db->get('tblFolders');
    //         if($query->num_rows() != 0){
    //             $this->db->where('id', $id);
    //             $query=$this->db->delete('tblFolders');
    //         }
    //     }
    //     if($deleteLevel==3){

    //         $this->db->where('level3 ',$id);
    //         $query = $this->db->get('tblFolders');
    //         if($query->num_rows() != 0){
    //             $this->db->where('level3', $id);
    //              $query=$this->db->delete('tblFolders');
    //         }

    //         $this->db->where('id', $id);
    //         $query = $this->db->get('tblFolders');
    //         if($query->num_rows() != 0){
    //             $this->db->where('id', $id);
    //             $query=$this->db->delete('tblFolders');
    //         }
    //     }
    //     if($deleteLevel==2){
    //         $this->db->where('level2 ',$id);
    //         $query = $this->db->get('tblFolders');
    //         if($query->num_rows() != 0){
    //             $this->db->where('level2', $id);
    //             $query=$this->db->delete('tblFolders');
    //         }

    //         $this->db->where('id', $id);
    //         $query = $this->db->get('tblFolders');
    //         if($query->num_rows() != 0){
    //             $this->db->where('id', $id);
    //             $query=$this->db->delete('tblFolders');
    //         }
    //     }
    //     if($deleteLevel==1){
    //         $this->db->where('level1 ',$id);
    //         $query = $this->db->get('tblFolders');
    //         if($query->num_rows() != 0){
    //             $this->db->where('level1', $id);
    //             $query=$this->db->delete('tblFolders');
    //         }

    //         $this->db->where('id', $id);
    //         $query = $this->db->get('tblFolders');
    //         if($query->num_rows() != 0){
    //             $this->db->where('id', $id);
    //             $query=$this->db->delete('tblFolders');
    //         }
    //     }

        
    //     return $query;
    // }

    // function folder_exists($foldername){
    //     // $this->db->from('adminUsers');
    //     $this->db->where('LOWER(name)', $foldername);
    //     $this->db->where('LOWER(name)', $foldername);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }

    // function folder_levelOneexists($foldername){
    //     // $this->db->from('adminUsers');
    //     $this->db->where('LOWER(name)', $foldername);
    //     $this->db->where('level1', '0');
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }

    // function folder_levelTwoexists($foldername,$level,$id){
    //     $this->db->where('LOWER(name)', $foldername);
    //     $this->db->where('level1', $id);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }
    // function folder_levelThreeexists($foldername,$level,$id,$secondllevelid){
    //     $this->db->where('LOWER(name)', $foldername);
    //     $this->db->where('level1', $id);
    //     $this->db->where('level2', $secondllevelid);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }
    // function folder_levelFourexists($foldername,$level,$id,$thirdllevelid){
    //     $secondlevelid=$this->findLevelThreeid($thirdllevelid);
    //     $this->db->where('LOWER(name)', $foldername);
    //     $this->db->where('level1', $id);
    //     $this->db->where('level2', $secondlevelid);
    //     $this->db->where('level3', $thirdllevelid);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }

    // }

    // function folder_levelTwoMonthWeekexists($values,$addlevel,$addlevelid,$secondvalues){
    //     $montharray = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct","Nov","Dec");
    //     foreach($montharray as $month){
    //         $this->db->select("id");
    //         $this->db->where('name', $month);
    //         $this->db->where('level1', $addlevelid);
    //         $this->db->where('level2', NULL);
    //         $query = $this->db->get('tblFolders');
    //         if($query->num_rows() == 1){
    //             return false;
    //             //check week    
                

    //             //end check week

    //         } else {

    //         }
    //     }
        
    //     return true;
    // }

    // function checkleveltwoid($secondlevelid){
    //     $this->db->where('id', $secondlevelid);
    //     $this->db->where('level1 !=',0);
    //     $this->db->where('level2 ', NULL);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }

    // function checklevelthreeid($thirdllevelid){
    //     $this->db->where('id', $thirdllevelid);
    //     $this->db->where('level2 !=', NULL);
    //     $this->db->where('level3 ', NULL);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }
    // function findLevelThreeid($thirdllevelid){
    //     $this->db->select("level2");
    //     $this->db->where('id', $thirdllevelid);
    //     $this->db->from('tblFolders');
    //     $query = $this->db->get();
    //     // $ret = $query->row();
    //     // return $ret->level2;
    //     if ($query->num_rows() > 0)
    //     {
    //         $row = $query->row(); 
    //         return $row->level2;
    //     }
    //     return NULL;
    // }

    // function login_existsbyid($loginname,$id){
    //     // $this->db->from('adminUsers');
    //     $this->db->where('LOWER(login)', $loginname);
    //     $this->db->where('id!=', $id);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }
   

    // function admin_exists($loginname){
    //     // $this->db->from('adminUsers');
    //     $this->db->where('LOWER(fullName)', $loginname);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }

    // function admin_existsbyid($loginname,$id){
    //     // $this->db->from('adminUsers');
    //     $this->db->where('LOWER(fullName)', $loginname);
    //     $this->db->where('id!=', $id);
    //     $query = $this->db->get('tblFolders');
    //     if($query->num_rows() == 1){
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }


    // //process login
    // function check(){
    //     $userName =  $this->input->post('userName');
    //     $password =  $this->input->post('password');

    //     $this->db->where('login',$userName);
    //     $this->db->where('pwd',$password);
    //     // $this->db->where('user_active','yes');
    //     return $this->db->get('tblFolders')->row_array();
    // }


    // function processLogin($userName=NULL,$password){



    //     $this->db->select("id,login,fullName");
    //     $whereCondition = $array = array('login' =>$userName,'pwd'=>$password);
    //     $this->db->where($whereCondition);
    //     $this->db->from('tblFolders');
    //     $query = $this->db->get();
    //     return $query;
    // }//function processLogin(){
    // //end process login

    // function buildTopMenuItem()
    // {
    //     // $menu = array();
        
    //     // $result = $this->getSectionAll();
    //     // foreach ($result as $row)
    //     // {
    //     //     $menu[] = array(
    //     //         'name_zh' => $row->cp_name,
    //     //         'name_cn' => $row->sp_name,
    //     //         'name_en' => $row->ep_name,
    //     //         'link' => $row->link
    //     //     );
    //     // }
    //     // return $menu;
        
    // }
}