<?php

class Purchaseorder_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

    function getPurchase_order_list() {
        
        $startdate = $this->input->post('startdate', TRUE);
        $enddate = $this->input->post('enddate', TRUE);

        
        $subquery="(SELECT id_account_vouchers, account_vouchers.purchase_order_id, account_vouchers.grn_id, sum(debit) debit, sum(credit) credit, sum(credit)-sum(debit) as balance
                    FROM account_vouchers 
                    join account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                    where date(voucher_date) >= '".$startdate."'
                    and date(voucher_date) <= '".$enddate."'
                    and voucher_type=1
                    and voucher_status= 'Active'
                    and ifnull(account_vouchers.purchase_order_id,'') !=''                    
                    group by id_account_vouchers) as a";
        
        
        $showall='No';
        
        $this->db->select('*');
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('id_business', $this->session->userdata('businessid'));
        }
        $q = $this->db->get('business');
        $business= $q->result_array();
        foreach($business as $b){
        
            $showall=$b['multibranchpo'];
        }
        
        $this->db->select('idpurchase_order, purchase_order_number, business_supplier.supplier_name, total_purchase_pirce, Case When ifnull(a.debit,0) > total_purchase_pirce THEN total_purchase_pirce Else ifnull(a.debit,0) End as debit, a.balance, purchase_order.status, purchase_order.created_by, DATE_FORMAT(order_date, "%d-%m-%Y") as order_date, sum(purchase_order_details.product_qty) as qty, business_name, DATE_FORMAT(created_on, "%d-%m-%Y") as created_on'  );
        $this->db->join('purchase_order_details','purchase_order.idpurchase_order = purchase_order_details.purchase_order_id');
        $this->db->join('business_supplier','purchase_order.supplier_id = business_supplier.id_business_supplier');
        $this->db->join('business','purchase_order.business_id = business.id_business');
        $this->db->join($subquery, 'a.purchase_order_id = purchase_order.idpurchase_order', 'left');
        if($showall =='No'){
            $this->db->where('purchase_order.business_id', $this->session->userdata('businessid'));
        }        
        $this->db->where('date(purchase_order.created_on) >= ', $startdate);
        $this->db->where('date(purchase_order.created_on) <= ', $enddate);
        $this->db->group_by('idpurchase_order, purchase_order_number, business_supplier.supplier_name, total_purchase_pirce, purchase_order.status, purchase_order.created_by, order_date');
        $this->db->order_by('created_on', 'desc');
        $query = $this->db->get('purchase_order');
        //echo $query; exit();
        
        
        
        return $query->result_array();
    }

    function get_suppliers($businessid){
        
        $this->db->select('*');
        $this->db->join('business', 'business.id_business = business_supplier.business_id');
        
        $this->db->where('business_supplier.business_id', $businessid);
        $query = $this->db->get('business_supplier');

        return $query->result_array();
    }
    function get_supplier_brand($supplierid, $business_id) {
        $this->db->select('*');
        $this->db->join('supplier_brand sp', 'sp.brand_id = bb.id_business_brands');
        
        $this->db->where('bb.business_brand_active', 'Yes');
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('bb.business_id', $business_id);
        }
        $this->db->where('sp.supplier_id', $supplierid);
        $query = $this->db->get('business_brands bb');
       
        return $query->result_array();
    }

    function get_brand_product($brandid, $business_id) {
        $this->db->select("*", false);
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('business_products.business_id', $business_id);
        }
        $this->db->where('business_products.business_product_active', 'Yes');
        $this->db->where('business_products.brand_id', $brandid);
        $query = $this->db->get('business_products');
     
        return $query->result_array();
    }

    function add_order() {
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['orderdata']);

        // Decode the JSON array
        $tableData = json_decode($tableData, TRUE);

        // now $tableData can be accessed like a PHP array
         
        //add new customer_visit
        $total_qty = 0;
        $total_price = 0;
        foreach ($tableData as $row1) {
            $total_price += $row1['productprice'] * $row1['productqty'];
            $total_qty += $row1['productqty'];
        }
        $businessid = $this->session->userdata('businessid');
        if(null!==$tableData[0]['businessid']){
            $businessid=$tableData[0]['businessid'];
        } 
        
        $order = array(
            'business_id' => $businessid,
            'supplier_id' => $tableData[0]['supplierid'],
            'supplier_name' => $tableData[0]['suppliername'],
            'status' => 'Pending',
            'total_purchase_pirce' => $total_price,
            'product_total_qty' => $total_qty,
            'order_date' => $tableData[0]['orderdate'],
            'created_by' => $this->session->userdata('username')
        );
        
        
        $this->db->insert('purchase_order', $order);
        $order_id = $this->db->insert_id();

        $data = [];

        foreach ($tableData as $row) {

            $data = array(
                'purchase_order_id' => $order_id,
                'brand_id' => $row['brandid'],
                'brand_name' => $row['brandname'],
                'product_id' => $row['productid'],
                'product_name' => $row['productname'],
                'product_purchase_price' => $row['productprice'],
                'product_qty' => $row['productqty']
            );

            $this->db->insert('purchase_order_details', $data);
        }

        $data = array(
            'purchase_order_number' => 'PO-' . date('Y-m') . '-00' . $order_id
        );
        $this->db->where('idpurchase_order', $order_id);
        $this->db->update('purchase_order', $data);

        return $order_id;
    }

    function get_purchase_order_by_id($purchaseorder_id) {
        $this->db->select('*, date_format(order_date,"%d-%m-%Y") as d, bs.supplier_name');
        $this->db->join('business_supplier bs','bs.id_business_supplier = purchase_order.supplier_id');
        $this->db->join('business','business.id_business = purchase_order.business_id');
        $this->db->where('purchase_order.idpurchase_order', $purchaseorder_id);
        $query = $this->db->get('purchase_order');
        
       
        
        return $query->result_array();
    }

    function get_purchase_orders() {
        $this->db->select('*');
        $this->db->where('status', 'pending');
        $this->db->or_where('status', 'partial');
        $query = $this->db->get('purchase_order');

        return $query->result_array();
    }

    function get_purchase_order_detail($purchaseorder_id) {
//        $this->db->select('*');
//        $this->db->join('business_products bp','bp.id_business_products = purchase_order_details.product_id');
//        $this->db->join('business_brands bb','bb.id_business_brands = bp.brand_id');
//        $this->db->where('purchase_order_details.purchase_order_id', $purchaseorder_id);
//        $this->db->order_by('purchase_order_details.product_id');
//        $query = $this->db->get_compiled_select('purchase_order_details');
//        echo $query;exit();
        

        $sql="SELECT * 
                FROM purchase_order_details 
                JOIN business_products bp ON bp.id_business_products = purchase_order_details.product_id
                JOIN business_brands bb ON bb.id_business_brands = bp.brand_id 
                LEFT JOIN (

                        select grn_product_id, ifnull(sum(grn_qty_received),0) as received, grn_unit_price,
                        ifnull(sum(b.returned),0) returned 
                        FROM goods_received_note as grn 
                        JOIN grn_details gd ON gd.grn_id = grn.grn_id 
                        left JOIN 
                                (
                                select grn_id, product_id, ifnull(sum(return_qty),0) as returned 
                                from return_notes where return_status='Active' group by grn_id, product_id
                                )  as b on b.grn_id = gd.grn_id and b.product_id=gd.grn_product_id

                        where grn.purchase_order_id = '".$purchaseorder_id."'
                        group by grn_product_id


                ) a on purchase_order_details.product_id = a.grn_product_id
                WHERE purchase_order_details.purchase_order_id = '".$purchaseorder_id."' 
                ORDER BY purchase_order_details.product_id";
        
        $query = $this->db->query($sql);
        
        return $query->result_array();
    }

    //This function is using for already received qty in Good received Note
    public function get_grn_received_sum($purchaseorder_id) {
        $this->db->select('gd.grn_product_id, sum(gd.grn_qty_received) as received_sum');
        $this->db->join('grn_details gd', 'gd.grn_id = grn.grn_id');
        $this->db->where('grn.purchase_order_id', $purchaseorder_id);
        $this->db->group_by('gd.grn_product_id');
        $this->db->order_by('gd.grn_product_id');
        $query = $this->db->get('goods_received_note grn');
        if ($query->result_array()) {
            return $query->result_array();
        } else {
            $this->db->select('0 as received_sum');
            $query = $this->db->get('goods_received_note grn');
            return $query->result_array();
        }
    }

    function update_order() {
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['orderdata']);

        // Decode the JSON array
        $tableData = json_decode($tableData, TRUE);

        // now $tableData can be accessed like a PHP array
        //echo $tableData[0]['servicename'];
        //echo $this->input->post('visitid');
        //update customer_visit

        $this->db->where('customer_order_id', $this->input->post('orderid', TRUE));
        $this->db->delete('order_products');

        foreach ($tableData as $row) {

            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_order_id' => $this->input->post('orderid', TRUE),
                'product_id' => $row['productid'],
                'product_name' => $row['productname'],
                'staff_id' => $row['staffid'],
                'staff_name' => $row['staff'],
                'qty' => $row['qty']
            );

            $this->db->insert('order_products', $data);
        }
        return $this->input->post('orderid');
    }

    function grn_addupdate() {
        //exit();
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['orderdata']);

        // Decode the JSON array
        $tableData = json_decode($tableData, TRUE);
        
       // print_r($tableData) ; exit();
        // now $tableData can be accessed like a PHP array
        // echo $tableData[0]['servicename'];
        //add new customer_visit
        $grndate = $this->input->post('grndate');
        //echo $grndate ==''? date('Y-m-d') : $grndate; exit();
        $purchase_discount = $this->input->post('purchase_discount');
        $discounted_price= $this->input->post('discounted_price');
        $sales_tax= $this->input->post('sales_tax');
        $withholding_tax= $this->input->post('withholding_tax');
        $payable= $this->input->post('payable');
        $total_grn_value= $this->input->post('total_grn_value');
        $grn_comment = $this->input->post('grn_comment');
        
        $businessid = $this->session->userdata('businessid');

        $storeid=$this->input->post('storeid');
        if($storeid==null){
            $store = $this->product_model->get_business_store();
            if(!null == $store){
                $storeid=$store->id_business_stores;
            }
        }
        if(null!==$tableData[0]['businessid']){
            $businessid=$tableData[0]['businessid'];
        } 
        
        
        $order = array(
            'business_id' => $businessid,
            'grn_vendor_name' => $this->input->post('suppliername'),
            'purchase_order_id' => $this->input->post('purchaseorder_id'),
            'grn_created_date' => $grndate ==''? date('Y-m-d') : $grndate,
            'created_by' => $this->session->userdata('username'),
            'grn_comment' => $this->input->post('grn_comment')
        );
        
        
        
        $this->db->insert('goods_received_note', $order);
        $order_id = $this->db->insert_id();
       
        
        $GRN_number = $this->update_grn_number($order_id);

        $data = [];
        $inventory_increase=0;
        foreach ($tableData as $row) {
            if((float)$row['receivedQty'] > 0){//work only if recevied > 0
            //
            //
                //handle batches
                $batch_id = 0;
                if(isset($row['grnbatchid'])){ $batch_id= $row['grnbatchid'];}
                if($row['grnbatchnumber']==""){ //create new batch
                    $my_batch='0001';
                    $sql="SELECT LPAD(max(CAST(batch_number AS UNSIGNED))+1,4,0) as m FROM product_batch where product_id=". $row['productid'];
                    $query = $this->db->query($sql);
                    $max_batch=$query->row(); 
                    if ($max_batch && $max_batch->m!==null){$my_batch=$max_batch->m;}
                    $futureDate=$row['expiry_date'];
                    if($row['expiry_date']==""){
                        $futureDate=date('Y-m-d', strtotime('+1 year'));
                    }

                    $this->db->set('product_id', $row['productid']);
                    $this->db->set('batch_number', $my_batch);
                    $this->db->set('batch_date', $grndate=="" ? date("Y-m-d") :  $grndate);
                    $this->db->set('expiry_date', $futureDate);
                    $this->db->set('store_id', $storeid);
                    $this->db->set('batch_amount', $row['productunitprice']);
                    //New scenario where grn count is used to get the purchased qty
                  //  $this->db->set('batch_qty', (float)$row['receivedQty']);                
                    $this->db->insert('product_batch');
                    
                    $batch_id = $this->db->insert_id();
                    
                    
                    //insert GRN Details
                    if($row['grnbatchnumber']==''){$grn_batch_number=$my_batch;}else{$grn_batch_number=$row['grnbatchnumber'];}

                    $data = array(
                        'grn_id' => $order_id,
                        'grn_brand_id' => $row['brandid'],
                        'grn_product_id' => $row['productid'],
                        'grn_brand_name' => $row['brandname'],
                        'grn_product_name' => $row['productname'],
                        'grn_unit_price' => $row['productunitprice'],
                        'grn_qty_received' => $row['receivedQty'],
                        'grn_batch_number' => $grn_batch_number,
                        'grn_batch_id' => $batch_id
                    );
                    $this->db->insert('grn_details', $data);
                    
                    $inventory_increase += $row['productunitprice']*$row['receivedQty'];
                } else { 
                    //insert GRN Details
                    $my_batch='0001';
                    if($row['grnbatchnumber']==''){$grn_batch_number=$my_batch;}else{$grn_batch_number=$row['grnbatchnumber'];}

                    $data = array(
                        'grn_id' => $order_id,
                        'grn_brand_id' => $row['brandid'],
                        'grn_product_id' => $row['productid'],
                        'grn_brand_name' => $row['brandname'],
                        'grn_product_name' => $row['productname'],
                        'grn_unit_price' => $row['productunitprice'],
                        'grn_qty_received' => $row['receivedQty'],
                        'grn_batch_number' => $grn_batch_number,
                        'grn_batch_id' => $batch_id
                    );
                    $this->db->insert('grn_details', $data);
                    
                    //update existing batch
                    //New scenario where grn count is used to get the purchased qty
                    //$this->db->select('grn_batch_id, round(sum(grn_unit_price*grn_qty_received)/sum(grn_qty_received),2) as avg_unit_cost', false);
                    $this->db->select('grn_batch_id, round(sum(grn_unit_price*(grn_qty_received-ifnull(return_qty,0)))/sum(grn_qty_received-ifnull(return_qty,0)),2) as avg_unit_cost', false);
                     $this->db->join('(select batch_id, sum(return_qty) as return_qty from return_notes 
                                    where batch_id='.$row['grnbatchid'].'
                                    group by batch_id) as a', 'grn_batch_id = batch_id', false);
                    $this->db->where('grn_batch_id', $batch_id);
                    $this->db->group_by('grn_batch_id');
                    $q = $this->db->get('grn_details');

                    $all_grn=$q->row();
                    if($all_grn){
                        $grn_unit_cost=$all_grn->avg_unit_cost;
                    }else {
                        $grn_unit_cost=0;            
                    }

                    $this->db->select('batch_id, round(sum(unit_price*adjustment_qty)/sum(adjustment_qty),2) as avg_unit_cost', false);
                    $this->db->where('batch_id', $batch_id);
                    $this->db->where('adjustment_qty >', 0);
                    $this->db->group_by('batch_id');
                    $z = $this->db->get('adjustment_notes');

                    $all_adjustments=$z->row();
                    if($all_adjustments){
                        $adjustment_unit_cost=$all_adjustments->avg_unit_cost;
                    }else {
                        $adjustment_unit_cost=0;            
                    }



                    if($grn_unit_cost>0 && $adjustment_unit_cost>0){
                        $final_unit_cost= ($grn_unit_cost+$adjustment_unit_cost)/2;
                    } else {
                        $final_unit_cost= $grn_unit_cost+$adjustment_unit_cost;
                    }

                    $this->db->set('batch_amount', $final_unit_cost);  
                    $this->db->where('id_batch=',$batch_id);
                    $this->db->update('product_batch');
                    
                    $inventory_increase += $row['productunitprice']*$row['receivedQty'];
                }
                
                
           
            }
        }
        if($this->input->post('ordered_qty')==$this->input->post('received_qty')+$this->input->post('received_now')){
           $po = $this->purchase_order_status('Received',$this->input->post('purchaseorder_id'));
        }
        
        ////Create Account Voucher/////
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(20);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Goods Received against GRN ID ' . $order_id . ' on '. date('d-m-Y').', for  PO ID: '. $this->input->post('purchaseorder_id') .' Supplier Name: '. $this->input->post('suppliername'),
                'voucher_date' => $grndate=="" ? date('Y-m-d H:i:s') : $grndate,
                'voucher_amount' => $inventory_increase,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 2,
                'business_partner_id'=>$this->input->post('supplier_id'),
                'business_partner_name'=>$this->input->post('suppliername'),
                'voucher_type'=>3,
                'payment_mode'=>'cash',
                'bank_name'=>$bank_name,
                'purchase_order_id'=>$this->input->post('purchaseorder_id'),
                'grn_id'=>$order_id,
                'auto_voucher'=>'Yes'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                
                if($debit[2]=="inventory"){$debitamount= $inventory_increase;}
                if($debit[2]=="purchase_salestax"){$debitamount= $sales_tax;}
                if($debit[2]=="purchase_withholdingtax"){$debitamount= $withholding_tax;}
                
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
               
                if($credit[2]=="payables"){$creditamount= $payable;}
                if($credit[2]=="purchase_withholdingtax"){$creditamount= $withholding_tax;}
                if($credit[2]=="purchase_discount"){$creditamount= $purchase_discount;}
                
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        }
        
        return $order_id;
    }

    
    function return_note_addupdate(){
        
        
        
        $purchaseorder_id = $this->input->post('purchaseorder_id');
        $grn_id = $this->input->post('grn_id');
        $supplier_id = $this->input->post('supplier_id');
        $suppliername = $this->input->post('suppliername');
        $businessid = $this->input->post('businessid');
        //exit();
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['orderdata']);

        // Decode the JSON array
        $tableData = json_decode($tableData, TRUE);
        
        foreach ($tableData as $row) {
             
            ///check the inventory in batch before proceeding
                $stopproduct='';

                $qty=0;
                $batch = $this->product_model->get_a_batch($row['grnbatchid'], date('Y-m-d'), $this->session->userdata('businessid'));

                if($batch){
                    $qty=$batch->total_stock;
                    if($qty < $row['returnQty'] && $row['returnQty']>0){
                        $stopproduct=$batch->product;
                        return('error|Stock Qty left in '.$stopproduct.' batch '.$row['grnbatchid'].' is '.$qty.' and is less then the Return Qty');
                    }

                } else {

                    return('error|Stock Qty left in '.$stopproduct.' batch '.$row['grnbatchid'].' is '.$qty.' and is less then the Return Qty');
                }

            ////////////
        }
        
        $data = [];
        $count=0;
        foreach ($tableData as $row) {
            
             if($row['returnQty']>0){
              
                //create return note                
                $data=array(
                    'return_date' => date('Y-m-d'),
                    'batch_id' => $row['grnbatchid'],
                    'product_id' => $row['productid'],
                    'user_id' => $this->session->userdata('userid'),
                    'business_id' => $this->input->post('businessid'),
                    'grn_id' => $this->input->post('grn_id'),
                    'return_qty' => $row['returnQty']
                );
                
               
                $this->db->insert('return_notes', $data);
                $return_note_id = $this->db->insert_id();
                
                //update existing batch amount
                    //New scenario where grn count is used to get the purchased qty
                    $this->db->select('grn_batch_id, round(sum(grn_unit_price*(grn_qty_received-ifnull(return_qty,0)))/sum(grn_qty_received-ifnull(return_qty,0)),2) as avg_unit_cost', false);
                    $this->db->join('(select batch_id, sum(return_qty) as return_qty from return_notes 
                                    where batch_id='.$row['grnbatchid'].'
                                    group by batch_id) as a', 'grn_batch_id = batch_id', false);
                    $this->db->where('grn_batch_id', $row['grnbatchid']);
                    $this->db->group_by('grn_batch_id');
                    
                    $q = $this->db->get('grn_details');

                    $all_grn=$q->row();
                    if($all_grn){
                        $grn_unit_cost=$all_grn->avg_unit_cost;
                    }else {
                        $grn_unit_cost=0;            
                    }

                    $this->db->select('batch_id, round(sum(unit_price*adjustment_qty)/sum(adjustment_qty),2) as avg_unit_cost', false);
                    $this->db->where('batch_id', $row['grnbatchid']);
                    $this->db->where('adjustment_qty >', 0);
                    $this->db->group_by('batch_id');
                    $z = $this->db->get('adjustment_notes');

                    $all_adjustments=$z->row();
                    if($all_adjustments){
                        $adjustment_unit_cost=$all_adjustments->avg_unit_cost;
                    }else {
                        $adjustment_unit_cost=0;            
                    }
                    


                    if($grn_unit_cost>0 && $adjustment_unit_cost>0){
                        $final_unit_cost= ($grn_unit_cost+$adjustment_unit_cost)/2;
                    } else {
                        $final_unit_cost= $grn_unit_cost+$adjustment_unit_cost;
                    }

                    $this->db->set('batch_amount', $final_unit_cost);  
                    $this->db->where('id_batch=',$row['grnbatchid']);
                    $this->db->update('product_batch');
                
             ///////   
                
                
                
            //create account voucher
            if($this->session->userdata('auto_voucher')=='Yes'){
            //
            //
            /////get the batch amount
            $this->db->select('*');
            $this->db->where('id_batch', $row['grnbatchid']);
            $query = $this->db->get('product_batch');
            $batch = $query->row();

            $batch_amount = (float)$row['productunitprice'] * $row['returnQty'];
            
            //create inventory and cost of goods voucher/////////////////////////////////
                $debit_accounts=[];
                $credit_accounts=[];

                $account_heads = $this->accounting_model->get_mapped_accounts(21);
                //var_dump ($account_heads); exit();
                foreach($account_heads as $ah){
                    if($ah['transaction_type']=='debit'){
                       array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                    } else {
                        array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                    }
                }

                $bank_name='';
                //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
                $data = array( 
                    'business_id' => $this->session->userdata('businessid'),
                    'description' => 'Return Voucher against grn ID '. $grn_id . ' PO ID ' . $purchaseorder_id. ' on '. date('d-m-Y').', for '.$suppliername.' supplier ID : '. $supplier_id,
                    'voucher_date' => date('Y-m-d H:i:s'),
                    'voucher_amount' => $batch_amount,
                    'voucher_status' => 'Active',
                    'created_by' => $this->session->userdata('username'),
                    'cost_center'=> '1',
                    'cost_center_name'=> 'Front Desk',
                    'business_partner'=> 2,
                    'business_partner_id'=>$supplier_id,
                    'business_partner_name'=>$suppliername,
                    'voucher_type'=>3,
                    'payment_mode'=>'Cash',
                    'bank_name'=>$bank_name,
                    'purchase_order_id'=>$purchaseorder_id,
                    'return_note_id'=>$return_note_id,
                    'grn_id'=>$grn_id,
                    'auto_voucher'=>'Yes',
                    //'sale_type'=>'sale'
                );

                $this->db->insert('account_vouchers', $data);
                $cogs_voucherid =  $this->db->insert_id();

                //enter debit entries

                foreach($debit_accounts as $debit_account){
                    $debitamount=0;
                    $debit = explode("|", $debit_account);
                    //check entity

                    if($debit[2]=="payable"){$debitamount= $batch_amount;}

                    $data_detail=array(
                        'account_voucher_id' => $cogs_voucherid,
                        'account_head_id' => $debit[0],
                        'debit' => round($debitamount,2),
                        'credit' => 0
                    );
                    //insert debit detail
                    if($debitamount>0){
                        $this->db->insert('account_voucher_detail', $data_detail);
                    }
                }
                //enter credit entries
                foreach($credit_accounts as $credit_account){
                    $creditamount=0;
                    $credit = explode("|", $credit_account);
                    //check entity

                    if($credit[2]=="inventory"){$creditamount= $batch_amount;}

                    $data_detail=array(
                        'account_voucher_id' => $cogs_voucherid,
                        'account_head_id' => $credit[0],
                        'debit' => 0,
                        'credit' => round($creditamount,2)
                    );
                    //insert credit detail
                    if($creditamount>0){
                        $this->db->insert('account_voucher_detail', $data_detail);
                    }
                }
             }
                
             }
             $count++;
         }
        return "success|".$count;
        
    }
    
    
    function purchnaseorder_qty_update($poid, $bid, $pid, $rqty, $instock, $inhouse) {
        $this->db->select('sum(product_received_qty) as rqty');
        $this->db->where('purchase_order_id', $poid);
        $this->db->where('brand_id', $bid);
        $this->db->where('product_id', $pid);
        $query = $this->db->get('purchase_order_details');

        $result = $query->result_array();
        //$qtyreceived = $rqty + $result[0]['rqty'];
        $qtyreceived = $rqty;

        $data = array(
            'product_received_qty' => $qtyreceived,
            'product_instock_qty' => $instock,
            'product_inhouse_qty' => $inhouse
        );
        $this->db->where('purchase_order_id', $poid);
        $this->db->where('brand_id', $bid);
        $this->db->where('product_id', $pid);
        $this->db->update('purchase_order_details', $data);

        return $this->input->post('purchaseorder_id', TRUE);
    }

    //This function is updating instock inhouse in business_product table
    function grn_product_instock_inhouse_update($poid, $bid, $pid, $in_stock, $inhouse_stock) {
        $this->db->select('in_stock, inhouse_stock');
        $this->db->where('brand_id', $bid);
        $this->db->where('id_business_products', $pid);
        $query = $this->db->get('business_products');

        $result = $query->result_array();
        $instock_exist = $in_stock + $result[0]['in_stock'];
        $inhouse_stock_exist = $inhouse_stock + $result[0]['inhouse_stock'];

        $data = array(
            'in_stock' => $instock_exist,
            'inhouse_stock' => $inhouse_stock_exist
        );
        $this->db->where('brand_id', $bid);
        $this->db->where('id_business_products', $pid);
        $this->db->update('business_products', $data);

        return $poid;
    }

    function purchase_order_status($status, $poid) {
        $data = array(
            'status' => $status
        );
        $this->db->where('idpurchase_order', $poid);
        $this->db->update('purchase_order', $data);

        return $this->input->post('purchaseorder_id', TRUE);
    }

    function update_grn_number($last_insert_id) {
        $this->db->select('*');
        $query = $this->db->get('goods_received_note');
        $number_rows = $query->num_rows();

        $grn_number = 'GRN' . date('Yd') . $last_insert_id . '' . $number_rows . '';
        $data = array(
            'grn_number' => $grn_number
        );
        $this->db->where('grn_id', $last_insert_id);
        $this->db->update('goods_received_note', $data);
        return $grn_number;
    }

    function get_grn_purchase_orders() {
        $this->db->select('*');
        //$this->db->where('status', 'Delivered');
        //$this->db->or_where('status', 'partial');
        $query = $this->db->get('purchase_order');

        return $query->result_array();
    }

    function get_po_grns($purchaseorder_id) {
        
        $this->db->select('grn.grn_id, gd.grn_detail_id, grn_number, date_format(grn_created_date,"%d-%m-%Y %h:%i") d, '
                . 'bb.business_brand_name, product, grn_unit_price, grn_batch_number, '
                . 'grn_qty_received as received, ifnull(sum(return_qty),0) as returned, grn_comment',false);
        $this->db->join('grn_details gd', 'gd.grn_id = grn.grn_id');
        $this->db->join('business_products bp', 'gd.grn_product_id = bp.id_business_products');
        $this->db->join('business_brands bb', 'bp.brand_id = bb.id_business_brands');
        $this->db->join('return_notes rn', 'grn.grn_id = rn.grn_id and rn.product_id = gd.grn_product_id and rn.batch_id = gd.grn_batch_id', 'left');
        $this->db->where('grn.purchase_order_id', $purchaseorder_id);
        $this->db->group_by('grn_id, gd.grn_detail_id');
        $query = $this->db->get('goods_received_note as grn');
        
       //echo $query; exit(); 
       // $query = $this->db->query($sql);
        
        return $query->result_array();
    }
    
    
    
    
    function get_grn_for_create($purchaseorder_id){

        
        $sql="SELECT * , ifnull(a.received,0) as received_qty
                FROM purchase_order_details 
                JOIN business_products bp ON bp.id_business_products = purchase_order_details.product_id
                JOIN business_brands bb ON bb.id_business_brands = bp.brand_id
                JOIN purchase_order po on po.idpurchase_order = purchase_order_details.purchase_order_id
                JOIN business on business.id_business = po.business_id
                LEFT JOIN (

                        select grn_product_id, ifnull(sum(grn_qty_received),0) as received, 
                         ifnull(sum(b.returned),0) as returned
                        FROM goods_received_note as grn 
                        JOIN grn_details gd ON gd.grn_id = grn.grn_id 
                        left JOIN 
                                (
                                select grn_id, product_id, ifnull(sum(return_qty),0) as returned 
                                from return_notes where return_status='Active' group by product_id
                                )  as b on b.grn_id = gd.grn_id and b.product_id=gd.grn_product_id

                        where grn.purchase_order_id = '".$purchaseorder_id."'
                        group by grn_product_id


                ) a on purchase_order_details.product_id = a.grn_product_id
                WHERE purchase_order_details.purchase_order_id = '".$purchaseorder_id."' 
                ORDER BY purchase_order_details.product_id";
        
        $query = $this->db->query($sql);
        return $query->result_array();
    }
    
    function get_grn_by_id($grn_id){
        
        $this->db->select('b.business_name, b.id_business, business_supplier.id_business_supplier as supplier_id, business_supplier.supplier_name, business_supplier.contact_number, business_supplier.ho_address, 
                        po.idpurchase_order, po.purchase_order_number, grn.grn_number, 
                        grn_detail_id, grn.grn_id, bp.product, bb.business_brand_name, grn_qty_received, 
                        grn_unit_price, grn_batch_number, grn_batch_id, date_format(grn_created_date,"%y-%m-%d") as grn_date,
                        date_format(grn_created_date,"%d-%m-%Y") as grn_date_print,
                        date_format(expiry_date,"%d-%m-%Y") as expiry_date,
                        grn_brand_id, grn_product_id, grn_comment');
        $this->db->join('product_batch pb', 'pb.id_batch = gd.grn_batch_id');
        $this->db->join('business_products bp', 'bp.id_business_products = gd.grn_product_id');
        $this->db->join('business_brands bb', 'bb.id_business_brands = gd.grn_brand_id');
        $this->db->join('goods_received_note grn', 'grn.grn_id=gd.grn_id');
        $this->db->join('purchase_order po', 'po.idpurchase_order = grn.purchase_order_id');
        $this->db->join('business b', 'b.id_business = po.business_id');
        $this->db->join('business_supplier', 'po.supplier_id = business_supplier.id_business_supplier');
        $this->db->where('gd.grn_id=', $grn_id);
        $query=$this->db->get('grn_details gd');
        
        return $query->result_array();
        
    }
    
    function get_grn_list_detail($purchaseorder_id) {
        $this->db->select('grn_number, grn.created_by as username, gd.grn_detail_id,  '
                . 'gd.grn_brand_id, gd.grn_product_id, gd.grn_brand_name, gd.grn_product_name, '
                . 'gd.grn_qty_received, gd.grn_unit_price, gd.grn_batch_number, DATE_FORMAT(grn.grn_created_date, "%d-%m-%Y") as grn_created_date, '
                . 'grn.created_by');
        $this->db->join('grn_details gd', 'gd.grn_id = grn.grn_id');
        $this->db->where('grn.purchase_order_id', $purchaseorder_id);
        $query = $this->db->get('goods_received_note as grn');

        return $query->result_array();
    }

    function edit_purchaseorder($purchaseorder_id) {
        
        $sql = "SELECT * FROM goods_received_note
                where purchase_order_id=" . $purchaseorder_id;
        
        $grn = $this->db->query($sql);
        
        if($grn->num_rows() > 0){
            $detail = array(
                    'supplier_name'=>"GRN already Created"
                    );
            $data = [0=>$detail];
            return $data;
            exit();
        }
        
        
        $this->db->select('po.idpurchase_order, po.supplier_id, po.supplier_name, po.order_date');
        $this->db->where('po.idpurchase_order', $purchaseorder_id);
        $query = $this->db->get('purchase_order po');

        return $query->result_array();
    }

    function edit_purchaseorder_detail($purchaseorder_id) {
        $this->db->select('pod.brand_id,pod.brand_name,pod.product_id,pod.product_name,pod.product_purchase_price,product_qty');
        $this->db->where('pod.purchase_order_id', $purchaseorder_id);
        $query = $this->db->get('purchase_order_details pod');

        return $query->result_array();
    }

    function updatepurchase_orders() {
        $this->db->where('purchase_order_id', $this->input->post('purchaseorder_id', TRUE));
        $result = $this->db->delete('purchase_order_details');
        if ($result) {
            // Unescape the string values in the JSON array
            $tableData = stripcslashes($this->input->post('orderdata', TRUE));

            // Decode the JSON array
            $tableData = json_decode($tableData, TRUE);

            // now $tableData can be accessed like a PHP array
            // echo $tableData[0]['servicename'];
            //add new customer_visit
            $total_qty = 0;
            $total_price = 0;
            foreach ($tableData as $row1) {
                $total_price += $row1['productprice'] * $row1['productqty'];
                $total_qty += $row1['productqty'];
            }
            $order = array(
                'business_id' => $this->session->userdata('businessid'),
                'supplier_id' => $tableData[0]['supplierid'],
                'supplier_name' => $tableData[0]['suppliername'],
                'total_purchase_pirce' => $total_price,
                'product_total_qty' => $total_qty,
                'order_date' => $tableData[0]['orderdate'],
                'created_by' => $this->session->userdata('username')
            );
            //var_dump($order); exit();
            $this->db->where('idpurchase_order', $this->input->post('purchaseorder_id', TRUE));
            $this->db->update('purchase_order', $order);
            $order_id = $this->input->post('purchaseorder_id', TRUE);

            $data = [];

            foreach ($tableData as $row) {

                $data = array(
                    'purchase_order_id' => $order_id,
                    'brand_id' => $row['brandid'],
                    'brand_name' => $row['brandname'],
                    'product_id' => $row['productid'],
                    'product_name' => $row['productname'],
                    'product_purchase_price' => $row['productprice'],
                    'product_qty' => $row['productqty']
                );

                $this->db->insert('purchase_order_details', $data);
            }

            return $order_id;
        }
    }

    function updategrn() {

        //Fetch instock inhouse from business product table....
        $this->db->select('in_stock, inhouse_stock');
        $this->db->where('id_business_products', $this->input->post('grn_product_id'));
        $this->db->where('brand_id', $this->input->post('grn_brand_id'));
        $query = $this->db->get('business_products');

        $result = $query->row();

        $instock_qty = $result->in_stock; //exist instock qty
        $inhouse_qty = $result->inhouse_stock; //exist inhouse qty

        $new_instock = $instock_qty - $this->input->post('instock_orignal'); //exist instock - with grn instock 
        $new_inhouse = $inhouse_qty - $this->input->post('inhouse_orignal'); //exist inhouse - with grn inhouse

        $new_instock = $new_instock + $this->input->post('grn_qty_instock'); //add new instock qty
        $new_inhouse = $new_inhouse + $this->input->post('grn_qty_inhouse'); //add inhouse qty
        //Update instock inhouse in business product table...
        $data = array(
            'in_stock' => $new_instock,
            'inhouse_stock' => $new_inhouse,
        );

        $this->db->where('id_business_products', $this->input->post('grn_product_id'));
        $this->db->where('brand_id', $this->input->post('grn_brand_id'));
        $this->db->update('business_products', $data);

        $data = array(
            'grn_unit_price' => $this->input->post('grn_unit_price'),
            'grn_qty_received' => $this->input->post('grn_qty_received'),
            'grn_qty_instock' => $this->input->post('grn_qty_instock'),
            'grn_qty_inhouse' => $this->input->post('grn_qty_inhouse')
        );

        $this->db->where('grn_detail_id', $this->input->post('grn_detail_id'));
        $this->db->update('grn_details', $data);

        return $this->input->post('grn_detail_id');
    }
    function get_product_batches($product_id){
        $this->db->select('*');
        $this->db->join('business_stores','business_stores.id_business_stores = product_batch.store_id');
        $this->db->join('business','business_stores.business_id = business.id_business');
        $this->db->where('product_id = ', $product_id);
        
        if($this->session->userdata('ho')=='No'){
            $this->db->where('id_business = ', $this->session->userdata('businessid'));
        }
        
        $query = $this->db->get('product_batch');
        
        return $query->result_array();
        
    }
    
    function get_receiving_notes($startdate, $enddate){
        $brand_id=$this->input->post('brand');
        $product_id=$this->input->post('product');
        $supplier_id=$this->input->post('supplier');
        
        $sql = "SELECT *, goods_received_note.created_by as 'by' FROM business_products
                join business_brands on business_brands.id_business_brands = business_products.brand_id
                join product_batch on product_batch.product_id = business_products.id_business_products
                join business_stores on business_stores.id_business_stores = product_batch.store_id
                join grn_details on grn_details.grn_batch_id = product_batch.id_batch
                join goods_received_note on goods_received_note.grn_id = grn_details.grn_id
                join purchase_order on purchase_order.idpurchase_order = goods_received_note.purchase_order_id
                where grn_created_date >= '".$startdate."'
                and grn_created_date <= '".$enddate."' ";
        if(null!==$brand_id && $brand_id!==''){
            $sql .= " and grn_brand_id = ".$brand_id." ";
        }    
        if(null!==$product_id && $product_id!==''){
            $sql .= " and grn_product_id = ".$product_id." ";
        }
        if(null!==$supplier_id && $supplier_id!==''){
            $sql .= " and purchase_order.supplier_id = ".$supplier_id." ";
        }
       if($this->session->userdata('ho')=='No'){
             $sql .= " and goods_received_note.business_id = ". $this->session->userdata('businessid')." ";
        }
        $sql .= " order by idpurchase_order,  goods_received_note.grn_id;";
        
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    
    
    function get_return_notes($startdate, $enddate){
        $brand_id=$this->input->post('brand');
        $product_id=$this->input->post('product');
       
        
        $sql = "SELECT *, date_format(return_date,'%d-%m-%Y %h:%i:%s') as return_note_date, users.user_fullname as 'by',
            round(return_notes.return_qty*grn_details.grn_unit_price,2) as 'return_value'
            FROM return_notes
                join business_products on business_products.id_business_products = return_notes.product_id
                join business_brands on business_brands.id_business_brands = business_products.brand_id
                join product_batch on product_batch.id_batch = return_notes.batch_id and product_batch.product_id = return_notes.product_id
                join business_stores on business_stores.id_business_stores = product_batch.store_id                
                join users on users.id_users = return_notes.user_id
                join goods_received_note on goods_received_note.grn_id = return_notes.grn_id 
                join grn_details on grn_details.grn_id = goods_received_note.grn_id and return_notes.product_id=grn_details.grn_product_id
                where return_date >= '".$startdate."'
                and return_date <= '".$enddate."' ";
        if(null!==$brand_id && $brand_id!==''){
            $sql .= " and business_products.brand_id = ".$brand_id." ";
        }    
        if(null!==$product_id && $product_id!==''){
            $sql .= " and return_notes.product_id = ".$product_id." ";
        }
         if($this->session->userdata('ho')=='No'){
            $sql .= " and return_notes.business_id = ". $this->session->userdata('businessid')." ";
        }
        
        $sql .= " order by id_return_notes;";
        
        //echo $sql; exit();
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    
}
