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

class Products extends CI_Controller {

    var $main_menu_name = "products";
	var $sub_menu_name = "products";

    public function __construct()
     {
            parent::__construct();
            $this->load->model('category_models');
            $this->load->model('product_models');
			$this->load->model('common_model');
			$this->load->model('Sales_Model');
			$this->load->model('Transfer_Model');
			$this->load->model('Purchases_Model');
		$this->load->model('Product_Damage_Model');
		$this->load->model('Sales_Return_Model');
			
			

     }

    public function index()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['main_category'] 	= $this->category_models->getCategory();
		$this->load->view('products',$data);
	}
	

public function get_next_prodcut_code(){
		$prodcut_code=$this->common_model->gen_ref_number('product_id','product','PD');
		//$result = $query->row();
		//print_r($result);
		//$sale_reference_no=sprintf("%05d", $result->sale_id+1);
		//$sale_reference_no=$sale_reference_no;
		echo json_encode(array('prodcut_code'=>$prodcut_code));
	}
		

    public function save_new_sub_category()
    {
        $new_sub_category = $this->input->get('new_sub_category');
		 $cat_id= $this->input->get('cat_id');
           if($this->category_models->category_sub_save($cat_id,'',$new_sub_category)) {
					$cat_id=$this->db->insert_id();
                   $st = array('status' =>1,'validation' =>'Done!','cat_id' =>$cat_id,'cat_name'=>$new_sub_category);
                   echo json_encode($st);

           }else {

                   $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                   echo json_encode($st);
           }
        
    }
		
	public function save_new_category(){
        $new_cat_name = $this->input->get('new_cat_name');
        if ($this->category_models->category_save('', $new_cat_name,NULL,NULL)) {

$cat_id=$this->db->insert_id();
                       $st = array('status' =>1,'validation' =>'Done!','cat_id' =>$cat_id,'cat_name'=>$new_cat_name);
                       echo json_encode($st);

               } else {

                       $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                       echo json_encode($st);
               }
    }
	
	public function get_search_product(){
        $str = $this->input->get('search_string');
        $result = $this->product_models->get_search_product($str);
        echo json_encode($result);
    }
	
	public function create_product_code($cat_id){
		$cat_id=$this->uri->segment(3);
		$sn_data=array();
		//echo "sn:".$sn;
		{
		$sn_data = $this->product_models->create_product_code($cat_id);
		}
		
		$cat_data=$this->category_models->getCategory_by_id($cat_id);
		
		//print_r($cat_data);
		$cat_code=$cat_data[0]->cat_code;
		
		//print_r($sn_data);
		$status=0;
		if(count($sn_data)) $status=0; else $status=1;
		$status=1;
		
		//get nxt id
		$query=$this->product_models->get_product_next_ref_no($cat_id);
		
		//print_r($product_cat_ref_id);
		//echo $this->db->last_query();
		$result = $query->row();
		//print_r($result);
		
		//$product_code=$cat_code."/".$result->product_cat_ref_id+1;
		$product_cat_ref_id_nxt=$result->product_cat_ref_id+1;
		$product_code=$cat_code."/".sprintf("%03d",($product_cat_ref_id_nxt));
		//echo "code id:".$result->product_cat_ref_id+1;
		$st = array('status' =>$status,'product_code'=>$product_code,'product_cat_ref_id'=>$product_cat_ref_id_nxt);
        echo json_encode($st);
		
	}

	public function add_product()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] 	= 'add_products';
		$data['main_category'] 	= $this->category_models->getCategory();
		$data['unit_type'] 		= $this->product_models->getUnit();
		$data['tax'] 		    = $this->product_models->getTax();
		$this->load->view('add_product',$data);
	}

	public function get_sub_category_by_id()
	{
		$parent_category =  $this->input->get('category_id');

		if ( $parent_category ) {
			$val = $this->category_models->get_sub_category( $this->input->get('category_id') );
			if (!empty($val)) {
				echo '<select onChange="create_product_name()" name="subcategory" id="subcategory" class="form-control search-select">';
				echo "<option value=''></option>";
				foreach ($val as $key => $lst) {
				echo "<option value='$lst->sub_cat_id'>$lst->sub_cat_name</option>";
				}
				echo '</select>';
			}
			
		} else {
			echo NULL;
		}
		
	}

	public function save_product()
	{
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('product_name', 'Product Name', 'required');
        $this->form_validation->set_rules('product_code', 'Product Code', 'required|is_unique[product.product_code]');
        $this->form_validation->set_rules('product_cost', 'product cost', 'required');
        $this->form_validation->set_rules('product_price', 'product price', 'required');
        $this->form_validation->set_rules('wholesale_price', 'wholesale price', 'required');
        $this->form_validation->set_rules('credit_salling_price', 'credit salling price', 'required');
        $this->form_validation->set_rules('alert_quty', 'alert quty', 'required');



        if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        	$product_name 			= $this->input->post('product_name');
        	$product_code 			= $this->input->post('product_code');
        	$category 	  			= $this->input->post('category');
        	$subcategory  			= $this->input->post('subcategory');
        	$unit 		  			= $this->input->post('unit');
        	$product_cost 			= $this->price_filter($this->input->post('product_cost'));
        	$product_price 			= $this->price_filter($this->input->post('product_price'));
        	$wholesale_price 		= $this->price_filter($this->input->post('wholesale_price'));
        	$credit_salling_price 	= $this->price_filter($this->input->post('credit_salling_price'));
        	$tax 					= $this->input->post('tax');
        	$alert_quty 			= $this->input->post('alert_quty');
        	//$image_name 			= $this->input->post('product_image');
        	$product_details 		= $this->input->post('product_details');
			$product_part_no 		= $this->input->post('product_part_no');
			$product_oem_part_number=$this->input->post('product_oem_part_number');
			$product_id=$this->input->post('product_id');
			$store_position=$this->input->post('store_position');
			 $product_max_qty=intval($this->input->post('product_max_qty'));
			  $product_sn_exissts=$this->input->post('product_sn_exissts');
			   $product_cat_ref_id=intval($this->input->post('product_cat_ref_id'));
			
			

        	if (!empty($_FILES["userfile"]['name'])) {

                $image_name_enc = "PRODUCT_".time().$_FILES["userfile"]['name'];
                $this->load->library('upload',$this->image_manipulation->image_config($image_name_enc));

                if ( ! $this->upload->do_upload()){

                   $st = array('status' =>0,'validation' => $this->upload->display_errors());
                   echo json_encode($st);
                }
                else{

                    $this->load->library('image_lib',$this->image_manipulation->image_thumb($image_name_enc,100,100));
                    if ( ! $this->image_lib->resize())
                    {
                        echo $this->image_lib->display_errors();
                    }
                    else
                    {
                        $imgName    = $this->upload->data();
                        $imageThumb = $imgName['raw_name']."_thumb".$imgName['file_ext'];

                      $last_id = $this->product_models->save_product($product_name,$product_code,$category,$subcategory,$unit,$product_cost,$product_price,$wholesale_price,$credit_salling_price,$tax,$alert_quty,$imgName['file_name'],$imageThumb,$product_details,$product_part_no,$product_oem_part_number,$product_id,$store_position,$product_max_qty,$product_sn_exissts,$product_cat_ref_id);  
                       if ($last_id) {

                               $st = array('status' =>1,'validation' =>'Done!','last_id'=>"PD".sprintf("%04d",$last_id+1));
                               echo json_encode($st);

                       } else {

                               $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                               echo json_encode($st);
                       }
                       $this->image_lib->clear();
                    }                  

                }

        	} else {

                      $last_id = $this->product_models->save_product($product_name,$product_code,$category,$subcategory,$unit,$product_cost,$product_price,$wholesale_price,$credit_salling_price,$tax,$alert_quty,NULL,NULL,$product_details,$product_part_no,$product_oem_part_number,$product_id,$store_position,$product_max_qty,$product_sn_exissts,$product_cat_ref_id);
                       if ($last_id) {

                               $st = array('status' =>1,'validation' =>'Done!','last_id'=>"PD".sprintf("%04d",$last_id+1));
                               echo json_encode($st);

                       } else {

                               $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                               echo json_encode($st);
                       }
        	}
        	
        }

	}

	function price_filter($amount='')
	{
		$s = explode("Rs.",$amount);
		return str_replace(',', '', $s[1]);
	}

	public function get_list_product($value='')
	{
		$search_key=$this->input->get('search');
		$search_key_val=$search_key['value'];
		$start=$this->input->get('start');
		$length=$this->input->get('length');
		$category=$this->input->get('category');
		$totalData = 0;
		
		
	       		$values = $this->product_models->getProducts($start,$length,$search_key_val,$category);
		
		$value_count = $this->product_models->getProducts('','','',$category);

		if($search_key_val){
			$values_c = $this->product_models->getProducts('','',$search_key_val,$category);
			$totalData = count($values_c);	
			}else
		
		$totalData = count($value_count);
		$totalFiltered = $totalData; 
		
	        $data = array();

	        if (!empty($values)) {
	            foreach ($values as $products) {
if ($products->product_name == "OUTSTANDING"){continue;} 
	            if ($products->product_status == 0) {$k = "btn-warning";$m = "fa-minus-circle";} else {$k = "btn-green";$m = "fa-check";}
              $retVal = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name ;
              $qty = $this->product_models->get_item_qty($products->product_id);
              $qty = (empty($qty[0]->qty)) ? "--:--" : $qty[0]->qty ;
	            $row = array();
				
				//get transferd qty
				$transferd_qty=0;
				$transfer_reseve_qty=0;
				$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$products->product_id);
				$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$products->product_id);
				$sold_qty=$this->Sales_Model->getSoldQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$products->product_id);
				$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$products->product_id);
				$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$products->product_id);
				
				$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$products->product_id);
				 
				
                  $row[] = '<div style="margin-bottom: 0px; width: 50px; height: 50px;" class="fileupload-new thumbnail"><img alt="" src="'.asset_url()."uploads/thumbs/".$products->product_thumb.'"></div>';
                  $row[] = $products->product_code;
                  $row[] = $products->product_part_no;
                  //$row[] = $products->product_part_no;
	                $row[] = $products->product_name;
	                $row[] = $products->cat_name;
	                $row[] = $retVal;
                  $row[] = $products->product_price;
				  $row[] = $products->wholesale_price;
				  $row[] = $products->credit_salling_price;
	                $row[] = $products->product_cost;
	                $row[] = number_format(($purchased_qty+$transfer_reseve_qty+$sales_return_qty-$sold_qty-$transferd_qty-$product_damaged_qty), 2, '.', ',');
	               
	            $actdes='';
	                $actdes =$actdes. '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="'.base_url('products/view').'/'.$products->product_id.'"><i class="fa fa-file-text-o"></i> Product Details</a></li>
							';
							if ($this->session->userdata('ss_group_id')!=3){
                        $actdes =$actdes. '    <li><a href="'.base_url('products/edit').'/'.$products->product_id.'"><i class="fa fa-edit"></i> Edit Product</a></li>
							<li class="divider"></li><li><a onclick="product_delete('.$products->product_id.'); return false;" href="#"><i class="fa fa-trash-o"></i> Delete Product</a></li>
							';
							}
						$actdes = $actdes.'	
                            <li><a onclick=" print_barcode('.$products->product_id.'); return false;" href="#"><i class="fa fa-print"></i> Print Barcode</a></li>
                            
                            </ul></div>';
							
					$row[] =$actdes;		
	                $data[] = $row;
	            }

	            $output = array('data' =>$data);
	            //echo json_encode($output);
	        }else{
	            $output = array('data' =>'');
	           // echo json_encode($output);

	        }
			
			$json_data = array(
			"draw"            => intval( '' ),  
			"recordsTotal"    => intval( $totalData ),  
			"recordsFiltered" => intval( $totalFiltered ),
			"data"            => $data 
			);

	echo json_encode($json_data); 
	   }

  public function view($product_id = "")
  { 

    $sd = $this->product_models->get_product_by_id($product_id);

    if(!empty($sd)){

          $data['product_details'] = $this->product_models->get_product_by_id($product_id);
          $data['warehouses'] = $this->product_models->get_warehouse_product($product_id);
          $data['main_menu_name'] = $this->main_menu_name;
          $data['sub_menu_name'] = $this->sub_menu_name;
          $this->load->view('view_product',$data);

    }else{

          show_404();

    }

  }

  public function edit($product_id='')
  {
          $data['main_menu_name'] = $this->main_menu_name;
          $data['sub_menu_name']  = $this->sub_menu_name;
          $data['main_category']  = $this->category_models->getCategory();
          $data['unit_type']      = $this->product_models->getUnit();
          $data['tax']            = $this->product_models->getTax();
          $data['product_details'] = $this->product_models->get_product_by_id($product_id);
          $data['sub_category']   = $this->category_models->getSubCategory($data['product_details']->cat_id);
          $this->load->view('edit_product',$data);
  }

  public function single_barcode($product_id='')
  {
    $data['product_details'] = $this->product_models->get_product_by_id($product_id);
    $this->load->view('barcode/product_barcode',$data);
  }

    function gen_barcode($product_code = NULL, $height = 80)
    {
      if($this->input->get('code')){ $product_code = $this->input->get('code'); }
      if($this->input->get('height')){ $height = $this->input->get('height'); }
    
    //load library
    $this->load->library('zend');
    //load in folder Zend
    $this->zend->load('Zend/Barcode');
    //'drawText' => FALSE
    $barcodeOptions = array('text' => $product_code, 'barHeight' => $height, 'stretchText' => TRUE );
    $rendererOptions = array('imageType'=>'png', 'horizontalPosition' => 'center', 'verticalPosition' => 'middle');
    $imageResource = Zend_Barcode::render('code128', 'image', $barcodeOptions, $rendererOptions);
    return $imageResource;
     
    }

  function delete_product($product_id='')
  {
    $d = $this->product_models->delete_product($this->input->post('product_id'));
    if ($d) {
      $e = array('status' =>1);
      echo json_encode($e);
    } else {
      $e = array('status' =>0,'validation'=>'This product is already linked. You cannot delete it.');
      echo json_encode($e);
    }
    
  }
  public function edit_product()
  {
     
          $product_name           = $this->input->post('product_name');
          $product_code           = $this->input->post('product_code');
          $category               = $this->input->post('category');
          $subcategory            = $this->input->post('subcategory');
          $unit                   = $this->input->post('unit');
          $product_cost           = $this->price_filter($this->input->post('product_cost'));
          $product_price          = $this->price_filter($this->input->post('product_price'));
          $wholesale_price        = $this->price_filter($this->input->post('wholesale_price'));
          $credit_salling_price   = $this->price_filter($this->input->post('credit_salling_price'));
		  $product_cost_2		  = $this->price_filter($this->input->post('product_cost_2'));
          $tax                    = $this->input->post('tax');
          $alert_quty             = $this->input->post('alert_quty');
          $product_details        = $this->input->post('product_details');
		  $product_part_no 		= $this->input->post('product_part_no');
		  $product_oem_part_number= $this->input->post('product_oem_part_number');
		  $store_position= $this->input->post('store_position');
		   $product_max_qty=intval($this->input->post('product_max_qty'));
		   $product_sn_exissts=$this->input->post('product_sn_exissts');
		   $product_cat_ref_id=intval($this->input->post('product_cat_ref_id'));
		  

          if (!empty($_FILES["userfile"]['name'])) {

                $image_name_enc = "PRODUCT_".time().$_FILES["userfile"]['name'];
                $this->load->library('upload',$this->image_manipulation->image_config($image_name_enc));

                if ( ! $this->upload->do_upload()){

                   $st = array('status' =>0,'validation' => $this->upload->display_errors());
                   echo json_encode($st);
                }
                else{

                    $this->load->library('image_lib',$this->image_manipulation->image_thumb($image_name_enc,100,100));
                    if ( ! $this->image_lib->resize())
                    {
                        echo $this->image_lib->display_errors();
                    }
                    else
                    {
                        $imgName    = $this->upload->data();
                        $imageThumb = $imgName['raw_name']."_thumb".$imgName['file_ext'];

                       if ($this->product_models->update_product($this->input->post('product_id'), $product_name,$product_code,$category,$subcategory,$unit,$product_cost,$product_price,$wholesale_price,$credit_salling_price,$tax,$alert_quty,$imgName['file_name'],$imageThumb,$product_details,$product_part_no,$product_oem_part_number,$store_position,$product_max_qty,$product_sn_exissts,$product_cat_ref_id,$product_cost_2)) {

                               $st = array('status' =>1,'validation' =>'Done!');
                               echo json_encode($st);

                       } else {

                               $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                               echo json_encode($st);
                       }
                       $this->image_lib->clear();
                    }                  

                }

          } else {

                       if ($this->product_models->update_product($this->input->post('product_id'), $product_name,$product_code,$category,$subcategory,$unit,$product_cost,$product_price,$wholesale_price,$credit_salling_price,$tax,$alert_quty,0,0,$product_details,$product_part_no,$product_oem_part_number,$store_position,$product_max_qty,$product_sn_exissts,$product_cat_ref_id,$product_cost_2)) {

                               $st = array('status' =>1,'validation' =>'Done!');
                               echo json_encode($st);

                       } else {

                               $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                               echo json_encode($st);
                       }

          }
          


  }


}