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

class Reports extends CI_Controller {
    public $start = '';
    public $end = '';
    public $state_array = '';
    public function __construct() {
        parent::__construct();
        if (! $this->session->userdata ( 'user_logged_in' ) || !company_url($this->session->userdata ('company_slag'))) {
            redirect ( 'login', 'refresh' );
        }
        $this->load->vars ( array (
                'global' => 'Available to all views',
                'header' => 'common/header',
                'left' => 'common/left',
                'footer' => 'common/footer' 
        ) );

        $this->start = date('Y-m').'-01';
        $this->end = date('Y-m-t');

        $this->load->model('User_model');
        $this->load->model('Item_model');
        $this->load->model('Reports_model');

        $this->state_array = array('-','Jammu & Kashmir','Himachal Pradesh','Punjab','Chandigarh','Uttarakhand','Haryana','Delhi','Rajasthan','Uttar Pradesh','Bihar','Sikkim','Arunachal Pradesh','Nagaland','Manipur','Mizoram','Tripura','Meghalaya','Assam','West Bengal','Jharkhand','Odisha','Chhattisgarh','Madhya Pradesh','Gujarat','Daman & Diu','Dadra & Nagar Haveli','Maharashtra','Karnataka','Goa','Lakshdweep','Kerala','Tamil Nadu','Pondicherry','Andaman & Nicobar Islands','Telengana','Andhra Pradesh','Other Territory');
    }

    public function b2b(){
        $data['start_date'] = !empty($this->input->post('from')) ? $this->input->post('from') : $this->start; 
        $data['end_date'] = !empty($this->input->post('to')) ? $this->input->post('to') : $this->end; 
        $data['data'] = $this->input->post('data'); 
        $data['excel'] = $this->input->post('excel'); 
        $data['report'] = $this->Reports_model->generate_b2b(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
        //echo $this->db->last_query();die();
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['GSTIN/UIN of Recipient'] = $value->gstn;
                        $csv_arr[$key]['Invoice Number'] = $value->invoice_no;
                        $csv_arr[$key]['Invoice date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice Value'] = $value->total;
                        $csv_arr[$key]['Place Of Supply'] = $value->shipping_state.'-'.$this->state_array[$value->shipping_state];
                        $csv_arr[$key]['Reverse Charge'] = 0.00;
                        $csv_arr[$key]['Invoice Type'] = 'Rgular';
                        $csv_arr[$key]['E-Commerce GSTIN'] = 'NA';
                        $csv_arr[$key]['Rate'] = $value->gst_rate;
                        $csv_arr[$key]['Taxable Value'] = $value->taxable_amount;
                        $csv_arr[$key]['Cess Amount'] = 0.00;
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('b2b_report',$data);
        }
    }

    public function b2cl(){
        $data['start_date'] = !empty($this->input->post('from')) ? $this->input->post('from') : $this->start; 
        $data['end_date'] = !empty($this->input->post('to')) ? $this->input->post('to') : $this->end; 
        $data['data'] = $this->input->post('data'); 
        $data['excel'] = $this->input->post('excel'); 
        $data['report'] = $this->Reports_model->generate_b2cl(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
        //echo $this->db->last_query();die();
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        //$csv_arr[$key]['GSTIN/UIN of Recipient'] = $value->gstn;
                        $csv_arr[$key]['Invoice Number'] = $value->invoice_no;
                        $csv_arr[$key]['Invoice date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice Value'] = $value->total;
                        $csv_arr[$key]['Place Of Supply'] = $value->shipping_state.'-'.$this->state_array[$value->shipping_state];
                        //$csv_arr[$key]['Reverse Charge'] = 0.00;
                        //$csv_arr[$key]['Invoice Type'] = 'Rgular';
                        $csv_arr[$key]['Rate'] = $value->gst_rate;
                        $csv_arr[$key]['Taxable Value'] = ($value->taxable_amount);
                        $csv_arr[$key]['Cess Amount'] = 0.00;
                        $csv_arr[$key]['E-Commerce GSTIN'] = '';
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('b2cl_report',$data);
        }
    }

    public function b2cs(){
        $data['start_date'] = !empty($this->input->post('from')) ? $this->input->post('from') : $this->start; 
        $data['end_date'] = !empty($this->input->post('to')) ? $this->input->post('to') : $this->end; 
        $data['data'] = $this->input->post('data'); 
        $data['excel'] = $this->input->post('excel'); 
        $data['report'] = $this->Reports_model->generate_b2cs(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
        //echo $this->db->last_query();die();
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        //$csv_arr[$key]['GSTIN/UIN of Recipient'] = $value->gstn;
                        $csv_arr[$key]['Invoice Number'] = $value->invoice_no;
                        $csv_arr[$key]['Invoice date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice Value'] = $value->total;
                        $csv_arr[$key]['Place Of Supply'] = $value->shipping_state.'-'.$this->state_array[$value->shipping_state];
                        //$csv_arr[$key]['Reverse Charge'] = 0.00;
                        //$csv_arr[$key]['Invoice Type'] = 'Rgular';
                        $csv_arr[$key]['Rate'] = $value->gst_rate;
                        $csv_arr[$key]['Taxable Value'] = ($value->taxable_amount);
                        $csv_arr[$key]['Cess Amount'] = 0.00;
                        $csv_arr[$key]['E-Commerce GSTIN'] = '';
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('b2cs_report',$data);
        }
    }

    public function purchase(){
        $data['start_date'] = !empty($this->input->post('from')) ? $this->input->post('from') : $this->start; 
        $data['end_date'] = !empty($this->input->post('to')) ? $this->input->post('to') : $this->end; 
        $data['data'] = $this->input->post('data'); 
        $data['excel'] = $this->input->post('excel'); 
        $data['report'] = $this->Reports_model->generate_purchase(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
        // echo $this->db->last_query();die();
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['GSTIN/UIN of Recipient'] = $value->gstn;
                        $csv_arr[$key]['Bill Number'] = $value->bill_no;
                        $csv_arr[$key]['Vendor Name'] = $value->contact_display_name;
                        $csv_arr[$key]['Bill date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->bill_date)));
                        $csv_arr[$key]['Bill Value'] = $value->total;
                        $csv_arr[$key]['Place Of Supply'] = $value->shipping_state.'-'.$this->state_array[$value->shipping_state];
                        //$csv_arr[$key]['Reverse Charge'] = 0.00;
                        //$csv_arr[$key]['Bill Type'] = 'Rgular';
                        $csv_arr[$key]['Rate'] = 3;
                        $csv_arr[$key]['Taxable Value'] = ($value->total - $value->sub_total);
                        $csv_arr[$key]['Cess Amount'] = 0.00;
                        $csv_arr[$key]['E-Commerce GSTIN'] = '';
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('purchase_report',$data);
        }
    }

    public function customer_sale_combine($start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        
        $data['combine_sale'] = $this->Reports_model->customer_combine_sale(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
        
        $this->load->view('customer_sales_combine',$data);
    }

    public function customer_sale($customer=0,$start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['data'] = $this->input->get('data'); 
        $data['excel'] = $this->input->get('excel'); 
        $data['customer'] = !empty($customer) ? $customer : ''; 
       
        $where = array('contact_type' => 1);
        $data['customer_list'] = $this->User_model->user_list_where($where);

        // INVOICE SALES 
        $data['report'] = $this->Reports_model->generate_customer_invoice_sales(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))),$data['customer']);
        $data['credit_report'] = $this->Reports_model->get_credit_note_list(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))),$data['customer']);
        
        if (count($data['report']) > 0) {
            foreach ($data['report'] as $key => $value) {
                 if ($value->status == 1) {
                    if (strtotime($value->due_date) < strtotime(date('Y-m-d'))) {
                        if (($value->total - $value->payment) == 0) {
                            $status = "Paid";
                        }else{
                            $status = "Over Due";
                        }
                    } else {
                        if (($value->total - $value->payment) == 0) {
                            $status = "Paid";
                        }else{
                            $status = "Due";
                        }
                    }
                } else {
                    $status = "Draft";
                }
                $data['report'][$key]->status_text = $status;
                $data['report'][$key]->payment = !empty($value->payment) ? $value->payment : 0;
            }
        }

        if (count($data['credit_report']) > 0) {
            foreach ($data['credit_report'] as $key => $value) {
                if ($value->is_adjusted == 1) {
                    $status = "Paid";
                } else {
                    $status = "Due";
                }
                $data['credit_report'][$key]->status_text = $status;
            }
        }

        if (($data['data'] == 'json') && (!empty($data['excel']) && ($data['excel'] ==1))) {
            $csv_arr = array();
            $i = 0;
            if (count($data['report']) > 0) {
                foreach ($data['report'] as $key => $value) {
                    $csv_arr[$i]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                    $csv_arr[$i]['Type'] = 'Invoice';
                    $csv_arr[$i]['ID#'] = $value->invoice_no;
                    $csv_arr[$i]['Order No.'] = $value->order_no;
                    $csv_arr[$i]['Customer'] = $value->name;
                    $csv_arr[$i]['Status'] = $value->status_text;
                    $csv_arr[$i]['Due Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->due_date)));
                    $csv_arr[$i]['Amount'] = number_format((float)$value->sub_total, 2, '.', '');
                    $csv_arr[$i]['Amount With Tax'] = number_format((float)$value->total, 2, '.', '');
                    // $csv_arr[$i]['Balance Due'] = ($value->total - $value->payment);
                    $i++;
                }
            }

            if (count($data['credit_report'])) {
                foreach ($data['credit_report'] as $key => $value) {
                    $csv_arr[$i]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->credit_date)));
                    $csv_arr[$i]['Type'] = 'Credit Note';
                    $csv_arr[$i]['ID#'] = $value->credit_note_no;
                    $csv_arr[$i]['Order No.'] = '';
                    $csv_arr[$i]['Customer'] = $value->name;
                    $csv_arr[$i]['Status'] = $value->status_text;
                    $csv_arr[$i]['Due Date'] = '';
                    $csv_arr[$i]['Amount'] = '-'.number_format((float)$value->sub_total, 2, '.', '');
                    $csv_arr[$i]['Amount With Tax'] = '-'.number_format((float)$value->total, 2, '.', '');
                    // $csv_arr[$i]['Balance Due'] = ($value->total - $value->payment);
                    $i++;
                }
            }
            echo json_encode($csv_arr);
        } else {
            $this->load->view('customer_sales',$data);
        }
    }

    public function item_sales ($item=0,$start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['data'] = $this->input->get('data'); 
        $data['excel'] = $this->input->get('excel'); 
        $data['item'] = !empty($item) ? $item : ''; 

        $data['item_list'] = $this->Item_model->item_list();

        $data['report'] = $this->Reports_model->generate_item_sales(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))),$data['item']);
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice#'] = $value->invoice_no;
                        $csv_arr[$key]['Order No.'] = $value->order_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        // $csv_arr[$key]['Status'] = $status_text;
                        $csv_arr[$key]['Due Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->due_date)));
                        $csv_arr[$key]['Amount'] = $value->total;
                        $csv_arr[$key]['Balance Due'] = ($value->total - $value->payment);
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('item_sales',$data);
        }
    }

    public function customer_balance_details ($customer){
        $data['start_date'] = !empty($this->input->post('from')) ? $this->input->post('from') : $this->start; 
        $data['end_date'] = !empty($this->input->post('to')) ? $this->input->post('to') : $this->end; 
        $data['data'] = $this->input->post('data'); 
        $data['excel'] = $this->input->post('excel'); 
        $data['customer'] = !empty($customer) ? $customer : 0; 

        // $where = array('contact_type' => 1);
        // $data['customer_list'] = $this->User_model->user_list_where($where);

        $data['invoice_report'] = $this->Reports_model->customer_invoice_all($data['customer']);
        
        $data['payment_report'] = $this->Reports_model->customer_payment_all($data['customer']);

        $data['credit_note_report'] = $this->Reports_model->customer_credit_note_all($data['customer']);
        
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice#'] = $value->invoice_no;
                        $csv_arr[$key]['Order No.'] = $value->order_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Status'] = $status_text;
                        $csv_arr[$key]['Due Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->due_date)));
                        $csv_arr[$key]['Amount'] = $value->total;
                        $csv_arr[$key]['Balance Due'] = ($value->total - $value->payment);
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data);
            }
        } else {
            $this->load->view('customer_balance_details',$data);
        }
    }

    public function customer_balance (){
        $data['start_date'] = !empty($this->input->post('from')) ? $this->input->post('from') : $this->start; 
        $data['end_date'] = !empty($this->input->post('to')) ? $this->input->post('to') : $this->end; 
        $data['data'] = $this->input->post('data'); 
        $data['excel'] = $this->input->post('excel'); 
        $data['customer'] = $this->input->post('customer'); 

        $where = array('contact_type' => 1);
        $data['customer_list'] = $this->User_model->user_list_where($where);

        $nonpaid_invoice = array();
        $unused_credit_note = array();
        $recived_payment = array();
        $customer_nonpaid_invoice = $this->Reports_model->customer_nonpaid_invoice();
        
        if (count($customer_nonpaid_invoice) >0) {
            foreach ($customer_nonpaid_invoice as $key => $value) {
                if (empty($value->inv_total)) {
                   continue; 
                }
                $nonpaid_invoice[$value->id] = $value; 
            }
        }

        $customer_unused_credit_note = $this->Reports_model->customer_unused_credit_note();
        if (count($customer_unused_credit_note) >0) {
            foreach ($customer_unused_credit_note as $key => $value) {
                if (empty($value->crdt_total) && empty($value->crdt_used)) {
                       continue; 
                }
                $unused_credit_note[$value->id] = $value; 
            }
        }

        $customer_unused_payment = $this->Reports_model->customer_unused_payment();
        if (count($customer_unused_payment) >0) {
            foreach ($customer_unused_payment as $key => $value) {
                if (empty($value->rcv_amount)) {
                       continue; 
                }
                $recived_payment[$value->id] = $value; 
            }
        }
        
        $data['customer_balance'] = array();
        if (count($data['customer_list'])) {
            foreach ($data['customer_list'] as $key => $value) {
                $data['customer_balance'][$value->id]['name'] = $value->name;
                $data['customer_balance'][$value->id]['nonpaid_invoice'] = isset($nonpaid_invoice[$value->id]) ? $nonpaid_invoice[$value->id]->due_total : 0;
                $data['customer_balance'][$value->id]['unused_credit_note'] = isset($unused_credit_note[$value->id]) ? $unused_credit_note[$value->id]->crdt_total : 0;

                $data['customer_balance'][$value->id]['unused_payment'] = ((isset($nonpaid_invoice[$value->id]) ? $nonpaid_invoice[$value->id]->invoice_paid_total : 0) - ((isset($recived_payment[$value->id]) ? $recived_payment[$value->id]->rcv_amount : 0) + (isset($unused_credit_note[$value->id]) ? $unused_credit_note[$value->id]->crdt_used : 0)));
            }
        }
        $this->load->view('customer_balance',$data);
    }

    public function vendor_balance (){
        $data['start_date'] = !empty($this->input->post('from')) ? $this->input->post('from') : $this->start; 
        $data['end_date'] = !empty($this->input->post('to')) ? $this->input->post('to') : $this->end; 
        $data['data'] = $this->input->post('data'); 
        $data['excel'] = $this->input->post('excel'); 
        $data['customer'] = $this->input->post('customer'); 

        $where = array('contact_type' => 2);
        $data['vendor_list'] = $this->User_model->user_list_where($where);

        $nonpaid_bills = array();
        $unused_debit_note = array();
        $payment_made = array();

        $vendor_nonpaid_bill = $this->Reports_model->vendor_nonpaid_bills();
        if (count($vendor_nonpaid_bill) >0) {
            foreach ($vendor_nonpaid_bill as $key => $value) {
                if (empty($value->bill_total)) {
                   continue; 
                }
                $nonpaid_bills[$value->id] = $value; 
            }
        }
        
        $vendor_unused_debit_note = $this->Reports_model->vendor_unused_dabit_note();
        // echo $this->db->last_query();
        if (count($vendor_unused_debit_note) >0) {
            foreach ($vendor_unused_debit_note as $key => $value) {
                if (empty($value->dbt_total) && empty($value->dbt_used)) {
                       continue; 
                }
                $unused_debit_note[$value->id] = $value; 
            }
        }
        // echo "<pre>";print_r($unused_debit_note);die();
        $vendor_unused_payment = $this->Reports_model->vendor_unused_payment();
        if (count($vendor_unused_payment) >0) {
            foreach ($vendor_unused_payment as $key => $value) {
                if (empty($value->paid_amount)) {
                       continue; 
                }
                $payment_made[$value->id] = $value; 
            }
        }
        
        $data['vendor_balance'] = array();
        if (count($data['vendor_list'])) {
            foreach ($data['vendor_list'] as $key => $value) {
                $data['vendor_balance'][$value->id]['name'] = $value->name;
                $data['vendor_balance'][$value->id]['nonpaid_bills'] = isset($nonpaid_bills[$value->id]) ? $nonpaid_bills[$value->id]->due_total : 0;
                $data['vendor_balance'][$value->id]['unused_dabit_note'] = isset($unused_debit_note[$value->id]) ? $unused_debit_note[$value->id]->dbt_total : 0;

                $data['vendor_balance'][$value->id]['unused_payment'] = ((isset($nonpaid_bills[$value->id]) ? $nonpaid_bills[$value->id]->bill_paid_total : 0) - ((isset($payment_made[$value->id]) ? $payment_made[$value->id]->paid_amount : 0) + (isset($unused_debit_note[$value->id]) ? $unused_debit_note[$value->id]->dbt_used : 0)));
            }
        }
        
        $this->load->view('vendor_balance',$data);
    }

    public function vendor_balance_details ($vendor){
        $data['start_date'] = !empty($this->input->post('from')) ? $this->input->post('from') : $this->start; 
        $data['end_date'] = !empty($this->input->post('to')) ? $this->input->post('to') : $this->end; 
        $data['data'] = $this->input->post('data'); 
        $data['excel'] = $this->input->post('excel'); 
        $data['vendor'] = !empty($vendor) ? $vendor : 0; 

        // $where = array('contact_type' => 1);
        // $data['vendor_list'] = $this->User_model->user_list_where($where);

        $data['bill_report'] = $this->Reports_model->vendor_bill_all($data['vendor']);
        
        $data['payment_report'] = $this->Reports_model->vendor_payment_all($data['vendor']);

        $data['debit_note_report'] = $this->Reports_model->vendor_debit_note_all($data['vendor']);
        
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice#'] = $value->invoice_no;
                        $csv_arr[$key]['Order No.'] = $value->order_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Status'] = $status_text;
                        $csv_arr[$key]['Due Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->due_date)));
                        $csv_arr[$key]['Amount'] = $value->total;
                        $csv_arr[$key]['Balance Due'] = ($value->total - $value->payment);
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data);
            }
        } else {
            $this->load->view('vendor_balance_details',$data);
        }
    }

    public function invoice_details ($start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['data'] = $this->input->get('data'); 
        $data['excel'] = $this->input->get('excel'); 

        $data['report'] = $this->Reports_model->invoice_details(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
        // echo $this->db->last_query();die();
        if (count($data['report']) > 0) {
            foreach ($data['report'] as $key => $value) {
                 if ($value->status == 1) {
                    if (strtotime($value->due_date) < strtotime(date('Y-m-d'))) {
                        if (($value->total - $value->payment) == 0) {
                            $status = "Paid";
                        }else{
                            $status = "Over Due";
                        }
                    } else {
                        if (($value->total - $value->payment) == 0) {
                            $status = "Paid";
                        }else{
                            $status = "Due";
                        }
                    }
                } else {
                    $status = "Draft";
                }
                $data['report'][$key]->status_text = $status;
                // $data['report'][$key]->payment = !empty($value->payment) ? $value->payment : 0;
            }
        }

        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice#'] = $value->invoice_no;
                        $csv_arr[$key]['Order No.'] = $value->order_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Status'] = $value->status_text;
                        $csv_arr[$key]['Due Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->due_date)));
                        $csv_arr[$key]['Amount'] = $value->total;
                        $csv_arr[$key]['Balance Due'] = ($value->total - $value->payment);
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('invoice_details',$data);
        }
    }

    public function bill_details ($start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['data'] = $this->input->get('data'); 
        $data['excel'] = $this->input->get('excel'); 

        $data['report'] = $this->Reports_model->bill_details(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
        // echo "<pre>";print_r($data['report']);die();
        if (count($data['report']) > 0) {
            foreach ($data['report'] as $key => $value) {
                 if ($value->status == 1) {
                    if (strtotime($value->due_date) < strtotime(date('Y-m-d'))) {
                        if (($value->total - $value->payment) == 0) {
                            $status = "Paid";
                        }else{
                            $status = "Over Due";
                        }
                    } else {
                        if (($value->total - $value->payment) == 0) {
                            $status = "Paid";
                        }else{
                            $status = "Due";
                        }
                    }
                } else {
                    $status = "Draft";
                }
                $data['report'][$key]->status_text = $status;
                // $data['report'][$key]->payment = !empty($value->payment) ? $value->payment : 0;
            }
        }

        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice#'] = $value->invoice_no;
                        $csv_arr[$key]['Order No.'] = $value->order_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Status'] = $value->status_text;
                        $csv_arr[$key]['Due Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->due_date)));
                        $csv_arr[$key]['Amount'] = $value->total;
                        $csv_arr[$key]['Balance Due'] = ($value->total - $value->payment);
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('bill_details',$data);
        }
    }

    public function payment_receive_list($customer_id=null,$start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['customer_id'] = !empty($customer_id) ? $customer_id : ''; 
        $data['data'] = $this->input->get('data'); 
        $data['excel'] = $this->input->get('excel'); 

        $where = array('contact_type' => 1);
        $data['customer_list'] = $this->User_model->user_list_where($where);

        $data['report'] = $this->Reports_model->payment_receive_list(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))),$data['customer_id']);
       // echo $this->db->last_query();die();
        
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->payment_date)));
                        $csv_arr[$key]['Referance#'] = $value->reference;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Payment Method'] = ($value->payment_type == 1) ? 'CASH' : 'CHEQUE';
                        $csv_arr[$key]['Note'] = $value->note;
                        $csv_arr[$key]['Invoices'] = !empty($value->invoices) ? $value->invoices : '';
                        $csv_arr[$key]['Amount'] = $value->amount;
                        $csv_arr[$key]['Unused Amount'] = ($value->amount - $value->invoice_paid_amount);
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('report_payment_receive',$data);
        }
    }

    public function credit_note_list($customer_id=null,$start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['customer_id'] = !empty($customer_id) ? $customer_id : '';
        $data['data'] = $this->input->get('data'); 
        $data['excel'] = $this->input->get('excel'); 

        $where = array('contact_type' => 1);
        $data['customer_list'] = $this->User_model->user_list_where($where);

        $data['report'] = $this->Reports_model->credit_note_list(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))),$data['customer_id']);
       // echo $this->db->last_query();die();
        
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->credit_date)));
                        $csv_arr[$key]['Credit No#'] = $value->credit_note_no;
                        $csv_arr[$key]['Invoice'] = $value->invoice_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Status'] = ($value->is_adjusted == 1) ? 'PAID' : 'DUE';
                        $csv_arr[$key]['Amount'] = number_format((float)($value->total), 2, '.', '');
                        $csv_arr[$key]['Unused Amount'] = ($value->is_adjusted == 0) ? number_format((float)($value->total), 2, '.', '') : '0.00';
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('report_credit_note',$data);
        }
    }

    public function debit_note_list($vendor_id=null,$start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['vendor_id'] = !empty($vendor_id) ? $vendor_id : '';
        $data['data'] = $this->input->get('data'); 
        $data['excel'] = $this->input->get('excel'); 

        $where = array('contact_type' => 2);
        $data['vendor_list'] = $this->User_model->user_list_where($where);

        $data['report'] = $this->Reports_model->debit_note_list(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))),$data['vendor_id']);
       // echo $this->db->last_query();die();
        
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->credit_date)));
                        $csv_arr[$key]['Credit No#'] = $value->credit_note_no;
                        $csv_arr[$key]['Invoice'] = $value->invoice_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Status'] = ($value->is_adjusted == 1) ? 'PAID' : 'DUE';
                        $csv_arr[$key]['Amount'] = number_format((float)($value->total), 2, '.', '');
                        $csv_arr[$key]['Unused Amount'] = ($value->is_adjusted == 0) ? number_format((float)($value->total), 2, '.', '') : '0.00';
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('report_debit_note',$data);
        }
    }

    public function expence(){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['data'] = $this->input->get('data'); 
        $data['excel'] = $this->input->get('excel'); 

        $data['report'] = $this->Reports_model->expence_list(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));

        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->credit_date)));
                        $csv_arr[$key]['Credit No#'] = $value->credit_note_no;
                        $csv_arr[$key]['Invoice'] = $value->invoice_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Status'] = ($value->is_adjusted == 1) ? 'PAID' : 'DUE';
                        $csv_arr[$key]['Amount'] = number_format((float)($value->total), 2, '.', '');
                        $csv_arr[$key]['Unused Amount'] = ($value->is_adjusted == 0) ? number_format((float)($value->total), 2, '.', '') : '0.00';
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('report_expence',$data);
        }
    }
    
    
    
     public function item_stock ($item=0,$start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['data'] = $this->input->get('data'); 
        //$data['excel'] = $this->input->get('excel'); 
        //$data['item'] = !empty($item) ? $item : ''; 

      //  $data['item_list'] = $this->Item_model->item_list();

        $data['report'] = $this->Reports_model->item_stock(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
		
		
		//print_r($data['report']);
		//exit();
		
		
        
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->invoice_date)));
                        $csv_arr[$key]['Invoice#'] = $value->invoice_no;
                        $csv_arr[$key]['Order No.'] = $value->order_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        // $csv_arr[$key]['Status'] = $status_text;
                        $csv_arr[$key]['Due Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->due_date)));
                        $csv_arr[$key]['Amount'] = $value->total;
                        $csv_arr[$key]['Balance Due'] = ($value->total - $value->payment);
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('item_stock',$data);
        }
    }
    
    

    public function expence_details($expence_id,$start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        $data['data'] = $expence_id; 
        $data['excel'] = $this->input->get('excel'); 

        $data['report'] = $this->Reports_model->expence_list(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))),$data['data']);
        
        if ($data['data'] == 'json') {
            if (!empty($data['excel']) && ($data['excel'] ==1)) {
                $csv_arr = array();
                if (count($data['report']) > 0) {
                    foreach ($data['report'] as $key => $value) {
                        $csv_arr[$key]['Date'] = date('d/m/Y',strtotime(str_replace('-', '/', $value->credit_date)));
                        $csv_arr[$key]['Credit No#'] = $value->credit_note_no;
                        $csv_arr[$key]['Invoice'] = $value->invoice_no;
                        $csv_arr[$key]['Customer'] = $value->name;
                        $csv_arr[$key]['Status'] = ($value->is_adjusted == 1) ? 'PAID' : 'DUE';
                        $csv_arr[$key]['Amount'] = number_format((float)($value->total), 2, '.', '');
                        $csv_arr[$key]['Unused Amount'] = ($value->is_adjusted == 0) ? number_format((float)($value->total), 2, '.', '') : '0.00';
                    }
                }
                echo json_encode($csv_arr);
            } else {
                echo json_encode($data['report']);
            }
        } else {
            $this->load->view('report_expence_details',$data);
        }
    }
    

    public function metal_stock($start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;

        $data['report'] = $this->Reports_model->metal_stock_report($data['start_date'],$data['end_date']);
        $this->load->view('report_metal_stock',$data);
    }
    public function ston_stock($start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;

        $data['report'] = $this->Reports_model->ston_stock_report($data['start_date'],$data['end_date']);
        $this->load->view('report_ston_stock',$data);
    }

    public function balance_sheet($start=null,$end=null){
        $data['start_date'] = !empty($start) ? date('Y-m-d',strtotime($start)) : $this->start; 
        $data['end_date'] = !empty($end) ? date('Y-m-d',strtotime($end)) : $this->end;

        // $data['opening_balance'] = $this->Reports_model->get_single_record('company_setings',array('setings_id'=>1),'*');
        $opening_balance_arr = $this->Reports_model->get_opening_balance();
        
        if (count($opening_balance_arr) == 0) {
            $opening_balance_arr = $this->Reports_model->get_single_record('company_setings',array('setings_id'=>1),'*');
            $data['opening_balance'] = $opening_balance_arr[0]->opening_balance;
        } else {
            $data['opening_balance'] = $opening_balance_arr->closing_balance;
        }

        $where_purchase = 'bill_date BETWEEN "'.$data['start_date'].'" AND "'.$data['end_date'].'"';
        $data['purchase'] = $this->Reports_model->get_single_record('purchase_bill',$where_purchase,'sum(total) purchase_amount');
        
        $where_debit = 'devid_date BETWEEN "'.$data['start_date'].'" AND "'.$data['end_date'].'"';
        $data['debit_note'] = $this->Reports_model->get_single_record('devid_note',$where_debit,'sum(total) debit_amount');
        
        $where_sale = 'invoice_date BETWEEN "'.$data['start_date'].'" AND "'.$data['end_date'].'"';
        $data['sales'] = $this->Reports_model->get_single_record('sale_invoice',$where_sale,'sum(total) sale_amount');
        
        $where_credit = 'credit_date BETWEEN "'.$data['start_date'].'" AND "'.$data['end_date'].'"';
        $data['credit_note'] = $this->Reports_model->get_single_record('credit_note',$where_credit,'sum(total) credit_amount');
        
        $data['closing_stock_details'] = $this->Reports_model->get_closing_stock($data['start_date'],$data['end_date']);

        $data['expences'] = $this->Reports_model->expence_list($data['start_date'],$data['end_date']);
        // echo $this->db->last_query();die();
        // echo "<pre>";print_r($data);die();
        $this->load->view('report_balance_sheet',$data);
    }

    //OPENING AND CLOSING BALANCE
    public function balance_sheet_open_close_cron($start=null,$end=null){
        $date = new DateTime();
        $date->modify("first day of last month");
        $start_date = !empty($start) ? $start : $date->format("Y-m-d");
        $date->modify("last day of previous month");
        $end_date = !empty($end) ? $end : $date->format("Y-m-d");

        $opening_balance_arr = $this->Reports_model->get_opening_balance();
        if (count($opening_balance_arr) == 0) {
            $opening_balance_arr = $this->Reports_model->get_single_record('company_setings',array('setings_id'=>1),'*');
            $opening_balance = $opening_balance_arr[0]->opening_balance;
        } else {
            $opening_balance = $opening_balance_arr->closing_balance;
        }
        
        $where_purchase = 'bill_date BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
        $purchase = $this->Reports_model->get_single_record('purchase_bill',$where_purchase,'sum(total) purchase_amount');
        
        $where_debit = 'devid_date BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
        $debit_note = $this->Reports_model->get_single_record('devid_note',$where_debit,'sum(total) debit_amount');
        
        $where_sale = 'invoice_date BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
        $sales = $this->Reports_model->get_single_record('sale_invoice',$where_sale,'sum(total) sale_amount');
        
        $where_credit = 'credit_date BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
        $credit_note = $this->Reports_model->get_single_record('credit_note',$where_credit,'sum(total) credit_amount');
        
        $closing_stock_details = $this->Reports_model->get_closing_stock($start_date,$end_date);
        $closing_amount=$opening_balance;
        if (count($closing_stock_details) > 0) {
            foreach ($closing_stock_details as $key => $value) {
                $closing_amount += (($value->buy - $value->sale) * $value->rate_purchase);
            }
        }

        $left_side = ($opening_balance + $purchase[0]->purchase_amount - $debit_note[0]->debit_amount);
        $right_side = ($sales[0]->sale_amount -$credit_note[0]->credit_amount + $closing_amount);

        // $outstanding = ($left_side - $right_side);

        $data['month'] = date('m',strtotime($start_date));
        $data['year'] = date('Y',strtotime($end_date));
        $data['opening_balance'] = $opening_balance;
        $data['closing_balance'] = $closing_amount;
        $data['date_added'] = date('Y-m-d');
        return $closing_bal_id = $this->Reports_model->insert_data('opening_closing_balance_month',$data);
        // $expences = $this->Reports_model->expence_list($start_date,$end_date);
    }

    public function bank_accounts($account_id=0,$start=null,$end=null){
        $data['account_id'] = $account_id; 
        $data['start_date'] = !empty($start) ? date('Y-m-d',strtotime($start)) : $this->start; 
        $data['end_date'] = !empty($end) ? date('Y-m-d',strtotime($end)) : $this->end;
        $data['bank_accounts'] = $this->Reports_model->get_data('bank_accounts','account_id > 0');
        $data['report'] = $this->Reports_model->bank_report_summery($data['account_id'],$data['start_date'],$data['end_date']);
        // echo $this->db->last_query();
        // echo "<pre>";print_r($data['report']);die();
        $this->load->view('report_bank_transaction',$data);
    }

    public function production_expence($start=null,$end=null){
        $data['start_date'] = !empty($start) ? $start : $this->start; 
        $data['end_date'] = !empty($end) ? $end : $this->end;
        
        $data['expence'] = $this->Reports_model->production_expence(date('Y-m-d',strtotime(str_replace('/', '-', $data['start_date']))),date('Y-m-d',strtotime(str_replace('/', '-', $data['end_date']))));
        
        $this->load->view('report_production_expence',$data);
    }


}?>