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

class Invoice extends CI_Controller {
    
    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->load->model('User_model');
        $this->load->model('Item_model');
        $this->load->model('Invoice_model');
        $this->load->model('Setings_model');
    }

    public function index(){
        $data['invoice_list'] = $this->Invoice_model->invoice_list();
        $this->load->view('invoice_list',$data);
    }

    public function newinvoice(){
        $data['invoice_id'] = !empty($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        if (!empty($data['invoice_id'])) {
            $invoice_details = $this->Invoice_model->get_from_table('sale_invoice','*',array('invoice_no' => $data['invoice_id']));
            $data['invoice_data'] = (array)$invoice_details[0];
            $data['item_details'] = $this->Invoice_model->get_from_table('invoice_item_detail','*',array('sale_invoice_id' => $data['invoice_data']['sale_invoice_id']));
            $data['customer_details'] = $this->User_model->get_user_data($data['invoice_data']['customer_id']);
        } else {
            $data['invoice_id'] = $this->invoice_id();
        }
        $where = array('contact_type' => 1,'status' => 1);
        $data['customer_list'] = $this->User_model->user_list_where($where);
        $data['item_list'] = $this->Item_model->get_items();
        $item_gst = array();
        $item_sale_price = array();
        $item_uom = array();
        $item_hsn = array();
        $items_autocomplete = array();
        $items_barcode = array();
        if (count($data['item_list'])>0) {
            foreach ($data['item_list'] as $key => $value) {
                $items_autocomplete[$key] = new stdClass();
                $items_autocomplete[$key]->id = $value->item_id;
                $items_autocomplete[$key]->name = $value->item_name;

                $items_barcode[$value->item_no] = $value;

                $item_hsn[$value->item_id]=$value->hsn_code;
                $item_gst[$value->item_id]=$value->gst_rate;
                $item_sale_price[$value->item_id]=$value->rate_sale;
                $item_uom[$value->item_id]=$value->unit;
            }
        }
        $data['items_autocomplete'] = json_encode($items_autocomplete);
        $data['items_barcode'] = json_encode($items_barcode);
        $data['item_hsn'] = json_encode($item_hsn);
        $data['item_gst'] = json_encode($item_gst);
        $data['item_sale_price'] = json_encode($item_sale_price);
        $data['item_uom'] = json_encode($item_uom);

        $this->load->view('invoice_create',$data);
    }

    public function invoice_id(){
        $last_id = $this->Invoice_model->get_from_table('sale_invoice','max(sale_invoice_id) lastId','sale_invoice_id > 0');
        $invoice_id = 'S-21-22-'.sprintf('%06d', ($last_id[0]->lastId-128)); 
        $check_invoice = $this->Invoice_model->get_from_table("sale_invoice","*","invoice_no ='".$invoice_id."'");
        
        if (count($check_invoice) == 0) {
            return $invoice_id;
        } else {
            return 'S-21-22-'.sprintf('%06d', ($last_id[0]->lastId-127));
        }
    }
    
   /* public function invoice_id(){
        $last_id = $this->Invoice_model->get_from_table('sale_invoice','max(sale_invoice_id) lastId','sale_invoice_id > 0');
        $invoice_id = 'S-19-20-'.sprintf('%06d', ($last_id[0]->lastId-73)); 
        $check_invoice = $this->Invoice_model->get_from_table("sale_invoice","*","invoice_no ='".$invoice_id."'");
        
        if (count($check_invoice) == 0) {
            return $invoice_id;
        } else {
            return 'S-19-20-'.sprintf('%06d', ($last_id[0]->lastId-72));
        }
    } */

    public function generate_invoice(){
        $form_data = $this->input->post('invoice_basic');
        $sum_amounts = $this->input->post('items_tot');
        $item_data = $this->input->post('items');
        $userState = $this->input->post('userState');
        $status = $this->input->post('status');

        $data['invoice_data'] = array(
                'invoice_no'    => $form_data[1]['value'],
                'customer_id'   => $form_data[0]['value'],
                'order_no'      => $form_data[2]['value'],
                'invoice_date'  => date('Y-m-d',strtotime(str_replace('/', '-', $form_data[3]['value']))),
                'due_date'      => date('Y-m-d',strtotime(str_replace('/', '-', $form_data[4]['value']))),
                'total'         => $sum_amounts['final_total'],
                'sub_total'     => $sum_amounts['sub_total'],
                'cgst_total'    => $sum_amounts['cgst'],
                'sgst_total'    => $sum_amounts['sgst'],
                'igst_total'    => $sum_amounts['igst'],
                'status'        => $status,
                'date_added'    => date('Y-m-d')
            );
        $check_invoice = $this->Invoice_model->get_from_table('sale_invoice','*',array('invoice_no' => $form_data[1]['value']));
        if (count($check_invoice) > 0) {
            $sale_invoice_id =  $check_invoice[0]->sale_invoice_id;
            $this->Invoice_model->update_data('sale_invoice',$data['invoice_data'],array('invoice_no' => $form_data[1]['value'],'sale_invoice_id' => $sale_invoice_id));
        } else {
            $sale_invoice_id = $this->Invoice_model->insert_data('sale_invoice',$data['invoice_data']);    
        }

        if (count($item_data) > 0) {
            $stock_items = array();
            foreach ($item_data as $key => $value) {
                if ($value['item_name'] != '') {
                    $item_details[] = array(
                        'sale_invoice_id'   => $sale_invoice_id,
                        'item_id'           => $value['item_id'],
                        'item'              => $value['item_name'],
                        'hsn_code'          => $value['hsn_code'],
                        'gst_rate'          => $value['item_gst'],
                        'qty'               => $value['quantity'],
                        'uom'               => $value['uom'],
                        'rate'              => $value['unit_price'],
                        'discount'          => $value['discount'],
                        'amount'            => $value['price'],
                        'cgst'              => (($userState == 19) ? (((($value['quantity'] * $value['unit_price'])-((($value['quantity'] * $value['unit_price'])*$value['discount'])/100)) * ($value['item_gst']/2)) / 100) : 0),
                        'sgst'              => (($userState == 19) ? (((($value['quantity'] * $value['unit_price'])-((($value['quantity'] * $value['unit_price'])*$value['discount'])/100)) * ($value['item_gst']/2)) / 100) : 0),
                        'igst'              => (($userState != 19) ? (((($value['quantity'] * $value['unit_price'])-((($value['quantity'] * $value['unit_price'])*$value['discount'])/100)) * $value['item_gst']) / 100) : 0)
                    );

                    if ($value['item_id'] > 0) {
                        $stock_items[]= array(
                            'item_id'       => $value['item_id'],
                            'qty_sale'      => $value['quantity'],
                            'qty_purchase'  => 0,
                            'inv_bill_id'   => $sale_invoice_id,
                            'date_added'    => date('Y-m-d'),
                            'is_note'       => 1
                        );
                    }
                }
            }

            // $data['customer_details'] = $this->User_model->get_user_data($form_data[0]['value']);
            // $data['item_details'] = $item_details;
            if (count($check_invoice) > 0) {
                $sale_invoice_id =  $check_invoice[0]->sale_invoice_id;
                $this->Invoice_model->delete_data('invoice_item_detail',array('sale_invoice_id' => $sale_invoice_id));
                $this->Invoice_model->delete_data('item_stock',array('inv_bill_id' => $sale_invoice_id,'is_note' =>1));
            }
            $this->Invoice_model->insert_data_batch('invoice_item_detail',$item_details);
            if (count($stock_items) > 0) {
                $this->Invoice_model->insert_data_batch('item_stock',$stock_items);
            }
        }

        echo $form_data[1]['value'];
    }

    public function invoice_print($key_invoice){
        $data['setings'] = $this->Setings_model->get_setings();
        $data['invoice_id'] = $key_invoice;
        $invoice_details = $this->Invoice_model->get_from_table('sale_invoice','*',array('invoice_no' => $data['invoice_id']));
        $data['invoice_data'] = (array)$invoice_details[0];
        $data['item_details'] = $this->Invoice_model->get_from_table('invoice_item_detail','*',array('sale_invoice_id' => $data['invoice_data']['sale_invoice_id']));
        $data['payment_done'] = $this->Invoice_model->get_from_table('invoice_payment','*',array('sale_invoice_id' => $data['invoice_data']['sale_invoice_id']));

        $data['is_editable'] = (count($data['payment_done']) > 0) ? FALSE : TRUE;
        // $data['item_details'] = $this->Invoice_model->get_invoice_item_details(array('sale_invoice_id' => $data['invoice_data']['sale_invoice_id']));
        $data['customer_details'] = $this->User_model->get_user_data($data['invoice_data']['customer_id']);
        $this->load->view('invoice_print',$data);
    }
}
?>