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/laciasmara.com/public_html/shop/application/controllers/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/laciasmara.com/public_html/shop/application/controllers/admin/Products copy 2.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;

	function __construct()
	{

		parent::__construct();
		$this->load->model('product_m');
		$this->load->model('category_m');
		$this->load->model('configuration_m');
		$this->load->model('brand_m');
		$this->load->model('product_attributes_m');
		$this->load->helper('form');
	}

	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 {

			//Add pagination
			$this->load->helper('pagination_helper');
			add_pagination(base_url() . 'admin/products/index', $this->product_m->record_count(), 100, 4);
			$this->data['products'] = $this->product_m->get_all_products(100, $this->uri->segment(4));
			$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');
	}

	function bundle()
	{

		//Add pagination
		$this->load->helper('pagination_helper');
		add_pagination(base_url() . 'admin/products/bundle', $this->product_m->record_count_bundle(), 100, 4);
		$this->data['bundle'] = $this->product_m->get_bundle(100, $this->uri->segment(4));
		$this->data['use_pagination'] = 'yes';




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

	function add_bundle()
	{
		$this->data['bundle'] = $this->product_m->get_new_bundle();

		$this->data['products'] = $this->db
			->distinct()
			->select('title,id_products')
			->from('products')
			->where('product_status', 1)
			->order_by('title')
			->get()
			->result();

		//validation in action
		//validation check in action
		$config = $this->product_m->rules_bundle;
		$this->form_validation->set_rules($config);
		$this->form_validation->set_error_delimiters(
			'<div class="error">',
			'</div>'
		);

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


			if ($_FILES['image']['size'] !== 0) {
				$config['upload_path'] 		= './uploads/bundle/';
				$config['allowed_types'] 	= 'jpeg|jpg|png|pdf';
				$config['max_size']			= '5000';
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('image')) {
					echo $this->upload->display_errors();
					die;
					$this->session->set_flashdata('receipt_file_error', '<br>
					<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format.</p>');
					//echo $this->upload->display_errors(); exit();
					redirect('/admin/products/add_bundle');
				} else {
					$image = $this->upload->data();
					$image_name =  $image['file_name'];
				}
			}

			$created_date = date('Y-m-d H:i:s');
			$Selled = 0;
			$Product_id = "11,12";

			$data = $this->table_data_processing_bundle(
				$this->input->post('title'),
				$Selled,
				$this->input->post('stock'),
				$Product_id,
				$this->input->post('price'),
				$image_name,
				$this->input->post('status'),
				$created_date
			);

			$this->product_m->add_bundle($data);

			$bundle_name = $this->input->post('title');

			$user_id = $this->session->userdata('admin')['id'];
			$activity = 'User menambah bundle (' . $bundle_name . ')';

			log_activity($user_id, $activity);

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

			redirect('admin/products/bundle');
		}

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

	function edit_bundle($id = null)
	{

		//check if id exist. If not exist, show 404.
		$count = $this->product_m->count_exist_bundle($id);

		if ($count == 0) {
			//page not exist
			show_404();
		}

		$this->data['products'] = $this->db
			->distinct()
			->select('title,id_products')
			->from('products')
			->where('product_status', 1)
			->order_by('title')
			->get()
			->result();


		$this->data['bundle'] = $this->product_m->get_bundle_1($id);

		//get all chosen (active) product
		$active_product = $this->data['bundle']->product_id;
		if ($active_product != null) {
			$this->data['chosen_products'] = array_filter(
				explode(',', $active_product)
			); //array_filter to remove empty array element
		}

		$config = $this->product_m->rules_bundle;

		$this->form_validation->set_rules($config);
		$this->form_validation->set_error_delimiters(
			'<div class="error">',
			'</div>'
		);

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


			if ($_FILES['image']['size'] !== 0) {
				$config['upload_path'] 		= './uploads/bundle/';
				$config['allowed_types'] 	= 'jpeg|jpg|png|webp';
				$config['max_size']			= '5000';
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				if (!$this->upload->do_upload('image')) {
					echo $this->upload->display_errors();
					die;
					$this->session->set_flashdata('receipt_file_error', '<br>
					<p style="background:red; color:white; padding:5px; font-weight:bold;">Image Upload Error. Wrong format.</p>');
					//echo $this->upload->display_errors(); exit();
					redirect('/admin/products/add_bundle');
				} else {
					$image = $this->upload->data();
					$image_name =  $image['file_name'];
				}
			} else {
				// Gunakan gambar yang sudah ada
				$image_name = $this->data['bundle']->image;
			}

			$created_date = date('Y-m-d H:i:s');
			$Selled = 0;
			$Product_id = "11,12";

			$data = $this->table_data_processing_bundle(
				$this->input->post('title'),
				$Selled,
				$this->input->post('stock'),
				$Product_id,
				$this->input->post('price'),
				$image_name,
				$this->input->post('status'),
				$created_date
			);

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

			$bundle_name = $this->input->post('title');

			$user_id = $this->session->userdata('admin')['id'];
			$activity = 'User mengedit bundle (' . $bundle_name . ')';

			log_activity($user_id, $activity);

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

			redirect('admin/products/bundle');
		}


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

	function specialdiscount()
	{

		//Add pagination
		$this->load->helper('pagination_helper');
		add_pagination(base_url() . 'admin/products/specialdiscount', $this->product_m->record_count_special_discount(), 100, 4);
		$this->data['special_discount'] = $this->product_m->get_special_discount(100, $this->uri->segment(4));
		$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/specialdiscount';
		$this->load->view('admin/templates/header', $this->data_header);
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');
	}

	function add_special_discount()
	{
		$this->data['special_discount'] = $this->product_m->get_new_special_discount();

		//get parent product categories
		$this->load->model('category_m');
		$this->data['parent_categories'] = $this->category_m->get_parent_categories();

		//get products
		$this->data['products'] = $this->db
			->distinct()
			->select('title,id_products')
			->from('products')
			->where('product_status', 1)
			->order_by('title')
			->get()
			->result();

		//get brands
		$this->db
			->select('id_brands, brand')
			->from('brands')
			->order_by('brand', 'ASC');
		$this->data['brands'] = $this->db->get()->result();

		//validation in action
		//validation check in action
		$config = $this->product_m->rules_special_discount;
		$this->form_validation->set_rules($config);
		$this->form_validation->set_error_delimiters(
			'<div class="error">',
			'</div>'
		);

		if ($this->form_validation->run($this) == true) {
			$created_date = date('Y-m-d H:i:s');
			$Status = 'Next';
			$data = $this->table_data_processing_special_discount(
				$this->input->post('title'),
				$this->input->post('discount_type'),
				$this->input->post('discount_value'),
				$this->input->post('promostart'),
				$this->input->post('promoend'),
				$Status,
				$created_date,
			);

			$this->input->post('discount_type') == 'Brand'
				? ($data['brand_id'] = implode(',', $this->input->post('brand_id')))
				: ($data['brand_id'] = null);
			$this->input->post('discount_type') == 'Produk'
				? ($data['product_id'] = implode(
					',',
					$this->input->post('product_id')
				))
				: ($data['product_id'] = null);
			$this->product_m->add_special_discount($data);

			$voucher_name = $this->input->post('title');

			$user_id = $this->session->userdata('admin')['id'];
			$activity = 'User menambah discount (' . $voucher_name . ')';

			log_activity($user_id, $activity);

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

			redirect('admin/products/specialdiscount');
		}

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

	function edit_special_discount($id = null)
	{

		//check if id exist. If not exist, show 404.
		$count = $this->product_m->count_exist_special_discount($id);

		if ($count == 0) {
			//page not exist
			show_404();
		}

		$this->data['products'] = $this->db
			->distinct()
			->select('title,id_products')
			->from('products')
			->where('product_status', 1)
			->order_by('title')
			->get()
			->result();

		//get Categories
		$this->load->model('category_m');
		$this->data['parent_categories'] = $this->category_m->get_parent_categories();

		//get brands
		$this->db
			->select('id_brands, brand')
			->from('brands')
			->order_by('brand', 'ASC');
		$this->data['brands'] = $this->db->get()->result();

		$this->data['special_discount'] = $this->product_m->get_special_discount_1($id);

		//get all chosen (active) product
		$active_product = $this->data['special_discount']->product_id;
		if ($active_product != null) {
			$this->data['chosen_products'] = array_filter(
				explode(',', $active_product)
			); //array_filter to remove empty array element
		}

		//get all chosen (active) categories
		$active_categories = $this->data['special_discount']->category_id;
		if ($active_categories != null) {
			$this->data['chosen_categories'] = array_filter(
				explode(',', $active_categories)
			); //array_filter to remove empty array element
		}

		$active_brands = $this->data['special_discount']->brand_id;
		if ($active_brands != null) {
			$this->data['chosen_brands'] = array_filter(explode(',', $active_brands)); //array_filter to remove empty array element
		}

		$config = $this->product_m->rules_special_discount;

		$this->form_validation->set_rules($config);
		$this->form_validation->set_error_delimiters(
			'<div class="error">',
			'</div>'
		);

		if ($this->form_validation->run($this) == true) {
			//get current created date from table
			$this->db
				->select('created_date')
				->from('special_discount')
				->where('id_discount', (int) $id);
			$created_date = $this->db->get()->row()->created_date;
			$Status = 'Next';

			$data = $this->table_data_processing_special_discount(
				$this->input->post('title'),
				$this->input->post('discount_type'),
				$this->input->post('discount_value'),
				$this->input->post('promostart'),
				$this->input->post('promoend'),
				$Status,
				$created_date,
			);

			$this->input->post('discount_type') == 'Brand'
				? ($data['brand_id'] = implode(',', $this->input->post('brand_id')))
				: ($data['brand_id'] = null);
			$this->input->post('discount_type') == 'Produk'
				? ($data['product_id'] = implode(
					',',
					$this->input->post('product_id')
				))
				: ($data['product_id'] = null);
			$this->product_m->edit_special_discount($id, $data);
			$voucher_name = $this->input->post('title');

			$user_id = $this->session->userdata('admin')['id'];
			$activity = 'User mengedit discount (' . $voucher_name . ')';

			log_activity($user_id, $activity);

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

			redirect('admin/products/edit_special_discount/' . $id);
		}


		//load view
		$this->data['subview'] = 'admin/products/edit_special_discount';
		$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 or EDIT a product content 
	function edit($id = NULL)
	{

		if ($id != NULL) {

			$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 is an existing product
			$this->data['new_product'] = 'no';

			$this->data['products'] 			= $this->product_m->get($id);
			$this->data['productssuggest'] = $this->db
				->distinct()
				->select('title,id_products')
				->from('products')
				->where('product_status', 1)
				->order_by('title')
				->get()
				->result();
			$this->data['parent_categories'] 	= $this->category_m->get_parent_categories();
			// Get active product_suggest and convert it into an array
			$active_product = $this->data['products']->product_suggest;
			if ($active_product != null) {
				$this->data['chosen_products'] = array_filter(
					explode(',', $active_product)
				);
			}

			//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();

			$this->db->select('id_customers, name')->from('customers')->where('reseller_id IS NOT NULL');
			$this->data['customers'] = $this->db->get()->result();

			//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;

			/*get shipment method*/
			$this->data['shipment'] = $this->db->select('*')->from('shipment_method')->order_by('id', 'ASC')->get()->result();

			/*get all chosen (active) shipment*/
			$this->db->select('*')->from('shipment_method_product')->where('product_id', $id);
			$this->data['chosen_shipments'] = $this->db->get()->result();

			//assign to properties, used for custom callback validation
			$this->product_current_id = (int) $this->data['products']->id_products;
		} else {

			if (($this->data['membership_type'] == "starter" && $this->data['jml_produk'] >= 100) || ($this->data['membership_type'] == "business" && $this->data['jml_produk'] >= 500)) {
				redirect('admin/products');
			}

			//id is null. this is a new product
			$this->data['new_product'] = 'yes';
			/*get product data*/
			$this->data['products'] 			= $this->product_m->get_new();
			$this->data['productssuggest'] = $this->db
				->distinct()
				->select('title,id_products')
				->from('products')
				->where('product_status', 1)
				->order_by('title')
				->get()
				->result();
			$this->data['parent_categories'] 	= $this->category_m->get_parent_categories();
			$this->data['brands'] 				= $this->brand_m->get_brands();

			$this->db->select('id_customers, name')->from('customers')->where('reseller_id IS NOT NULL');
			$this->data['customers'] = $this->db->get()->result();
			/*get shipment method*/
			$this->data['shipment'] = $this->db->select('*')->from('shipment_method')->order_by('id', 'ASC')->get()->result();

			//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 in product details table
			foreach ($this->input->post('product_details') as $product_detail) {

				if ($id == NULL) {
					$this->db->select('sku')->from('product_details')->where('sku', $product_detail['sku']);
				} else {
					$this->db->select('sku')->from('product_details')->where('product_id !=', $id)->where('sku', $product_detail['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;'>Kode SKU {$product_detail['sku']} sudah ada. Gunakan SKU/Kode Produk unik lainnya.</p>");

					if ($id == NULL) {
						redirect('admin/products/edit');
					} else {
						redirect('admin/products/edit/' . $id);
					}
				}
			}


			$data = $this->table_data_processing();
			// Mengambil pemilihan produk dari formulir
			$selectedProducts = $this->input->post('product_id');

			// Periksa apakah ada produk yang dipilih
			if (!empty($selectedProducts)) {
				$productSuggest = implode(',', $selectedProducts);
			} else {
				$productSuggest = '';
			}

			// Menyimpan pemilihan produk dalam kolom product_suggest
			$data['product_suggest'] = $productSuggest;


			if ($id == NULL) {
				$product_id = (int) $this->product_m->add_product($data);
			} else {
				$this->product_m->edit_product($id, $data);
			}

			/*INSERT INTO SHIPMENT*/
			$shipments_id = $this->input->post('shipment_id');

			if (!in_array("3", $shipments_id)) {
				$shipments_id[]	= '3'; //add regular shipping method
			}

			if ($id != NULL) {
				//firstly, we delete all existing records inside current table
				$this->db->where('product_id', $id);
				$this->db->delete('shipment_method_product');
			}

			$shipments_keywords = '';

			foreach ($shipments_id as $shipment_id) {

				$data_shipment = array(
					'shipment_method_id'	=> $shipment_id,
				);

				if ($id != NULL) {
					$data_shipment['product_id'] = $id;
				} else {
					$data_shipment['product_id'] = $product_id;
				}
				$this->db->insert('shipment_method_product', $data_shipment);
				$this->db->select('name')->from('shipment_method')->where('id', $shipment_id);
				$shipments_keywords .= $this->db->get()->row()->name . ',';
			}

			$data_shipments = array(
				'shipment_method' => $shipments_keywords,
			);
			if ($id != NULL) {
				$this->db->where('id_products', $id);
			} else {
				$this->db->where('id_products', $product_id);
			}
			$this->db->update('products', $data_shipments);

			/*INSERT INTO CATEGORY*/
			//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) {

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

				foreach ($categories_id as $category_id) {

					$data = array(
						'id_category' => $category_id,
					);

					if ($id != NULL) {
						$data['id_product'] = $id;
					} else {
						$data['id_product'] = $product_id;
					}
					$this->db->insert('category_product', $data);
				}
			} else {

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

				$data = array(
					'id_category' => NULL,
				);
				if ($id != NULL) {
					$data['id_product'] = $id;
				} else {
					$data['id_product'] = $product_id;
				}
				$this->db->insert('category_product', $data);
			}

			//Varians and attributes
			foreach ($this->input->post('product_details') as $product_detail) {

				if (!empty($product_detail['sku'])) {

					$data = array(
						'sku' => $product_detail['sku'],
						'price' => $product_detail['price'],
						'discounted_price' => $product_detail['discounted_price'],
						'length' => $product_detail['length'],
						'width' => $product_detail['width'],
						'height' => $product_detail['height'],
						'is_indent' => $product_detail['is_indent'],
					);

					if ($id != NULL) {
						$data['product_id'] = $id;
					} else {
						$data['product_id'] = $product_id;
					}

					if (empty($product_detail['weight'])) {
						$data['weight'] = 1;
					} else {
						$data['weight'] = $product_detail['weight'];
					}

					if ($id != NULL) {
						//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', $product_detail['sku'])->where('product_id', $id);
						$count_sku = $this->db->get()->num_rows();
					} else {
						$count_sku = 0;
					}

					if ($count_sku > 0) {
						//update product detail
						$this->db->where('sku', $product_detail['sku']);
						$this->db->where('product_id', $id);
						$this->db->update('product_details', $data);

						//get $product_details_id
						$this->db->select('id')->from('product_details')->where('sku', $product_detail['sku'])->where('product_id', $id);
						$product_details_id = $this->db->get()->row()->id;
					} else {
						//insert new product detail
						$this->db->insert('product_details', $data);
						$product_details_id = $this->db->insert_id();
					}

					//adit product_combination table
					//first, delete combination table
					$this->db->where('product_details_id', $product_details_id);
					$this->db->delete('product_combination');

					for ($i = 0; $i < 20; $i++) {

						if (!empty($product_detail['variant'][$i]) && !empty($product_detail['attribute'][$i])) {

							$data = array(
								'product_details_id' => $product_details_id,
								'attribute_id' => $product_detail['variant'][$i],
								'attribute_detail_id' => $product_detail['attribute'][$i],
							);

							if ($id == NULL) {
								$data['product_id'] = $product_id;
							} else {
								$data['product_id'] = $id;
							}
							$this->db->insert('product_combination', $data);
						}
					}
				}
			}

			if ($id != NULL) {
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Produk berhasil diedit</p>');
				redirect('admin/products/edit/' . $id);
			} else {
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Produk berhasil dibuat</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 delete a product
	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();
		}

		$user_id = $this->session->userdata('admin')['id'];

		// Query untuk mengambil title dari tabel product
		$this->db->select('title');
		$this->db->from('products');
		$this->db->where('id_products', $id);
		$query_product = $this->db->get();
		$product_data = $query_product->row();

		// Buat string "title/SKU"
		if ($product_data) {
			$activity = 'User menghapus produk (' . $product_data->title . ')';
		} else {
			// Handle jika data produk atau detail produk tidak ditemukan
			$activity = 'User menghapus produk (' . $id . ')';
		}

		log_activity($user_id, $activity);

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

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

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

		//check if id_product_detail exist. If not exist, show 404.
		$this->db->select('id')->from('product_details')->where('id', $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();
		}

		$user_id = $this->session->userdata('admin')['id'];

		// Query untuk mengambil title dari tabel product
		$this->db->select('sku');
		$this->db->from('product_details');
		$this->db->where('id', $id_product_detail);
		$query_product = $this->db->get();
		$product_data = $query_product->row();

		// Buat string "title/SKU"
		if ($product_data) {
			$activity = 'User menghapus SKU (' . $product_data->sku . ')';
		} else {
			// Handle jika data produk atau detail produk tidak ditemukan
			$activity = 'User menghapus varian (' . $id_product_detail . ')';
		}

		log_activity($user_id, $activity);

		$this->db->where('id', $id_product_detail);
		$this->db->delete('product_details');

		$this->db->where('product_id', $id_product);
		$this->db->where('product_details_id', $id_product_detail);
		$this->db->delete('product_combination');

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

	function delete_special_discount($id)
	{

		//check if id exist. If not exist, show 404.
		$count = $this->product_m->count_exist_special_discount($id);

		if ($count == 0) {
			//page not exist 
			show_404();
		}

		$user_id = $this->session->userdata('admin')['id'];

		// Query untuk mengambil title dari tabel product
		$this->db->select('title');
		$this->db->from('special_discount');
		$this->db->where('id_discount', $id);
		$query_product = $this->db->get();
		$product_data = $query_product->row();

		// Buat string "title/SKU"
		if ($product_data) {
			$activity = 'User menghapus special discount (' . $product_data->title . ')';
		} else {
			// Handle jika data produk atau detail produk tidak ditemukan
			$activity = 'User menghapus special discount (' . $id . ')';
		}

		log_activity($user_id, $activity);

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

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

	function delete_bundle($id)
	{

		//check if id exist. If not exist, show 404.
		$count = $this->product_m->count_exist_bundle($id);

		if ($count == 0) {
			//page not exist 
			show_404();
		}

		$user_id = $this->session->userdata('admin')['id'];

		// Query untuk mengambil title dari tabel product
		$this->db->select('title');
		$this->db->from('bundle');
		$this->db->where('id', $id);
		$query_product = $this->db->get();
		$product_data = $query_product->row();

		// Buat string "title/SKU"
		if ($product_data) {
			$activity = 'User menghapus bundle (' . $product_data->title . ')';
		} else {
			// Handle jika data produk atau detail produk tidak ditemukan
			$activity = 'User menghapus bundle (' . $id . ')';
		}

		log_activity($user_id, $activity);

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

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

	function product_images($product_id = NULL)
	{

		if ($product_id == NULL) {
			redirect(base_url('admin/products'));
		}

		//pagination in action. 100 results per page
		$this->load->library('pagination');
		$config['base_url'] = base_url() . 'admin/products/product_images';
		$config['per_page'] = 100;
		$config['uri_segment'] = 3;

		//fetch all product images 
		$this->db->select('id')->from('product_images')->where('product_id', $product_id);
		$config['total_rows'] = $this->db->get()->num_rows();
		$this->pagination->initialize($config);

		$this->db->select('*');
		$this->db->from('product_images');
		$this->db->where('product_id', $product_id);
		$this->db->order_by('product_details_id', 'ASC');
		$this->db->order_by('priority', 'ASC');
		$this->db->limit($config['per_page'], $this->uri->segment($config['uri_segment']));
		$this->data['product_images'] = $this->db->get()->result();

		$this->data['product_id'] = $product_id;
		//get product name
		$this->db->select('title')->from('products')->where('id_products', $product_id);
		$this->data['product_name'] = $this->db->get()->row()->title;
		//load view
		$this->data['subview'] = 'admin/products/product_images';
		$this->load->view('admin/templates/header', $this->data_header);
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');
	}

	function edit_product_image($product_id = NULL, $product_image_id = NULL, $case_addnew = false)
	{

		if ($product_id == NULL) {
			redirect(base_url('admin/products'));
		}

		$case_save = $this->input->post('case_save');
		if (isset($case_save)) {
			if ($case_save == 'addnew') {
				$config = array(
					array(
						'field'   => 'title',
						'label'   => 'Banner Title',
						'rules'   => 'trim|required'
					),
					array(
						'field'   => 'title_en',
						'label'   => 'Banner Title English',
						'rules'   => 'trim|required'
					),
					array(
						'field'   => 'product_detail_id',
						'label'   => 'Varian',
						'rules'   => 'required'
					),
					array(
						'field'   => 'priority[]',
						'label'   => 'Priority',
						'rules'   => 'trim|required|numeric'
					),
					array(
						'field'   => 'status[]',
						'label'   => 'status',
						'rules'   => 'trim|required'
					)
				);

				$this->load->library('form_validation');
				$this->form_validation->set_rules($config);
				$this->form_validation->set_error_delimiters('<div class="error">', '</div>');

				if ($this->form_validation->run() == TRUE) {
					$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();

					$ar_status = $this->input->post('status[]');
					$ar_priority = $this->input->post('priority[]');

					$cpt = count($_FILES['image']['name']);

					$config['upload_path'] = './uploads/product/';
					$config['allowed_types'] = 'jpg|png|gif|jpeg|webp';
					$config['max_size']	= '600';
					$config['max_width']  = $image_dimension->product_image_width;
					$config['max_height'] = $image_dimension->product_image_height;
					$this->load->library('upload', $config);

					$files = $_FILES;
					for ($i = 0; $i < $cpt; $i++) {
						if ($_FILES['image']['size'][$i] !== 0) {

							$_FILES['image']['name'] = $files['image']['name'][$i];

							$_FILES['image']['type'] = $files['image']['type'][$i];

							$_FILES['image']['tmp_name'] = $files['image']['tmp_name'][$i];

							$_FILES['image']['error'] = $files['image']['error'][$i];

							$_FILES['image']['size'] = $files['image']['size'][$i];



							$this->upload->initialize($config);
							if (!$this->upload->do_upload('image')) {
								echo $this->upload->display_errors();
								die();
								$this->session->set_flashdata('image_error', '<br>
								<p style="background:orange; color:white; padding:5px; font-weight:bold;">Image Upload Error. Salah format atau ukuran.</p>');
								redirect('admin/products/edit_product_image/' . $product_id . '/' . $this->input->post('correct_product_details_id') . '/addnew');
							} else {
								$image = $this->upload->data();
								$image_filename[$i] = $image['file_name'];
							}

							$this->load->library('image_lib');

							//image resizing (LARGE IMAGE)
							$config['image_library'] = 'gd2';
							$config['source_image'] = './uploads/product/' . $image_filename[$i];
							$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);

							$this->image_lib->resize();

							//image resizing (SMALL IMAGE)
							$config['image_library'] = 'gd2';
							$config['source_image'] = './uploads/product/' . $image_filename[$i];
							$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);

							$this->image_lib->resize();

							//image resizing (THUMBNAIL)
							$config['image_library'] = 'gd2';
							$config['source_image'] = './uploads/product/' . $image_filename[$i];
							$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);

							$this->image_lib->resize();
						}
						$data = array(
							'product_id' => $product_id,
							'product_details_id' =>
							$this->input->post('correct_product_details_id'),
							'title' =>
							$this->security->xss_clean($this->input->post('title')),
							'title_en' =>
							$this->security->xss_clean($this->input->post('title_en')),
							'priority' =>
							$this->input->post('priority')[$i],
							'status' =>
							$this->input->post('status')[$i],
							'alt' =>
							$this->input->post('alt')[$i]
						);
						if (isset($image_filename[$i])) {
							$data['image'] = $image_filename[$i];
						}

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

					$user_id = $this->session->userdata('admin')['id'];
					$activity = 'User menambahkan gambar produk(' . $data['title'] . ')';

					log_activity($user_id, $activity);
					redirect(base_url('admin/products/product_images/' . $product_id));
				}

				// else{
				// 	// jika error
				// 	// echo validation_errors();

				// 	redirect('admin/products/edit_product_image/' . $product_id . '/' . $this->input->post('correct_product_details_id').'/addnew');
				// }
			}
			// return false;
		}
		if ($product_image_id == NULL) {
			//create new  photo
			$product_image = new stdClass();
			$product_image->title = '';
			$product_image->title_en = '';
			$product_image->image = '';
			$product_image->priority = '';
			$product_image->alt = '';
			$product_image->status = '';
			$product_image->product_details_id = '';
			$this->data['product_image'] = $product_image;

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

			//edit current photo
			$this->db->select('*')->from('product_images')->where('id', $product_image_id);
			$this->data['product_image'] = $this->db->get()->row();

			if (count($this->data['product_image']) == 0) {
				if (empty($case_addnew) || $case_addnew != 'addnew') {
					redirect(base_url('admin/products/product_images/' . $product_id));
				}
			}
		}

		//validation check in action
		$config = array(
			array(
				'field'   => 'title',
				'label'   => 'Banner Title',
				'rules'   => 'trim|required'
			),
			array(
				'field'   => 'product_detail_id',
				'label'   => 'Varian',
				'rules'   => 'required'
			),
			array(
				'field'   => 'priority',
				'label'   => 'Priority',
				'rules'   => 'trim|required|numeric'
			),
			array(
				'field'   => 'status',
				'label'   => 'status',
				'rules'   => 'trim|required'
			)
		);

		$this->load->library('form_validation');
		$this->form_validation->set_rules($config);
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');

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

			$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();

			if ($_FILES['image']['size'] !== 0) {

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

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

				if (!$this->upload->do_upload('image')) {
					$this->session->set_flashdata('image_error', '<br>
						<p style="background:orange; color:white; padding:5px; font-weight:bold;">Image Upload Error. Salah format atau ukuran.</p>');
					redirect('admin/products/edit_product_image/' . $product_id);
				} else {
					$image = $this->upload->data();
					$image_filename = $image['file_name'];
				}

				$this->load->library('image_lib');

				//image resizing (LARGE IMAGE)
				$config['image_library'] = 'gd2';
				$config['source_image'] = './uploads/product/' . $image_filename;
				$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_filename;
				$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_filename;
				$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();
			}


			$data = array(
				'product_id' => $product_id,
				'product_details_id' => $this->input->post('product_detail_id'),
				'title' => $this->security->xss_clean($this->input->post('title')),
				'title_en' => $this->security->xss_clean($this->input->post('title_en')),
				'priority' => $this->input->post('priority'),
				'alt' => $this->input->post('alt'),
				'status' => $this->input->post('status')
			);
			if (isset($image_filename)) {
				$data['image'] = $image_filename;
			}

			if ($product_image_id == NULL) {
				$this->db->insert('product_images', $data);
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Foto produk berhasil ditambahkan</p>');
				redirect('admin/products/product_images/' . $product_id);
			} else {
				$user_id = $this->session->userdata('admin')['id'];
				$activity = 'User mengedit gambar produk(' . $data['title'] . ')';

				log_activity($user_id, $activity);
				$this->db->where('id', $product_image_id);
				$this->db->update('product_images', $data);
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Foto produk berhasil diedit</p>');
				redirect('admin/products/edit_product_image/' . $product_id . '/' . $product_image_id);
			}
		}

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

		//get product details
		$this->db->select('id, product_id, sku')->from('product_details')->where('product_id', $product_id)->order_by('id', 'ASC');
		$this->data['product_details'] = $this->db->get()->result();

		if ($case_addnew == 'addnew') {
			$this->data['case_addnew'] = $case_addnew;
		}
		$this->data['product_image_id'] = $product_image_id;

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

	function delete_product_image($product_id = NULL, $product_image_id = NULL)
	{

		if ($product_id == NULL || $product_image_id == NULL) {
			redirect(base_url('admin/products'));
		}

		//get image file name for deletion
		$this->db->select('image')->from('product_images')->where('id', $product_image_id);
		$image = $this->db->get()->row()->image;

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

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

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

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

		$this->db->where('id', $product_image_id);
		$this->db->delete('product_images');
		//logging
		$user_id = $this->session->userdata('admin')['id'];

		// Query untuk mengambil title dari tabel product
		$this->db->select('title');
		$this->db->from('products');
		$this->db->where('id_products', $product_id);
		$query_product = $this->db->get();
		$product_data = $query_product->row();

		// Buat string "title/SKU"
		if ($product_data) {
			$activity = 'User menghapus gambar produk (' . $product_data->title . ')';
		} else {
			// Handle jika data produk atau detail produk tidak ditemukan
			$activity = 'User menghapus gambar produk (' . $product_id . ')';
		}

		log_activity($user_id, $activity);
		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Foto produk berhasil dihapus</p>');
		redirect('admin/products/product_images/' . $product_id);
	}

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

		$num_rows = $this->product_m->cek_existing_product_code($str, $this->product_current_id);
		if ($num_rows != 0) {
			$this->form_validation->set_message('_cek_existing_product_code', 'Product code 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()
	{

		$data = array(
			'title' 					=> $this->security->xss_clean($this->input->post('product_name')),
			'alias' 					=> url_title($this->security->xss_clean($this->input->post('product_name'))),
			'description' 				=> $this->security->xss_clean($this->input->post('description')),
			'description_en' 			=> $this->security->xss_clean($this->input->post('description_en')),
			'long_description' 			=> $this->security->xss_clean($this->input->post('long_description')),
			'long_description_en' 		=> $this->security->xss_clean($this->input->post('long_description_en')),
			'additional_information' 	=> $this->security->xss_clean($this->input->post('additional_information')),
			'additional_information_en' => $this->security->xss_clean($this->input->post('additional_information_en')),
			'media_file_link' 			=> $this->security->xss_clean($this->input->post('media_file_link')),
			'product_video_link' 		=> $this->security->xss_clean($this->input->post('product_video_link')),
			'product_guide_link' 		=> $this->security->xss_clean($this->input->post('product_guide_link')),
			'brand_id' 					=> (int) $this->input->post('brand_id'),
			'product_status' 			=> $this->input->post('product_status'),
			'priority' 					=> $this->input->post('priority'),
			'new_arrival' 				=> $this->input->post('new_arrival'),
			'best_seller' 				=> $this->input->post('best_seller'),
			'restock' 					=> $this->input->post('restock'),
			'customer_id_exc' 			=> $this->input->post('customer_eksklusif'),
			'popular_product' 			=> $this->input->post('popular_product'),
			'meta_description' 			=> $this->security->xss_clean($this->input->post('meta_description')),
			'meta_title' 				=> $this->security->xss_clean($this->input->post('meta_title')),
			'indent_time' 				=> $this->security->xss_clean($this->input->post('indent_time')),
			'indent_dp' 				=> $this->security->xss_clean($this->input->post('indent_dp'))
		);

		return $data;
	}

	private function table_data_processing_special_discount(
		$title,
		$discount_type,
		$discount_value,
		$promostart,
		$promoend,
		$Status,
		$created_date
	) {
		$data = [
			'title' => $this->security->xss_clean($title),
			'type' => $this->security->xss_clean($discount_type),
			'value' => (int) $this->security->xss_clean($discount_value),
			'time_start' => $promostart,
			'time_end' => $promoend,
			'status' => $Status,
			'created_date' => $created_date,
		];

		//Promo by Product Category
		//get category_id from view,
		$categories_id = $this->input->post('category_id');

		//check id there is content inside category array
		if (is_array($categories_id)) {
			$categories_id_count = count($categories_id);
		} else {
			$categories_id_count = 0;
		}

		if ($categories_id_count > 0) {
			$data['category_id'] = implode(',', $categories_id);
		} else {
			$data['category_id'] = null;
		}

		//Promo by Brand
		//get brand_id from view,
		$brands_id = $this->input->post('brand_id');

		//check id there is content inside brand array
		if (is_array($brands_id)) {
			$brands_id_count = count($brands_id);
		} else {
			$brands_id_count = 0;
		}

		if ($brands_id_count > 0) {
			$data['brand_id'] = implode(',', $brands_id);
		} else {
			$data['brand_id'] = null;
		}

		return $data;
	}

	private function table_data_processing_bundle(
		$title,
		$selled,
		$stock,
		$product_id,
		$price,
		$image,
		$status,
		$created_date
	) {
		$data = [
			'title' => $this->security->xss_clean($title),
			'selled' => $this->security->xss_clean($selled),
			'stock' => (int) $this->security->xss_clean($stock),
			'price' => (int) $this->security->xss_clean($price),
			'image' => $image,
			'status' => $status,
			'created_date' => $created_date,
		];
		$product_id = $this->input->post('product_id');

		//check id there is content inside category array
		if (is_array($product_id)) {
			$product_id_count = count($product_id);
		} else {
			$product_id_count = 0;
		}

		if ($product_id_count > 0) {
			$data['product_id'] = implode(',', $product_id);
		} else {
			$data['product_id'] = null;
		}



		return $data;
	}



	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');
		}
	}

	function ajax_get_attributes()
	{

		if (!$this->input->is_ajax_request()) {
			exit('No direct script access allowed');
		}

		$varian_id = $this->input->post('id_varian');
		//get all attribute details
		$this->db->select('id, attribute_detail')->from('product_attributes_detail')->where('product_attribute_id', $varian_id)->order_by('priority', 'ASC');
		$data['attributes'] = $this->db->get()->result();
		$this->load->view('admin/products/ajax_get_attributes', $data);
	}

	function upload_products()
	{

		if (!$_POST) {
			redirect('admin/products');
		}

		//ini hanya contoh saja, perlu di mofif sesuai excel yg baru...
		$config['upload_path']		= 'uploads/excel/';
		$config['allowed_types']	= 'xlsx|xls';

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

		if (!$this->upload->do_upload('userfile')) {
			$this->session->set_flashdata('error', '<p style="background:red; color:white; padding:5px; font-weight:bold;">' . strip_tags($this->upload->display_errors()) . '</p>');
			redirect('admin/products');
		} else {
			require_once APPPATH . 'third_party/PHPExcel/IOFactory.php';

			$data 			= array('upload_data' => $this->upload->data());
			$upload_data 	= $this->upload->data(); //Mengambil detail data yang di upload
			$filename 		= $upload_data['file_name']; //Nama File

			//ini_set('memory_limit', '-1');

			$inputFileName = 'uploads/excel/' . $filename;

			try {
				$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
			} catch (Exception $e) {
				die('Error loading file :' . $e->getMessage());
			}

			$worksheet	= $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
			$numRows 	= count($worksheet);

			for ($i = 1; $i < ($numRows + 1); $i++) {
				if ($i > 50) {
					break;
				}
				if ($i != 1) {
					$nama_product = $worksheet[$i]["A"];
					$sku = $worksheet[$i]["B"];
					$merek = $worksheet[$i]["C"];
					$kategori = $worksheet[$i]["D"];
					$harga_normal = $worksheet[$i]["E"];
					$harga_diskon = $worksheet[$i]["F"];
					$panjang_cm = $worksheet[$i]["G"];
					$lebar_cm = $worksheet[$i]["H"];
					$tinggi_cm = $worksheet[$i]["I"];
					$berat_cm = $worksheet[$i]["J"];
					$is_indent = $worksheet[$i]["K"];
					$varian = $worksheet[$i]["L"];
					$short_descr_id = $worksheet[$i]["M"];
					$short_descr_en = $worksheet[$i]["N"];
					$long_descr_id = $worksheet[$i]["O"];
					$long_descr_en = $worksheet[$i]["P"];
					$kurir_pengiriman = $worksheet[$i]["Q"];
					$is_new_arrivals = $worksheet[$i]["R"];
					$is_featured = $worksheet[$i]["S"];
					$is_best_sellers = $worksheet[$i]["T"];
					$seo_judul = $worksheet[$i]["U"];
					$seo_descr_meta = $worksheet[$i]["V"];
					$dp_produk_persen = $worksheet[$i]["W"];
					$durasi_info_indent = $worksheet[$i]["X"];
					$is_product_active = $worksheet[$i]["Y"];
					$is_restock = $worksheet[$i]["Z"];
					$is_exc = $worksheet[$i]["AA"];

					// query product
					$query_products = $this->db->get_where('products', array(
						'title' => $nama_product,
					));

					// query brands
					$query_brands = $this->db->get_where('brands', array(
						'brand' => $merek,
					));
					$id_brands = null;
					if ($query_brands->num_rows() > 0) {
						$id_brands = $query_brands->row()->id_brands;
					}

					// shipment method
					$output_kurir_pengiriman = '';
					$kurir_pengiriman = str_replace('.', ',', (string)$kurir_pengiriman);
					$id_kurir_pengiriman = explode(',', $kurir_pengiriman);
					// query shipment method
					for ($j = 0; $j < count($id_kurir_pengiriman); $j++) {
						$query_shipment_method = $this->db->get_where('shipment_method', array(
							'id' => $id_kurir_pengiriman[$j],
						));

						if ($query_shipment_method->num_rows() > 0) {
							$output_kurir_pengiriman .= $query_shipment_method->row()->name . ",";
						}
					}
					$output_kurir_pengiriman = substr($output_kurir_pengiriman, 0, -1);


					// data categories
					$data_group_categories = [];
					$group_categories = explode(', ', $kategori);
					$cntr_categories = -1;
					for ($j = 0; $j < count($group_categories); $j++) {
						$each_categories = explode('>', $group_categories[$j]);
						for ($k = 0; $k < count($each_categories); $k++) {
							$cntr_categories++;
							$data_group_categories[$cntr_categories] = $each_categories[$k];
						}
					}

					// data varian
					$data_group_varians = [];
					$group_varians = explode(', ', $varian);

					for ($j = 0; $j < count($group_varians); $j++) {
						$data_group_varians[$j] = explode('>', $group_varians[$j]);
					}

					// status produk
					if ($is_product_active == 'ya' || $is_product_active == 'yes') {
						$is_product_active = 1;
					} else {
						$is_product_active = 0;
					}

					// best seller
					if ($is_best_sellers == 'ya' || $is_best_sellers == 'yes') {
						$is_best_sellers = 'yes';
					} else {
						$is_best_sellers = 'no';
					}

					// restock
					if ($is_restock == 'ya' || $is_restock == 'yes') {
						$is_restock = 'yes';
					} else {
						$is_restock = 'no';
					}

					// eksklusif
					if ($is_exc == 'ya' || $is_exc == 'yes') {
						$is_exc = 'yes';
					} else {
						$is_exc = 'no';
					}

					// new arrivals
					if ($is_new_arrivals == 'ya' || $is_new_arrivals == 'yes') {
						$is_new_arrivals = 'yes';
					} else {
						$is_new_arrivals = 'no';
					}

					// featured
					if ($is_featured == 'ya' || $is_featured == 'yes') {
						$is_featured = 'yes';
					} else {
						$is_featured = 'no';
					}

					// is_indent
					if ($is_indent == 'ya' || $is_indent == 'yes') {
						$is_indent = 'yes';
					} else {
						$is_indent = 'no';
					}

					// data products
					$data_products = array(
						"brand_id" => $id_brands,
						"alias" => preg_replace('/\s+/', '-', $nama_product),
						"description" => $short_descr_id,
						"description_en" => $short_descr_en,
						"long_description" => $long_descr_id,
						"long_description_en" => $long_descr_en,
						"shipment_method" => $output_kurir_pengiriman,
						"best_seller" => $is_best_sellers,
						"restock" => $is_restock,
						"customer_id_exc" => $is_exc,
						"new_arrival" => $is_new_arrivals,
						"popular_product" => $is_featured,
						"indent_dp" => $dp_produk_persen,
						"meta_title" => $seo_judul,
						"meta_description" => $seo_descr_meta,
						"indent_time" => $durasi_info_indent,
						"product_status" => $is_product_active,
					);

					// data product details
					$data_product_details = array(
						"weight" => $berat_cm,
						"length" => $panjang_cm,
						"width" => $lebar_cm,
						"height" => $tinggi_cm,
						"price" => $harga_normal,
						"discounted_price" => $harga_diskon,
						"is_indent" => $is_indent,
					);

					$id_product = null;
					if ($query_products->num_rows() > 0) {
						// update products
						$id_product = $query_products->row()->id_products;
						$upd_products = $this->db->update("products", $data_products, array('title' => $nama_product));
					} else {
						// insert products
						$data_products['title'] = $nama_product;

						if ($data_products['title'] != null) {
							$this->db->insert("products", $data_products);
							$id_product = $this->db->insert_id();
						}
					}

					// query product details
					$query_product_details = $this->db->get_where(
						'product_details',
						array(
							'sku' => $sku,
						)
					);

					$id_product_details = null;
					if ($query_product_details->num_rows() > 0) {
						// update product details
						$id_product_details = $query_product_details->row()->id;
						$upd_products = $this->db->update("product_details", $data_product_details, array(
							'id' => $id_product_details,
							'sku' => $sku,
						));
					} else {
						// insert product details
						$data_product_details['sku'] = $sku;
						$data_product_details['product_id'] = $id_product;

						if ($data_product_details['weight'] != null) {
							$this->db->insert("product_details", $data_product_details);
							$id_product_details = $this->db->insert_id();
						}
					}

					if ($id_product != null) {
						// delete categories by id product
						if ($i <= 2) {
							$del_categories = $this->db->delete('category_product', array('id_product' => $id_product));
							$del_shipment = $this->db->delete('shipment_method_product', array('product_id' => $id_product));
						}
						for ($j = 0; $j < count($id_kurir_pengiriman); $j++) {
							// insert shipment product
							$query_check_shipment_product =
								$this->db->get_where('shipment_method_product', array(
									"product_id" => $id_product,
									"shipment_method_id" => $id_kurir_pengiriman[$j],
								));

							if ($query_check_shipment_product->num_rows() == 0) {
								$ins_shipment_product = $this->db->insert('shipment_method_product', array(
									"product_id" => $id_product,
									"shipment_method_id" => $id_kurir_pengiriman[$j],
								));
							}
						}

						for ($j = 0; $j < count($data_group_categories); $j++) {
							$this_val_for_search = strtolower($data_group_categories[$j]);

							$query_categories = $this->db->select('*')
								->from('categories')
								->where('category', $this_val_for_search)
								->or_where('category_en', $this_val_for_search)
								->or_where('alias', $this_val_for_search)
								->or_where('alias_en', $this_val_for_search)
								->get();

							if ($query_categories->num_rows() > 0) {
								$id_categories = $query_categories->row()->id_categories;

								// insert category product
								$ins_category_product = $this->db->insert('category_product', array(
									"id_product" => $id_product,
									"id_category" => $id_categories,
								));
							}
						}
					}

					if ($id_product != null && $id_product_details != null) {
						// delete varians by id product
						if ($i <= 2) {
							$del_varians = $this->db->delete('product_combination', array(
								'product_id' => $id_product,
								'product_details_id' => $id_product_details,
							));
						}

						for ($j = 0; $j < count($data_group_varians); $j++) {
							$key_product_attributes = strtolower($data_group_varians[$j][0]);
							$key_product_attributes_detail = strtolower($data_group_varians[$j][1]);

							$query_product_attributes = $this->db->select("*")
								->from("product_attributes")
								->where('product_attribute', $key_product_attributes)
								->or_where('product_attribute_en', $key_product_attributes)->get();

							if ($query_product_attributes->num_rows() > 0) {
								$attribute_id = $query_product_attributes->row()->id;

								$query_product_detail_attributes = $this->db->select("*")
									->from("product_attributes_detail")
									->where('attribute_detail', $key_product_attributes_detail)
									->or_where('attribute_detail_en', $key_product_attributes_detail)
									->where('product_attribute_id', $attribute_id)->get();

								if ($query_product_detail_attributes->num_rows() > 0) {
									$attribute_detail_id = $query_product_detail_attributes->row()->id;

									$ins_p_combination = $this->db->insert('product_combination', array(
										'product_id' => $id_product,
										'product_details_id' => $id_product_details,
										'attribute_id' => $attribute_id,
										'attribute_detail_id' => $attribute_detail_id,
									));
								}
							}
						}
					}
				}
			}

			unlink('uploads/excel/' . $filename);
			$this->session->set_flashdata('success', '<p style="background:green; color:white; padding:5px; font-weight:bold;">Upload produk Sukses</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
		$count = $this->db->select('id_products')->from('products')->where('id_products', $product_id)->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,
			'product_status' => '0',
			'new_arrival' => $current_product->new_arrival,
			'best_seller' => $current_product->best_seller,
			'restock' => $current_product->restock,
			'customer_id_exc' => $current_product->is_exc,
			'popular_product' => $current_product->popular_product,
			'meta_description' => $current_product->meta_description,
		);
		$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);
		}

		//Copy product details as well
		$current_product_details = $this->db->select('*')->from('product_details')->where('product_id', $product_id)->get()->result();

		foreach ($current_product_details as $detail) {
			$data = array(
				'product_id' => $new_product_id,
				'sku' => $detail->sku,
				'weight' => $detail->weight,
				'price' => $detail->price,
				'discounted_price' => $detail->discounted_price,
				'length' => $detail->length,
				'width' => $detail->width,
				'height' => $detail->height,
				'is_indent' => $detail->is_indent
			);
			$this->db->insert('product_details', $data);
			$new_product_detail_id = $this->db->insert_id();

			//get old product images for current product details
			$old_product_images = $this->db->select('*')->from('product_images')->where('product_id', $product_id)->where('product_details_id', $detail->id)->get()->result();

			foreach ($old_product_images as $old_image) {
				//insert into new image row
				$data = array(
					'product_id' => $new_product_id,
					'product_details_id' => $new_product_detail_id,
					'title' => $old_image->title,
					'title_en' => $old_image->title_en,
					'image' => $old_image->image,
					'status' => $old_image->status,
					'priority' => $old_image->priority,
					'alt' => $old_image->alt

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

			//insert new stock of 0 stock for each detail
			$data = array(
				'id_product' => $new_product_id,
				'id_product_detail' => $new_product_detail_id,
				'stock' => 0,
				'warehouse_id' => 1
			);
			$this->db->insert('stock', $data);
		}

		$user_id = $this->session->userdata('admin')['id'];
		$activity = 'User melakukan duplikat produk(' . $current_product_title . ')';

		log_activity($user_id, $activity);

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Produk berhasil di diduplikat. Sikahkan edit lebih lanjut.</p>');
		redirect('admin/products');
	}
}

https://t.me/RX1948 - 2025