<?php

class Transfernotes_model extends CI_Model {

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

//    function get_incoming_gtn_list() {
//        $startdate = $this->input->post('startdate', TRUE);
//        $enddate = $this->input->post('enddate', TRUE);
//
//        $store = $this->input->post('selectstore');
//        
//        //echo $store;
//         
//        $this->db->select('gtn_id, id_business_products, id_transfer_notes, 
//            DATE_FORMAT(transfer_date, "%d-%m-%Y %h:%i:%s") as transfer_date,
//        business_store, product, product_batch.batch_number, tranfer_out_qty, tranfer_in_qty, product_batch.id_batch, 
//        product_batch.store_id,  transfer_notes.created_by, product_batch.batch_amount price, 
//        round((product_batch.batch_amount*tranfer_in_qty),2) transferamount', false );
//        $this->db->join('product_batch','id_batch = transfer_notes.batch_id ');
//        $this->db->join('business_products','business_products.id_business_products = product_batch.product_id');
//        $this->db->join('business_stores','id_business_stores = product_batch.store_id');
//        
//        $this->db->where('transfer_notes.transfer_date >= ', $startdate.' 00:00:00');
//        $this->db->where('transfer_notes.transfer_date <= ', $enddate.' 23:59:59' );
//        if($store!=='All'){
//            $this->db->where('business_stores.id_business_stores', $store );
//        }
//        $this->db->order_by('1,3,4', 'desc');
//        $query = $this->db->get_compiled_select('transfer_notes');
//        echo $query; exit();
//        return $query->result_array();
//    }

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

        $fromstore = $this->input->post('selectfromstore');
        $tostore = $this->input->post('selecttostore');
        
        if($fromstore>0){
            
            $sql = "SELECT id_gtn, sum(transfer_notes.tranfer_out_qty) tranfer_out_qty,
                sum(transfer_notes.tranfer_in_qty) tranfer_in_qty,
                DATE_FORMAT(transfer_date, '%d-%m-%Y %h:%i:%s') as transfer_date, 
               transfer_notes.created_by, transfer_notes.requisition_id, 
               id_batch, batch_number, id_business_products, product, qty_per_unit, measure_unit, 
               id_business_stores, business_store, round(ifnull(batch_amount,0),2) batch_amount,
               round(ifnull(batch_amount,0)*sum(transfer_notes.tranfer_out_qty),2) as 'Cost of Transferred Goods' , business_brand_name
               FROM transfer_notes join gtn on gtn.id_gtn = transfer_notes.gtn_id
                join product_batch on transfer_notes.batch_id = product_batch.id_batch
                join business_stores on business_stores.id_business_stores = product_batch.store_id 
                join business_products on business_products.id_business_products = product_batch.product_id
                join business_brands on business_products.brand_id = business_brands.id_business_brands
                
            where transfer_date >=  '". $startdate." 00:00:00'  
            and transfer_date <= '". $enddate." 23:59:59'
              and id_gtn in (
                select id_gtn from gtn 
                    join transfer_notes on transfer_notes.gtn_id = gtn.id_gtn
                    join product_batch on transfer_notes.batch_id = product_batch.id_batch 
                    where transfer_date >=  '". $startdate." 00:00:00'  
                    and transfer_date <= '". $enddate." 23:59:59' 
                    and product_batch.store_id = ".$fromstore ." 
              ) 
            ";
            if($tostore>0){
                $sql .= " and gtn.to_store = ".$tostore ." ";
            }        
            $sql.=" group by  transfer_notes.id_transfer_notes order by id_gtn, transfer_notes.id_transfer_notes";

        } else {
            $sql = "SELECT id_gtn, sum(transfer_notes.tranfer_out_qty) tranfer_out_qty,
                sum(transfer_notes.tranfer_in_qty) tranfer_in_qty,
                DATE_FORMAT(transfer_date, '%d-%m-%Y %h:%i:%s') as transfer_date, 
               transfer_notes.created_by, transfer_notes.requisition_id, 
               id_batch, batch_number, id_business_products, product, qty_per_unit, measure_unit, 
               id_business_stores, business_store, round(ifnull(batch_amount,0),2) batch_amount,
               round(ifnull(batch_amount,0)*sum(transfer_notes.tranfer_out_qty),2) as 'Cost of Transferred Goods' , business_brand_name
               FROM transfer_notes join gtn on gtn.id_gtn = transfer_notes.gtn_id
                join product_batch on transfer_notes.batch_id = product_batch.id_batch
                join business_stores on business_stores.id_business_stores = product_batch.store_id 
                join business_products on business_products.id_business_products = product_batch.product_id
                 join business_brands on business_products.brand_id = business_brands.id_business_brands
            where transfer_date >=  '". $startdate." 00:00:00'  
            and transfer_date <= '". $enddate." 23:59:59'     ";
            if($tostore>0){
                $sql .= " and gtn.to_store = ".$tostore ." ";
            }        
            $sql.=" group by  id_transfer_notes order by id_gtn, transfer_notes.id_transfer_notes";            
            
        }
         
        //echo $sql;; exit();
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    function create_gtn($tostore){
        $this->db->set('gtn_date', date('Y-m-d H:s:i'));
        $this->db->set('created_by', $this->session->userdata('username'));
        $this->db->set('business_id', $this->session->userdata('businessid'));
        $this->db->set('to_store', $tostore);
        $this->db->insert('gtn');
        
        return $this->db->insert_id();
        
    }
    
    function createtransfernote($data){
      //  var_dump($data);exit();
        $this->db->insert('transfer_notes', $data);
        
        return $this->db->insert_id();
    }
    
    function createinventorydecrease($data, $fromstore,  $tostore, $batch_amount){
      //  var_dump($data);exit();
        //get the business id of the new store
        
        $this->db->select('*');
        $this->db->join('business', 'id_business = business_id');
        $this->db->where('id_business_stores', $tostore);
        $query = $this->db->get('business_stores');
        $to_store = $query->row();
        
        $this->db->select('*');
        $this->db->join('business', 'id_business = business_id');
        $this->db->where('id_business_stores', $fromstore);
        $query1 = $this->db->get('business_stores');
        $from_store = $query1->row();
        
        if($to_store->id_business != $from_store->id_business) {   
           //create inventory and cost of goods voucher/////////////////////////////////
           if($this->session->userdata('auto_voucher')=='Yes'){
               $debit_accounts=[];
               $credit_accounts=[];
               $description='';
              
                $account_heads = $this->accounting_model->get_mapped_accounts(34);
                $description = 'Inventory Transferred Out from '.$from_store->business_name.' store '.$from_store->business_store.' to '.$to_store->business_name.' store '.$to_store->business_store.' through Transfer note ID '. $data['gtn_id'] . ' on '. date('d-m-Y');
             
               //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' => $from_store->id_business,
                   'description' => $description,
                   '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'=> 'Back Office',
                   'business_partner'=> 4,
                   'business_partner_id'=> $to_store->business_id,
                   'business_partner_name'=>$to_store->business_name,
                   'voucher_type'=>3,
                   //'payment_mode'=>$paymentmode,
                   //'bank_name'=>$bank_name,
                   'gtn_id'=>$data['gtn_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]=="receivable"){$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_out"){$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);
                   }
               }
           }
        }
    }

    function createinventoryincrease($data, $fromstore, $tostore, $batch_amount){
      //  var_dump($data);exit();
       
        //get the business id of the new store
        
       $this->db->select('*');
        $this->db->join('business', 'id_business = business_id');
        $this->db->where('id_business_stores', $tostore);
        $query = $this->db->get('business_stores');
        $to_store = $query->row();
        
        $this->db->select('*');
        $this->db->join('business', 'id_business = business_id');
        $this->db->where('id_business_stores', $fromstore);
        $query1 = $this->db->get('business_stores');
        $from_store = $query1->row();
       
        if($to_store->id_business != $from_store->id_business) { 
           //create inventory and cost of goods voucher/////////////////////////////////
           if($this->session->userdata('auto_voucher')=='Yes'){
               $debit_accounts=[];
               $credit_accounts=[];
               $description='';
              
                $account_heads = $this->accounting_model->get_mapped_accounts(34, $to_store->id_business);
                $description = 'Inventory Transferred In from '.$from_store->business_name.' store '.$from_store->business_store.' to '.$to_store->business_name.' store '.$to_store->business_store.' through Transfer note ID '. $data['gtn_id'] . ' on '. date('d-m-Y');
             
               //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' => $to_store->business_id,
                   'description' => $description,
                   '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'=> 'Back Office',
                   'business_partner'=> 4,
                   'business_partner_id'=> $from_store->id_business,
                   'business_partner_name'=> $from_store->business_name,
                   'voucher_type'=>3,
                   //'payment_mode'=>$paymentmode,
                   //'bank_name'=>$bank_name,
                   'gtn_id'=>$data['gtn_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]=="inventory_in"){$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]=="payable"){$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);
                   }
               }
           }
        } else {
            if($this->session->userdata('auto_voucher')=='Yes'){
               $debit_accounts=[];
               $credit_accounts=[];
               $description='';
              
               //$account_heads = $this->accounting_model->get_mapped_accounts(34, $from_store->id_business);
                      
               if(isset($to_store->account_head_id)){
                    if(null==$to_store->account_head_id || null==$from_store->account_head_id){
                        return false;
                    }
               }else{
                   return false;
               }
               
               $description = 'Inventory Transferred In from '.$from_store->business_name.' store '.$from_store->business_store.' to '.$to_store->business_name.' store '.$to_store->business_store.' through Transfer note ID '. $data['gtn_id'] . ' on '. date('d-m-Y');
               //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' => $to_store->business_id,
                   'description' => $description,
                   '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'=> 'Back Office',
                   'business_partner'=> 4,
                   'business_partner_id'=> $from_store->id_business,
                   'business_partner_name'=> $from_store->business_name,
                   'voucher_type'=>3,
                   //'payment_mode'=>$paymentmode,
                   //'bank_name'=>$bank_name,
                   'gtn_id'=>$data['gtn_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]=="inventory_in"){$debitamount= $batch_amount;}
                   $debitamount= $batch_amount;

                   $data_detail=array(
                       'account_voucher_id' => $cogs_voucherid,
                       'account_head_id' => $to_store->account_head_id,
                       '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]=="payable"){$creditamount= $batch_amount;}
                   $creditamount= $batch_amount;

                   $data_detail=array(
                       'account_voucher_id' => $cogs_voucherid,
                       'account_head_id' => $from_store->account_head_id,
                       'debit' => 0,
                       'credit' => round($creditamount,2)
                   );
                   //insert credit detail
                   //if($creditamount>0){
                       $this->db->insert('account_voucher_detail', $data_detail);
                   //}
               //}
            }
        }
    }
 
}
