<?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');
        $this->load->model('Color_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['vendor_list'] = $this->Product_model->get_vendor();
//        $data['invoice_list'] = $this->Product_model->product_list($page);
        $this->load->view('invoice_list', $data);
    }

    public function invoice_list_1($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['vendor_list'] = $this->Product_model->get_vendor();
//        $data['invoice_list'] = $this->Product_model->product_list($page);
        $this->load->view('invoice_list_1', $data);
    }

    public function product_data() {
        $dat = $this->uri->segment(3);
        $staus = $this->uri->segment(4);
       $draw = intval($this->input->get('draw'));
       $row = intval($this->input->get('start'));
       $page = intval($this->input->get('length'));


        $product = $this->Color_model->getAllProductData($row,$page,$dat,$draw,$staus);   
        $count = $this->Color_model->countProductData($dat,$staus);   
      $datacount=0;
      $data=array();
        if (!empty($product)) {
            $datacount=$count->id_count;
            foreach ($product->result() as $res) {

                $action = '<a href="' . site_url("all_products/edit/" . $res->id) . '"><button class="btn btn-info btn-xs"><i class="fa fa-edit"></i></button></a>
                &nbsp;<a href="' . site_url("all_products/attributesEdit/" . $res->id) . '"><button class="btn btn-primary btn-xs"><i class="fa fa-edit"></i></button></a>';




                $data[] = array(
                    $res->name,                  
                    substr(!empty($res->photo_id) ? $res->photo_id : '', 0, 100),
                    $res->vendor!='' ? $res->vendor : '',
                    $res->color!='' ? $res->color : '',
                    $res->delivered!='' ? $res->delivered : '',
                    $res->made_in!='' ? $res->made_in : '',
                    $action
                );
            }
        }

        $result = array(
            "draw" => $draw,
            "recordsTotal" => $datacount,
            "recordsFiltered" => $datacount,
            "data" => $data
        );       
        echo json_encode($result);
        exit();
    }

    public function product_data_by_photo_id() {
        $photo_id = $this->uri->segment(3);
        
       $draw = intval($this->input->get('draw'));
       $row = intval($this->input->get('start'));
       $page = intval($this->input->get('length'));
       $product = $this->Color_model->getAllProductDataByPhotoId($row,$page,$photo_id,$draw);   
       $count = $this->Color_model->countProductDataByPhotoId($photo_id);   
      $datacount=0;
      $data=array();
        if (!empty($product)) {
            $datacount=$count->id_count;
            foreach ($product->result() as $res) {

                $action = '<a href="' . site_url("all_products/edit/" . $res->id) . '"><button class="btn btn-info btn-xs"><i class="fa fa-edit"></i></button></a>
                &nbsp;<a href="' . site_url("all_products/attributesEdit/" . $res->id) . '"><button class="btn btn-primary btn-xs"><i class="fa fa-edit"></i></button></a>';



                $data[] = array(
                    $res->name,                  
                    substr(!empty($res->photo_id) ? $res->photo_id : '', 0, 100),
                    $res->vendor!='' ? $res->vendor : '',
                    $res->color!='' ? $res->color : '',
                    $res->delivered!='' ? $res->delivered : '',
                    $res->made_in!='' ? $res->made_in : '',
                    $action
                );
            }
        }

        $result = array(
            "draw" => $draw,
            "recordsTotal" => $datacount,
            "recordsFiltered" => $datacount,
            "data" => $data
        );       
        echo json_encode($result);
        exit();
    }

    public function attributesEdit($id){
        if ($this->input->method(TRUE) == 'POST') {
            $group=$this->input->post('group');
            $value=$this->input->post('value');
            $name=$this->input->post('name');
            $total_group=count($this->input->post('group'));
            $total_value=count($this->input->post('value'));
            $total_name=count($this->input->post('name'));
            
            $productId=$this->input->post('product_id');
            $new_array=[];
            for($i=0;$i<$total_group;$i++){
               $new_array[$i]=array(
                "group"=>$group[$i],
                "value"=> $value[$i],
                 "name"=>$name[$i]
                ); 
            }
            $attributes=json_encode($new_array);
            $insertArr = array(
                'attributes'=>$attributes,
                'last_update'=>date("Y-m-d,h:m:s")
            );
            
            $updateRow = $this->Product_model->update_data('rugs_tmp', $insertArr, array('id' => $productId));
            $this->session->set_flashdata('message', 'Attributes Updates successfully!');
            redirect("/all_products");
         }
        $data['attributes']= $this->Color_model->getAllattributes("rugs_tmp", array('id' =>$id));
        $data['productId']= $id;
        $this->load->view('attributesEdit', $data);
        
    }

    public function newimage() {


        if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != NULL) {
            // $small_photo  = $this->upload_photo('productimage',  $this->input->post('photo_id').'_small');
            //$medium_photo = $this->upload_photo('productimage', $this->input->post('photo_id').'_medium');
            $large_photo = $this->upload_photo('file', rand(1111, 9999) . '_large');
        }
    }

    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();
        $data['size_drop'] = $this->Color_model->AllRecordWithWhere("search_sizes", array('id!=' => ''));
        $data['color_drop'] = $this->Color_model->AllRecordWithWhere("color", array('status' => '1'));
        $data['qualities_drop'] = $this->Color_model->AllRecordWithWhere("rugs_qualities", array('status' => '1'));
        $data['shape_drop'] = $this->Color_model->AllRecordWithWhere("rugs_shape", array('status' => '1'));

//        echo "<pre>";
//        print_r($data['size_drop']->result());

        if ($this->input->method(TRUE) == 'POST') {
            //print_r($_POST);die();
            $gs1 = $this->input->post('gs1');
            $msrp = $this->input->post('msrp');
            $length = $this->input->post('length');
            $width = $this->input->post('width');
            $height = $this->input->post('height');
            $price = $this->input->post('price');
            $cost = $this->input->post('cost');
            $size = $this->input->post('size');
            $shape = $this->input->post('shape');
            $stock = $this->input->post('stock');
            $shippingHeight = $this->input->post('shippingHeight');
            $shippingLength = $this->input->post('shippingLength');
            $shippingWidth = $this->input->post('shippingWidth');
            $add_name = $this->input->post('add_name');
            $add_val = $this->input->post('add_val');
            $show_front = $this->input->post('show_front');
            $show_back = $this->input->post('show_back');



            $variations = array();
            $incId = 0;
            foreach ($gs1 as $key => $value) {
                $incId++;
                $variations[] = array(
                    'GS1' => $value,
                    'MSRP' => $msrp[$key],
                    'length' => $length[$key],
                    'width' => $width[$key],
                    'height' => $height[$key],
                    'price' => $price[$key],
                    'cost' => $cost[$key],
                    'size' => $size[$key],
                    'shape' => $shape[$key],
                    'searchSize' => $size[$key],
                    'searchSizeFloor' => $size[$key],
                    'aliasSize' => $size[$key],
                    'option' => $incId,
                    'active' => 1,
                    'stock' => $stock[$key],
                    'shippingHeight' => $shippingHeight[$key],
                    'shippingLength' => $shippingLength[$key],
                    'shippingWidth' => $shippingWidth[$key],
                );
            }



            $variationsJson = json_encode($variations);

            $category = $this->Product_model->category(array('id' => $this->input->post('category')));
            $vendor = $this->Product_model->get_vendor(array('id' => $this->input->post('vendor')));

            //==========3 image upload===========
            $small_photo = $medium_photo = $large_photo = '';
            if (isset($_FILES['productimage']['name']) && $_FILES['productimage']['name'] != NULL) {
                $small_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_small');
                $medium_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_medium');
                $large_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_large');
            }

            //print_r($small_photo);die();
            //==========3 image upload===========
            //==========CREATE ADDITIONAL DATA===========

            $additional_attributes = array();
            foreach ($add_name as $key => $value) {
                $additional_attributes[] = array(
                    'title' => $value,
                    'value' => $add_val[$key],
                    'visibleAdmin' => $show_back[$key],
                    'visibleFront' => $show_front[$key],
                );
            }

            $additional_attributesjson = json_encode($additional_attributes);
            //==========CREATE ADDITIONAL DATA===========

            $insertArr = array(
                'name' => $this->input->post('name'),
                '_vendor' => $this->input->post('vendor'),
                'vendor' => $vendor[0]->vendor_name,
                '_category' => $this->input->post('category'),
                'category' => $category[0]->name,
                'photo_id' => $this->input->post('photo_id'),
                'isResidential' => "1",
                'attribute_set' => "Rugs",
                'description' => $this->input->post('description'),
                'color' => $this->input->post('color'),
                'material' => $this->input->post('material'),
                'backing' => $this->input->post('backing'),
                'quality' => $this->input->post('quality'),
                'keyword_additions' => $this->input->post('keyword_additions'),
                'variations' => $variationsJson,
                'thumb_pic' => '/rug_images/' . $small_photo,
                'picture' => '/rug_images/' . $medium_photo,
                'large_pic' => '/rug_images/' . $large_photo,
                'additional_attributes' => $additional_attributesjson,
            );
            //echo '<pre>';
            //print_r($insertArr);die();

            $insertRow = $this->Product_model->insert_data('rugs_tmp', $insertArr);

            if ($insertRow) {
                $this->session->set_flashdata('message', 'Product added successfully!');
                redirect("all_products");
            }
        }

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

    public function edit($id) {
        //echo $id;die();
        // $where = array('contact_type' => 1,'status' => 1);
        $data['vendor_list'] = $this->Product_model->get_vendor();
        $data['category_list'] = $this->Product_model->category_list();
        $data['size_drop'] = $this->Color_model->AllRecordWithWhere("search_sizes", array('id!=' => ''));
        // $data['color_drop'] = $this->Color_model->AllRecordWithWhere("color", array('status' => '1'));
        $product = $data['product'] = $this->Product_model->product(array('id' => $id));
        //$data['qualities_drop'] = $this->Color_model->AllRecordWithWhere("rugs_qualities", array('status' => '1'));
        //$data['shape_drop'] = $this->Color_model->AllRecordWithWhere("rugs_shape", array('status' => '1'));
        //echo "<pre>";
        //print_r($data['product_data']);die();

        if ($this->input->method(TRUE) == 'POST') {
            //print_r($_POST);die();
            /* $gs1 = $this->input->post('gs1');            
            $msrp = $this->input->post('msrp');
            $length = $this->input->post('length');
            $width = $this->input->post('width');
            $height = $this->input->post('height');            
            $cost = $this->input->post('cost');
            $size = $this->input->post('size');
            $shape = $this->input->post('shape');
            $stock = $this->input->post('stock');
            $shippingHeight = $this->input->post('shippingHeight');
            $shippingLength = $this->input->post('shippingLength');
            $shippingWidth = $this->input->post('shippingWidth');
            $add_name = $this->input->post('add_name');
            $add_val = $this->input->post('add_val'); */

            $price = $this->input->post('price');
            $sizesku = $this->input->post('sizesku');
            $active_status = $this->input->post('active_status');
            $new_arrival = $this->input->post('new_arrival');


            $variations = json_decode($product->variations);

            if ($variations) {
                foreach ($variations as $vkey => $value) {

                   if($value->sizeSku == $sizesku[$vkey])
                   {
                        $value->price = (int)$price[$vkey];
                        $value->active = (int)$active_status[$vkey];

                        $variations[$vkey] = $value;
                   }
                    
                }
            }  
            
            $variationsJson = json_encode($variations);

           // echo "<pre>";
           // print_r($variations);
           // exit();

            /*
            $variations = array();
            $incId = 0;
            foreach ($gs1 as $key => $value) {
                $incId++;
                $variations[] = array(
                    'GS1' => $value,
                    'MSRP' => $msrp[$key],
                    'length' => $length[$key],
                    'width' => $width[$key],
                    'height' => $height[$key],
                    'price' => $price[$key],
                    'cost' => $cost[$key],
                    'size' => $size[$key],
                    'shape' => $shape[$key],
                    'stock' => $stock[$key],
                    'searchSize' => $size[$key],
                    'searchSizeFloor' => $size[$key],
                    'aliasSize' => $size[$key],
                    'option' => $incId,
                    'active' => 1,
                    'shippingHeight' => $shippingHeight[$key],
                    'shippingLength' => $shippingLength[$key],
                    'shippingWidth' => $shippingWidth[$key],
                );
            }

            $variationsJson = json_encode($variations);

            $category = $this->Product_model->category(array('id' => $this->input->post('category')));
            $vendor = $this->Product_model->get_vendor(array('id' => $this->input->post('vendor')));

            //==========3 image upload===========

            if (isset($_FILES['productimage']['name']) && $_FILES['productimage']['name'] != NULL) {

                if ($data['product']->thumb_pic && file_exists('rug_images/' . str_replace('/rug_images/', '', $data['product']->thumb_pic))) {
                    unlink('rug_images/' . str_replace('/rug_images/', '', $data['product']->thumb_pic));
                }
                if ($data['product']->picture && file_exists('rug_images/' . str_replace('/rug_images/', '', $data['product']->picture))) {
                    unlink('rug_images/' . str_replace('/rug_images/', '', $data['product']->picture));
                }
                if ($data['product']->large_pic && file_exists('rug_images/' . str_replace('/rug_images/', '', $data['product']->large_pic))) {
                    unlink('rug_images/' . str_replace('/rug_images/', '', $data['product']->large_pic));
                }


                $small_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_small');
                $medium_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_medium');
                $large_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_large');

                $small_photo = '/rug_images/' . $small_photo;
                $medium_photo = '/rug_images/' . $medium_photo;
                $large_photo = '/rug_images/' . $large_photo;
            } else {
                $small_photo = ($data['product']->thumb_pic ? $data['product']->thumb_pic : '');
                $medium_photo = ($data['product']->picture ? $data['product']->picture : '');
                $large_photo = ($data['product']->large_pic ? $data['product']->large_pic : '');
            }

            //print_r($small_photo);die();
            //==========3 image upload===========
            //==========CREATE ADDITIONAL DATA===========

            $additional_attributes = array();
            foreach ($add_name as $key => $value) {
                $additional_attributes[] = array(
                    'title' => $value,
                    'value' => $add_val[$key],
                );
            }
            $additional_attributesjson = json_encode($additional_attributes);
            //==========CREATE ADDITIONAL DATA===========

            */


            $insertArr = array(
                'new_arrival' => $this->input->post('new_arrival'),              
                'variations' => $variationsJson,                
            );

            $updateRow = $this->Product_model->update_data('rugs_tmp', $insertArr, array('id' => $id));

            //if ($updateRow) {
                $this->session->set_flashdata('message', 'Product updated successfully!');
                redirect("all_products");
            // }
        }

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

    public function copy($id) {
        //echo $id;die();
        // $where = array('contact_type' => 1,'status' => 1);
        $data['vendor_list'] = $this->Product_model->get_vendor();
        $data['category_list'] = $this->Product_model->category_list();
        $data['size_drop'] = $this->Color_model->AllRecordWithWhere("search_sizes", array('id!=' => ''));
        $data['color_drop'] = $this->Color_model->AllRecordWithWhere("color", array('status' => '1'));
        $data['product'] = $this->Product_model->product(array('id' => $id));
        $data['qualities_drop'] = $this->Color_model->AllRecordWithWhere("rugs_qualities", array('status' => '1'));
        $data['shape_drop'] = $this->Color_model->AllRecordWithWhere("rugs_shape", array('status' => '1'));


        if ($this->input->method(TRUE) == 'POST') {
            //print_r($_POST);die();
            $gs1 = $this->input->post('gs1');
            $msrp = $this->input->post('msrp');
            $length = $this->input->post('length');
            $width = $this->input->post('width');
            $height = $this->input->post('height');
            $price = $this->input->post('price');
            $cost = $this->input->post('cost');
            $size = $this->input->post('size');
            $shape = $this->input->post('shape');
            $stock = $this->input->post('stock');
            $shippingHeight = $this->input->post('shippingHeight');
            $shippingLength = $this->input->post('shippingLength');
            $shippingWidth = $this->input->post('shippingWidth');
            $add_name = $this->input->post('add_name');
            $add_val = $this->input->post('add_val');

            $variations = array();
            $incId = 0;
            foreach ($gs1 as $key => $value) {
                $incId++;
                $variations[] = array(
                    'GS1' => $value,
                    'MSRP' => $msrp[$key],
                    'length' => $length[$key],
                    'width' => $width[$key],
                    'height' => $height[$key],
                    'price' => $price[$key],
                    'cost' => $cost[$key],
                    'size' => $size[$key],
                    'shape' => $shape[$key],
                    'stock' => $stock[$key],
                    'searchSize' => $size[$key],
                    'searchSizeFloor' => $size[$key],
                    'aliasSize' => $size[$key],
                    'option' => $incId,
                    'active' => 1,
                    'shippingHeight' => $shippingHeight[$key],
                    'shippingLength' => $shippingLength[$key],
                    'shippingWidth' => $shippingWidth[$key],
                );
            }

            $variationsJson = json_encode($variations);

            $category = $this->Product_model->category(array('id' => $this->input->post('category')));
            $vendor = $this->Product_model->get_vendor(array('id' => $this->input->post('vendor')));

            //==========3 image upload===========
            $small_photo = $medium_photo = $large_photo = '';
            if (isset($_FILES['productimage']['name']) && $_FILES['productimage']['name'] != NULL) {
                $small_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_small');
                $medium_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_medium');
                $large_photo = $this->upload_photo('productimage', $this->input->post('photo_id') . '_large');
            }

            //print_r($small_photo);die();
            //==========3 image upload===========
            //==========CREATE ADDITIONAL DATA===========

            $additional_attributes = array();
            foreach ($add_name as $key => $value) {
                $additional_attributes[] = array(
                    'title' => $value,
                    'value' => $add_val[$key],
                );
            }
            $additional_attributesjson = json_encode($additional_attributes);
            //==========CREATE ADDITIONAL DATA===========

            $insertArr = array(
                'name' => $this->input->post('name'),
                '_vendor' => $this->input->post('vendor'),
                'vendor' => $vendor[0]->vendor_name,
                '_category' => $this->input->post('category'),
                'category' => $category[0]->name,
                'photo_id' => $this->input->post('photo_id'),
                'isResidential' => "1",
                'attribute_set' => "Rugs",
                'description' => $this->input->post('description'),
                'color' => $this->input->post('color'),
                'material' => $this->input->post('material'),
                'backing' => $this->input->post('backing'),
                'quality' => $this->input->post('quality'),
                'keyword_additions' => $this->input->post('keyword_additions'),
                'variations' => $variationsJson,
                'thumb_pic' => $small_photo != '' ? '/rug_images/' . $small_photo : $this->input->post('smallimg'),
                'picture' => $medium_photo != '' ? '/rug_images/' . $medium_photo : $this->input->post('medimg'),
                'large_pic' => $large_photo != '' ? '/rug_images/' . $large_photo : $this->input->post('largeimg'),
                'additional_attributes' => $additional_attributesjson,
            );
            //echo '<pre>';
            //print_r($insertArr);die();

            $insertRow = $this->Product_model->insert_data('rugs_tmp', $insertArr);

            if ($insertRow) {
                $this->session->set_flashdata('message', 'Product added successfully!');
                redirect("all_products");
            }
        }

        $this->load->view('invoice_copy', $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);
    }

    private function upload_photo($field_name, $filename) {
        //echo $field_name.'=='.$filename;die();
        $this->load->library('upload');

        $config['upload_path'] = 'rug_images/';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '10240';
        //$config['max_width']  = '1024';
        //$config['max_height']  = '768';
        $config['file_name'] = $filename;

        $this->upload->initialize($config);
        //$this->load->library('upload', $config);

        if (!$this->upload->do_upload($field_name)) {
            return $error = array('error' => $this->upload->display_errors());
        } else {
            $upload = $this->upload->data();
            return $upload['file_name'];
        }
    }

}

?>