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

class All_products extends CI_Controller {
    
    public function __construct() {
        parent::__construct();

        $this->load->helper('url');        
        $this->load->library("pagination");


         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');
        $this->load->model('Product_model');
    }

    public function index($start=null){

        $config = array();
        $config["base_url"] = base_url() . "all_products/index/";
        $config["total_rows"] = 250;
        $config["per_page"] = 50;
        $config["uri_segment"] = 3;

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        
        $data["links"] = $this->pagination->create_links();



        $data['invoice_list'] = $this->Product_model->product_list( $page );
        $this->load->view('invoice_list',$data);

    }

    public function newproduct(){
        
        // $where = array('contact_type' => 1,'status' => 1);
        $data['vendor_list'] = $this->Product_model->get_vendor();
        $data['category_list'] = $this->Product_model->category_list();     
        
        //echo "<pre>";
        //print_r($data);

        $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-20-21-'.sprintf('%06d', ($last_id[0]->lastId-119)); 
        $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-20-21-'.sprintf('%06d', ($last_id[0]->lastId-118));
        }
    }
    
   /* 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);
    }
}
?>