<?php
class ControllerCatalogProduct extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('catalog/product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/product');

		$this->getList();
	}

	public function add() {
		$this->load->language('catalog/product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/product');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_catalog_product->addProduct($this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_price'])) {
				$url .= '&filter_price=' . $this->request->get['filter_price'];
			}

			if (isset($this->request->get['filter_quantity'])) {
				$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getForm();
	}

	public function edit() {
		$this->load->language('catalog/product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/product');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {

			$this->model_catalog_product->editProduct($this->request->get['product_id'], $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_price'])) {
				$url .= '&filter_price=' . $this->request->get['filter_price'];
			}

			if (isset($this->request->get['filter_quantity'])) {
				$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}
			
            $this->response->redirect($this->url->link('catalog/product/edit', 'user_token=' . $this->session->data['user_token'] . '&product_id=' . $this->request->get['product_id'], true));
		}

		$this->getForm();
	}

	public function delete() {
		$this->load->language('catalog/product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/product');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $product_id) {
				$this->model_catalog_product->deleteProduct($product_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_price'])) {
				$url .= '&filter_price=' . $this->request->get['filter_price'];
			}

			if (isset($this->request->get['filter_quantity'])) {
				$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getList();
	}

	public function copy() {
		$this->load->language('catalog/product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/product');

		if (isset($this->request->post['selected']) && $this->validateCopy()) {
			foreach ($this->request->post['selected'] as $product_id) {
				$this->model_catalog_product->copyProduct($product_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_price'])) {
				$url .= '&filter_price=' . $this->request->get['filter_price'];
			}

			if (isset($this->request->get['filter_quantity'])) {
				$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getList();
	}

	protected function getList() {
	    if (isset($this->request->get['filter_id'])) {
			$filter_id = $this->request->get['filter_id'];
		} else {
			$filter_id = '';
		}
		
		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
		} else {
			$filter_name = '';
		}

		if (isset($this->request->get['filter_model'])) {
			$filter_model = $this->request->get['filter_model'];
		} else {
			$filter_model = '';
		}

		if (isset($this->request->get['filter_price'])) {
			$filter_price = $this->request->get['filter_price'];
		} else {
			$filter_price = '';
		}

		if (isset($this->request->get['filter_quantity'])) {
			$filter_quantity = $this->request->get['filter_quantity'];
		} else {
			$filter_quantity = '';
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = '';
		}
		
		if (isset($this->request->get['filter_category_id'])) {
			$filter_category_id = $this->request->get['filter_category_id'];
		} else {
			$filter_category_id = '';
		}
		
		if (isset($this->request->get['filter_stock_status'])) {
			$filter_stock_status = $this->request->get['filter_stock_status'];
		} else {
			$filter_stock_status = '';
		}
		
		if (isset($this->request->get['filter_manufacture'])) {
			$filter_manufacture = $this->request->get['filter_manufacture'];
		} else {
			$filter_manufacture = '';
		}
		
		if (isset($this->request->get['filter_attribute_id'])) {
			$filter_attribute_id = $this->request->get['filter_attribute_id'];
		} else {
			$filter_attribute_id = '';
		}
		
		if (isset($this->request->get['filter_attribute_group_id'])) {
			$filter_attribute_group_id = $this->request->get['filter_attribute_group_id'];
		} else {
			$filter_attribute_group_id = '';
		}
		
		if (isset($this->request->get['filter_filter_group_id'])) {
			$filter_filter_group_id = $this->request->get['filter_filter_group_id'];
		} else {
			$filter_filter_group_id = '';
		}
		
		if (isset($this->request->get['filter_filter_id'])) {
			$filter_filter_id = $this->request->get['filter_filter_id'];
		} else {
			$filter_filter_id = '';
		}
		
		if (isset($this->request->get['filter_option_id'])) {
			$filter_option_id = $this->request->get['filter_option_id'];
		} else {
			$filter_option_id = '';
		}
		
		if (isset($this->request->get['filter_option_value_id'])) {
			$filter_option_value_id = $this->request->get['filter_option_value_id'];
		} else {
			$filter_option_value_id = '';
		}
		
		if (isset($this->request->get['filter_added_by'])) {
			$filter_added_by = $this->request->get['filter_added_by'];
		} else {
			$filter_added_by = '';
		}
		
		if (isset($this->request->get['filter_date_added_from'])) {
            $filter_date_added_from = $this->request->get['filter_date_added_from'];
        } else {
            $filter_date_added_from = '';
        }
        
        if (isset($this->request->get['filter_date_added_to'])) {
            $filter_date_added_to = $this->request->get['filter_date_added_to'];
        } else {
            $filter_date_added_to = '';
        }

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'p.product_id';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'DESC';
		}

		if (isset($this->request->get['page'])) {
			$page = (int)$this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}
		
		if (isset($this->request->get['filter_category_id'])) {
			$url .= '&filter_category_id=' . $this->request->get['filter_category_id'];
		}
		
		if (isset($this->request->get['filter_stock_status'])) {
			$url .= '&filter_stock_status=' . $this->request->get['filter_stock_status'];
		}
		
		if (isset($this->request->get['filter_manufacture'])) {
			$url .= '&filter_manufacture=' . $this->request->get['filter_manufacture'];
		}
		
		if (isset($this->request->get['filter_attribute_id'])) {
			$url .= '&filter_attribute_id=' . $this->request->get['filter_attribute_id'];
		}
		
		if (isset($this->request->get['filter_attribute_group_id'])) {
			$url .= '&filter_attribute_group_id=' . $this->request->get['filter_attribute_group_id'];
		}
		
		if (isset($this->request->get['filter_filter_group_id'])) {
			$url .= '&filter_filter_group_id=' . $this->request->get['filter_filter_group_id'];
		}
		
		if (isset($this->request->get['filter_filter_id'])) {
			$url .= '&filter_filter_id=' . $this->request->get['filter_filter_id'];
		}
		
		if (isset($this->request->get['filter_option_id'])) {
			$url .= '&filter_option_id=' . $this->request->get['filter_option_id'];
		}
		
		if (isset($this->request->get['filter_option_value_id'])) {
			$url .= '&filter_option_value_id=' . $this->request->get['filter_option_value_id'];
		}
		
		if (isset($this->request->get['filter_added_by'])) {
			$url .= '&filter_added_by=' . $this->request->get['filter_added_by'];
		}
		
		if (isset($this->request->get['filter_date_added_from'])) {
			$url .= '&filter_date_added_from=' . $this->request->get['filter_date_added_from'];
		}
		
		if (isset($this->request->get['filter_date_added_to'])) {
			$url .= '&filter_date_added_to=' . $this->request->get['filter_date_added_to'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

		$data['add'] = $this->url->link('catalog/product/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$data['copy'] = $this->url->link('catalog/product/copy', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$data['delete'] = $this->url->link('catalog/product/delete', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$data['download'] = $this->url->link('catalog/product/download', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$data['config_product_download'] = $this->config->get('config_product_download') ?? 0;

		$data['products'] = array();

		$filter_data = array(
		    'filter_id'	  => $filter_id,
			'filter_name'	  => $filter_name,
			'filter_model'	  => $filter_model,
			'filter_price'	  => $filter_price,
			'filter_quantity' => $filter_quantity,
			'filter_status'   => $filter_status,
			'filter_category_id' => $filter_category_id,
			'filter_stock_status' => $filter_stock_status,
			'filter_manufacture' => $filter_manufacture,
			'filter_attribute_id' => $filter_attribute_id,
			'filter_attribute_group_id' => $filter_attribute_group_id,
			'filter_filter_id'   => $filter_filter_id,
			'filter_filter_group_id' => $filter_filter_group_id,
			'filter_option_id' => $filter_option_id,
			'filter_option_value_id' => $filter_option_value_id,
			'filter_added_by' => $filter_added_by,
			'filter_date_added_from' => $filter_date_added_from,
			'filter_date_added_to' => $filter_date_added_to,
			'sort'            => $sort,
			'order'           => $order,
			'start'           => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'           => $this->config->get('config_limit_admin')
		);

		$this->load->model('tool/image');

		$product_total = $this->model_catalog_product->getTotalProducts($filter_data);

		$results = $this->model_catalog_product->getProducts($filter_data);

		foreach ($results as $result) {
			if (is_file(DIR_IMAGE . $result['image'])) {
				$image = $this->model_tool_image->resize($result['image'], 40, 40);
			} else {
				$image = $this->model_tool_image->resize('no_image.png', 40, 40);
			}

			$special = false;

			$product_specials = $this->model_catalog_product->getProductSpecials($result['product_id']);

			foreach ($product_specials  as $product_special) {
				if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
					$special = $this->currency->format($product_special['price'], $this->config->get('config_currency'));

					break;
				}
			}
			
			$added_user = '';
			$added_by = $result['added_by'];
			if($added_by){
			    $user_info = $this->db->query("SELECT firstname, lastname FROM " . DB_PREFIX . "user WHERE user_id = '" . $added_by . "'")->row;
			    if(!empty($user_info)){
			        $added_user = $user_info['firstname'].' '.$user_info['lastname'];
			    }
			}
			
			$updated_user = '';
			$updated_by = $result['updated_by'];
			if($updated_by){
			    $user_info = $this->db->query("SELECT firstname, lastname FROM " . DB_PREFIX . "user WHERE user_id = '" . $updated_by . "'")->row;
			    if(!empty($user_info)){
			        $updated_user = $user_info['firstname'].' '.$user_info['lastname'];
			    }
			}
			$stock_status_id = $result['stock_status_id'];
			$stock_status = '';
			$stock_info = $this->db->query("SELECT name FROM " . DB_PREFIX . "stock_status WHERE stock_status_id = '" . $stock_status_id . "'")->row;
		    if(!empty($stock_info)){
		        $stock_status = $stock_info['name'];
		    }
		    
		    $full_data = $this->model_catalog_product->getProductFullData($result['product_id']);
            $product_strength = $this->calculateProductStrength($full_data);
            $product_seo = $this->getProductSeoScore($full_data);
            
            $full_url = HTTPS_CATALOG . $full_data['seo_keyword'];
		
            $category =  $this->model_catalog_product->getProductCategories($result['product_id']);
            
			$data['products'][] = array(
				'product_id' => $result['product_id'],
				'image'      => $image,
				'name'       => $result['name'],
				'model'      => $result['model'],
				'category'   => $category,
				'price'      => $this->currency->format($result['price'], $this->config->get('config_currency')),
				'special'    => $special,
				'quantity'   => $result['quantity'],
				'viewed'     => $result['viewed'],
				'date_added' => date('d-m-Y, h:i A', strtotime($result['date_added'])),
				'date_modified' => date('d-m-Y, h:i A', strtotime($result['date_modified'])),
				'added_by' => $added_user,
				'updated_by' => $updated_user,
				'stock_status' => $stock_status,
				'subtract' => $result['subtract'],
				'status'     => $result['status'],
				'product_strength_total_score'       => $product_strength['total_score'],
                'product_strength_out_of'       => $product_strength['out_of'],
                'product_strength_details'       => $product_strength['details'],
                'product_seo_total_score'       => $product_seo['total_score'],
                'product_seo_out_of'       => $product_seo['out_of'],
                'product_seo_details'       => $product_seo['details'],
				'edit'       => $this->url->link('catalog/product/edit', 'user_token=' . $this->session->data['user_token'] . '&product_id=' . $result['product_id'] . $url, true),
				'view'             => HTTP_CATALOG.'index.php?route=product/product&product_id=' . $result['product_id'],
				'google_search' => 'https://www.google.com/search?q='. $result['name'],
                'google_index_check' => 'https://www.google.com/search?q=site:' . urlencode($full_url),
			);
		}
		
		$data['user_token'] = $this->session->data['user_token'];

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		if (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}
		
		if (isset($this->request->get['filter_category_id'])) {
			$url .= '&filter_category_id=' . $this->request->get['filter_category_id'];
		}
		
		if (isset($this->request->get['filter_stock_status'])) {
			$url .= '&filter_stock_status=' . $this->request->get['filter_stock_status'];
		}
		
		if (isset($this->request->get['filter_manufacture'])) {
			$url .= '&filter_manufacture=' . $this->request->get['filter_manufacture'];
		}
		
		if (isset($this->request->get['filter_attribute_id'])) {
			$url .= '&filter_attribute_id=' . $this->request->get['filter_attribute_id'];
		}
		
		if (isset($this->request->get['filter_attribute_group_id'])) {
			$url .= '&filter_attribute_group_id=' . $this->request->get['filter_attribute_group_id'];
		}
		
		if (isset($this->request->get['filter_filter_id'])) {
			$url .= '&filter_filter_id=' . $this->request->get['filter_filter_id'];
		}
		
		if (isset($this->request->get['filter_filter_group_id'])) {
			$url .= '&filter_filter_group_id=' . $this->request->get['filter_filter_group_id'];
		}
		
		if (isset($this->request->get['filter_option_id'])) {
			$url .= '&filter_option_id=' . $this->request->get['filter_option_id'];
		}
		
		if (isset($this->request->get['filter_option_value_id'])) {
			$url .= '&filter_option_value_id=' . $this->request->get['filter_option_value_id'];
		}
		
		if (isset($this->request->get['filter_added_by'])) {
			$url .= '&filter_added_by=' . $this->request->get['filter_added_by'];
		}
		
		if (isset($this->request->get['filter_date_added_from'])) {
			$url .= '&filter_date_added_from=' . $this->request->get['filter_date_added_from'];
		}
		
		if (isset($this->request->get['filter_date_added_to'])) {
			$url .= '&filter_date_added_to=' . $this->request->get['filter_date_added_to'];
		}

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['sort_name'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=pd.name' . $url, true);
		$data['sort_model'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.model' . $url, true);
		$data['sort_price'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.price' . $url, true);
		$data['sort_quantity'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.quantity' . $url, true);
		$data['sort_status'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.status' . $url, true);
		$data['sort_order'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.sort_order' . $url, true);

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}
		
		if (isset($this->request->get['filter_category_id'])) {
			$url .= '&filter_category_id=' . $this->request->get['filter_category_id'];
		}
		
		if (isset($this->request->get['filter_stock_status'])) {
			$url .= '&filter_stock_status=' . $this->request->get['filter_stock_status'];
		}
		
		if (isset($this->request->get['filter_manufacture'])) {
			$url .= '&filter_manufacture=' . $this->request->get['filter_manufacture'];
		}
		
		if (isset($this->request->get['filter_attribute_id'])) {
			$url .= '&filter_attribute_id=' . $this->request->get['filter_attribute_id'];
		}
		
		if (isset($this->request->get['filter_attribute_id'])) {
			$url .= '&filter_attribute_id=' . $this->request->get['filter_attribute_id'];
		}
		
		if (isset($this->request->get['filter_attribute_group_id'])) {
			$url .= '&filter_attribute_group_id=' . $this->request->get['filter_attribute_group_id'];
		}
		
		if (isset($this->request->get['filter_filter_group_id'])) {
			$url .= '&filter_filter_group_id=' . $this->request->get['filter_filter_group_id'];
		}
		
		if (isset($this->request->get['filter_option_id'])) {
			$url .= '&filter_option_id=' . $this->request->get['filter_option_id'];
		}
		
		if (isset($this->request->get['filter_option_value_id'])) {
			$url .= '&filter_option_value_id=' . $this->request->get['filter_option_value_id'];
		}
		
		if (isset($this->request->get['filter_added_by'])) {
			$url .= '&filter_added_by=' . $this->request->get['filter_added_by'];
		}
		
		if (isset($this->request->get['filter_date_added_from'])) {
			$url .= '&filter_date_added_from=' . $this->request->get['filter_date_added_from'];
		}
		
		if (isset($this->request->get['filter_date_added_to'])) {
			$url .= '&filter_date_added_to=' . $this->request->get['filter_date_added_to'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $product_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url . '&page={page}', true);

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($product_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($product_total - $this->config->get('config_limit_admin'))) ? $product_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $product_total, ceil($product_total / $this->config->get('config_limit_admin')));
        
        $data['filter_id'] = $filter_id;
		$data['filter_name'] = $filter_name;
		$data['filter_category_id'] = $filter_category_id;
		$data['filter_stock_status'] = $filter_stock_status;
		$data['filter_manufacture'] = $filter_manufacture;
		$data['filter_model'] = $filter_model;
		$data['filter_price'] = $filter_price;
		$data['filter_quantity'] = $filter_quantity;
		$data['filter_status'] = $filter_status;
		$data['filter_added_by'] = $filter_added_by;
		$data['filter_date_added_from'] = $filter_date_added_from;
		$data['filter_date_added_to'] = $filter_date_added_to;

		$data['sort'] = $sort;
		$data['order'] = $order;
		
		if($filter_category_id){
		    $this->load->model('catalog/category');
		    $category_info = $this->model_catalog_category->getCategory($filter_category_id);
		    $path = ($category_info['path']) ? $category_info['path'] . ' &gt; ' . $category_info['name'] : $category_info['name'];
		    $data['path'] = $path;
		}else{
		    $data['path'] = '';
		}
		
		if($filter_manufacture){
		    $this->load->model('catalog/manufacturer');
		    $manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($filter_manufacture);
		    $data['manufacturer'] = $manufacturer_info['name'];
		}else{
		    $data['manufacturer'] = '';
		}
		
		if($filter_added_by){
		    $this->load->model('user/user');
		    $user_info = $this->model_user_user->getUser($filter_added_by);
		    $data['users'] = $user_info['username'];
		}else{
		    $data['users'] = '';
		}
		
		$this->load->model('catalog/category');
		$data['categories'] = $this->model_catalog_category->getCategories(['sort' => 'name', 'order' => 'ASC',]);
		
		$this->load->model('localisation/stock_status');
        $data['stock_statuses'] = $this->model_localisation_stock_status->getStockStatuses();

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('catalog/product_list', $data));
	}

	protected function getForm() {
	    $data['light_attribute_helper'] = $this->load->controller('extension/light_attribute_helper/template_product');
		$data['text_form'] = !isset($this->request->get['product_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['name'])) {
			$data['error_name'] = $this->error['name'];
		} else {
			$data['error_name'] = array();
		}

		if (isset($this->error['meta_title'])) {
			$data['error_meta_title'] = $this->error['meta_title'];
		} else {
			$data['error_meta_title'] = array();
		}

		if (isset($this->error['model'])) {
			$data['error_model'] = $this->error['model'];
		} else {
			$data['error_model'] = '';
		}

		if (isset($this->error['keyword'])) {
			$data['error_keyword'] = $this->error['keyword'];
		} else {
			$data['error_keyword'] = '';
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

		if (!isset($this->request->get['product_id'])) {
			$data['action'] = $this->url->link('catalog/product/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
		} else {
			$data['action'] = $this->url->link('catalog/product/edit', 'user_token=' . $this->session->data['user_token'] . '&product_id=' . $this->request->get['product_id'] . $url, true);
		}

		$data['cancel'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url, true);

		if (isset($this->request->get['product_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$product_info = $this->model_catalog_product->getProduct($this->request->get['product_id']);
		}

		$data['user_token'] = $this->session->data['user_token'];

		$this->load->model('localisation/language');

		$data['languages'] = $this->model_localisation_language->getLanguages();

		if (isset($this->request->post['product_description'])) {
			$data['product_description'] = $this->request->post['product_description'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_description'] = $this->model_catalog_product->getProductDescriptions($this->request->get['product_id']);
		} else {
			$data['product_description'] = array();
		}
		
		//product seo content start
        if (isset($this->request->post['product_seo_content'])) {
            $data['product_seo_content'] = $this->request->post['product_seo_content'];
        } elseif (isset($this->request->get['product_id'])) {
            $this->load->model('extension/module/product_seo_content');                 
            $data['product_seo_content'] = $this->model_extension_module_product_seo_content->get_desrc_product($this->request->get['product_id']);
        } else {
            $data['product_seo_content'] = array();       
        }
        //product seo content end

		if (isset($this->request->post['model'])) {
			$data['model'] = $this->request->post['model'];
		} elseif (!empty($product_info)) {
			$data['model'] = $product_info['model'];
		} else {
			$data['model'] = '';
		}

		if (isset($this->request->post['sku'])) {
			$data['sku'] = $this->request->post['sku'];
		} elseif (!empty($product_info)) {
			$data['sku'] = $product_info['sku'];
		} else {
			$data['sku'] = '';
		}

		if (isset($this->request->post['upc'])) {
			$data['upc'] = $this->request->post['upc'];
		} elseif (!empty($product_info)) {
			$data['upc'] = $product_info['upc'];
		} else {
			$data['upc'] = '';
		}

		if (isset($this->request->post['ean'])) {
			$data['ean'] = $this->request->post['ean'];
		} elseif (!empty($product_info)) {
			$data['ean'] = $product_info['ean'];
		} else {
			$data['ean'] = '';
		}

		if (isset($this->request->post['jan'])) {
			$data['jan'] = $this->request->post['jan'];
		} elseif (!empty($product_info)) {
			$data['jan'] = $product_info['jan'];
		} else {
			$data['jan'] = '';
		}

		if (isset($this->request->post['isbn'])) {
			$data['isbn'] = $this->request->post['isbn'];
		} elseif (!empty($product_info)) {
			$data['isbn'] = $product_info['isbn'];
		} else {
			$data['isbn'] = '';
		}

		if (isset($this->request->post['mpn'])) {
			$data['mpn'] = $this->request->post['mpn'];
		} elseif (!empty($product_info)) {
			$data['mpn'] = $product_info['mpn'];
		} else {
			$data['mpn'] = '';
		}

		if (isset($this->request->post['location'])) {
			$data['location'] = $this->request->post['location'];
		} elseif (!empty($product_info)) {
			$data['location'] = $product_info['location'];
		} else {
			$data['location'] = '';
		}

		$this->load->model('setting/store');

		$data['stores'] = array();

		$data['stores'][] = array(
			'store_id' => 0,
			'name'     => $this->language->get('text_default')
		);

		$stores = $this->model_setting_store->getStores();

		foreach ($stores as $store) {
			$data['stores'][] = array(
				'store_id' => $store['store_id'],
				'name'     => $store['name']
			);
		}

		if (isset($this->request->post['product_store'])) {
			$data['product_store'] = $this->request->post['product_store'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_store'] = $this->model_catalog_product->getProductStores($this->request->get['product_id']);
		} else {
			$data['product_store'] = array(0);
		}

		if (isset($this->request->post['shipping'])) {
			$data['shipping'] = $this->request->post['shipping'];
		} elseif (!empty($product_info)) {
			$data['shipping'] = $product_info['shipping'];
		} else {
			$data['shipping'] = 1;
		}

		if (isset($this->request->post['price'])) {
			$data['price'] = $this->request->post['price'];
		} elseif (!empty($product_info)) {
			$data['price'] = $product_info['price'];
		} else {
			$data['price'] = '';
		}

		$this->load->model('catalog/recurring');

		$data['recurrings'] = $this->model_catalog_recurring->getRecurrings();

		if (isset($this->request->post['product_recurrings'])) {
			$data['product_recurrings'] = $this->request->post['product_recurrings'];
		} elseif (!empty($product_info)) {
			$data['product_recurrings'] = $this->model_catalog_product->getRecurrings($product_info['product_id']);
		} else {
			$data['product_recurrings'] = array();
		}

		$this->load->model('localisation/tax_class');

		$data['tax_classes'] = $this->model_localisation_tax_class->getTaxClasses();

		if (isset($this->request->post['tax_class_id'])) {
			$data['tax_class_id'] = $this->request->post['tax_class_id'];
		} elseif (!empty($product_info)) {
			$data['tax_class_id'] = $product_info['tax_class_id'];
		} else {
			$data['tax_class_id'] = 0;
		}

		if (isset($this->request->post['date_available'])) {
			$data['date_available'] = $this->request->post['date_available'];
		} elseif (!empty($product_info)) {
			$data['date_available'] = ($product_info['date_available'] != '0000-00-00') ? $product_info['date_available'] : '';
		} else {
			$data['date_available'] = date('Y-m-d');
		}

		if (isset($this->request->post['quantity'])) {
			$data['quantity'] = $this->request->post['quantity'];
		} elseif (!empty($product_info)) {
			$data['quantity'] = $product_info['quantity'];
		} else {
			$data['quantity'] = 100;
		}

		if (isset($this->request->post['minimum'])) {
			$data['minimum'] = $this->request->post['minimum'];
		} elseif (!empty($product_info)) {
			$data['minimum'] = $product_info['minimum'];
		} else {
			$data['minimum'] = 1;
		}

		if (isset($this->request->post['subtract'])) {
			$data['subtract'] = $this->request->post['subtract'];
		} elseif (!empty($product_info)) {
			$data['subtract'] = $product_info['subtract'];
		} else {
			$data['subtract'] = 1;
		}

		if (isset($this->request->post['sort_order'])) {
			$data['sort_order'] = $this->request->post['sort_order'];
		} elseif (!empty($product_info)) {
			$data['sort_order'] = $product_info['sort_order'];
		} else {
			$data['sort_order'] = 1;
		}

		$this->load->model('localisation/stock_status');

		$data['stock_statuses'] = $this->model_localisation_stock_status->getStockStatuses();

		if (isset($this->request->post['stock_status_id'])) {
			$data['stock_status_id'] = $this->request->post['stock_status_id'];
		} elseif (!empty($product_info)) {
			$data['stock_status_id'] = $product_info['stock_status_id'];
		} else {
			$data['stock_status_id'] = 0;
		}

		if (isset($this->request->post['status'])) {
			$data['status'] = $this->request->post['status'];
		} elseif (!empty($product_info)) {
			$data['status'] = $product_info['status'];
		} else {
			$data['status'] = true;
		}

		if (isset($this->request->post['weight'])) {
			$data['weight'] = $this->request->post['weight'];
		} elseif (!empty($product_info)) {
			$data['weight'] = $product_info['weight'];
		} else {
			$data['weight'] = '';
		}

		$this->load->model('localisation/weight_class');

		$data['weight_classes'] = $this->model_localisation_weight_class->getWeightClasses();

		if (isset($this->request->post['weight_class_id'])) {
			$data['weight_class_id'] = $this->request->post['weight_class_id'];
		} elseif (!empty($product_info)) {
			$data['weight_class_id'] = $product_info['weight_class_id'];
		} else {
			$data['weight_class_id'] = $this->config->get('config_weight_class_id');
		}

		if (isset($this->request->post['length'])) {
			$data['length'] = $this->request->post['length'];
		} elseif (!empty($product_info)) {
			$data['length'] = $product_info['length'];
		} else {
			$data['length'] = '';
		}

		if (isset($this->request->post['width'])) {
			$data['width'] = $this->request->post['width'];
		} elseif (!empty($product_info)) {
			$data['width'] = $product_info['width'];
		} else {
			$data['width'] = '';
		}

		if (isset($this->request->post['height'])) {
			$data['height'] = $this->request->post['height'];
		} elseif (!empty($product_info)) {
			$data['height'] = $product_info['height'];
		} else {
			$data['height'] = '';
		}

		$this->load->model('localisation/length_class');

		$data['length_classes'] = $this->model_localisation_length_class->getLengthClasses();

		if (isset($this->request->post['length_class_id'])) {
			$data['length_class_id'] = $this->request->post['length_class_id'];
		} elseif (!empty($product_info)) {
			$data['length_class_id'] = $product_info['length_class_id'];
		} else {
			$data['length_class_id'] = $this->config->get('config_length_class_id');
		}

		$this->load->model('catalog/manufacturer');

		if (isset($this->request->post['manufacturer_id'])) {
			$data['manufacturer_id'] = $this->request->post['manufacturer_id'];
		} elseif (!empty($product_info)) {
			$data['manufacturer_id'] = $product_info['manufacturer_id'];
		} else {
			$data['manufacturer_id'] = 0;
		}

		if (isset($this->request->post['manufacturer'])) {
			$data['manufacturer'] = $this->request->post['manufacturer'];
		} elseif (!empty($product_info)) {
			$manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($product_info['manufacturer_id']);

			if ($manufacturer_info) {
				$data['manufacturer'] = $manufacturer_info['name'];
			} else {
				$data['manufacturer'] = '';
			}
		} else {
			$data['manufacturer'] = '';
		}

		// Categories
		$this->load->model('catalog/category');

		if (isset($this->request->post['product_category'])) {
			$categories = $this->request->post['product_category'];
		} elseif (isset($this->request->get['product_id'])) {
			$categories = $this->model_catalog_product->getProductCategories($this->request->get['product_id']);
		} else {
			$categories = array();
		}

		$data['product_categories'] = array();

		foreach ($categories as $category_id) {
			$category_info = $this->model_catalog_category->getCategory($category_id);

			if ($category_info) {
				$data['product_categories'][] = array(
					'category_id' => $category_info['category_id'],
					'name'        => ($category_info['path']) ? $category_info['path'] . ' &gt; ' . $category_info['name'] : $category_info['name']
				);
			}
		}

		// Filters
		$this->load->model('catalog/filter');

		if (isset($this->request->post['product_filter'])) {
			$filters = $this->request->post['product_filter'];
		} elseif (isset($this->request->get['product_id'])) {
			$filters = $this->model_catalog_product->getProductFilters($this->request->get['product_id']);
		} else {
			$filters = array();
		}
		
		$selected_filter_ids = array();
        foreach ($filters as $filter_id) {
            $selected_filter_ids[] = (int)$filter_id;
        }
        $data['selected_filter_ids'] = $selected_filter_ids;
		
        $data['selected_filters_grouped'] = [];

        foreach ($filters as $filter_id) {
            $filter_info = $this->model_catalog_filter->getFilterforFilter($filter_id);
            if ($filter_info) {
                $group_name = $filter_info['group_name'] ?? 'Other';
        
                if (!isset($data['selected_filters_grouped'][$group_name])) {
                    $data['selected_filters_grouped'][$group_name] = [];
                }
        
                $data['selected_filters_grouped'][$group_name][] = [
                    'filter_id' => $filter_info['filter_id'],
                    'name'      => $filter_info['name']
                ];
            }
        }
        
        $this->document->addStyle('view/stylesheet/lib-customize/customize.css');
        $data['product_filters_all'] = array();
		if (isset($this->request->get['product_id'])) {
            $product_categories = $this->model_catalog_product->getProductCategories($this->request->get['product_id']);
            
            $filter_ids = $this->model_catalog_product->getUniqueProductFilters($this->request->get['product_id']);
            if($filter_ids){
                $filter_ids_array = explode(',', $filter_ids);
            }else{
                $filter_ids_array = array();
            }
            $grouped_filters = array();
            
            foreach ($product_categories as $category_id) {
                $category_filters = $this->model_catalog_filter->getFiltersByCategoryId($category_id);
                foreach ($category_filters as $category_filter) {
                    $filter_info = $this->model_catalog_filter->getFilter($category_filter['filter_id']);
                    if ($filter_info) {
                        $group_name = $filter_info['group'];
                        $filter_id = $filter_info['filter_id'];
            
                        if (!isset($grouped_filters[$group_name])) {
                            $grouped_filters[$group_name] = array(
                                'group' => $group_name,
                                'filters' => array()
                            );
                        }
                        
                        $filter_exists = false;
                        foreach ($grouped_filters[$group_name]['filters'] as $existing_filter) {
                            if ($existing_filter['filter_id'] == $filter_id) {
                                $filter_exists = true;
                                break;
                            }
                        }
                        
                        if (!$filter_exists) {
                            $grouped_filters[$group_name]['filters'][] = array(
                                'name'      => $filter_info['name'],
                                'filter_id' => $filter_id,
                                'selected'  => (in_array($filter_id, $filter_ids_array)) ? 'checked' : ''
                            );
                        }
                    }
                }
            }
            
            // Flatten grouped filters into the final data array
            foreach ($grouped_filters as $group_info) {
                $data['product_filters_all'][] = $group_info;
            }
        }
        
        // Your $data['product_filters_all'] now contains filters grouped by their group names.
        
// 		$data['product_filters'] = array();

// 		foreach ($filters as $filter_id) {
// 			$filter_info = $this->model_catalog_filter->getFilter($filter_id);

// 			if ($filter_info) {
// 				$data['product_filters'][] = array(
// 					'filter_id' => $filter_info['filter_id'],
// 					'name'      => $filter_info['group'] . ' &gt; ' . $filter_info['name']
// 				);
// 			}
// 		}

		// Attributes
		$this->load->model('catalog/attribute');

		if (isset($this->request->post['product_attribute'])) {
			$product_attributes = $this->request->post['product_attribute'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_attributes = $this->model_catalog_product->getProductAttributes($this->request->get['product_id']);
		} else {
			$product_attributes = array();
		}

		$data['product_attributes'] = array();

		foreach ($product_attributes as $product_attribute) {
			$attribute_info = $this->model_catalog_attribute->getAttribute($product_attribute['attribute_id']);

			if ($attribute_info) {
				$data['product_attributes'][] = array(
					'attribute_id'                  => $product_attribute['attribute_id'],
					'name'                          => $attribute_info['name'],
					'product_attribute_description' => $product_attribute['product_attribute_description']
				);
			}
		}

		// Options
		$this->load->model('catalog/option');

		if (isset($this->request->post['product_option'])) {
			$product_options = $this->request->post['product_option'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_options = $this->model_catalog_product->getProductOptions($this->request->get['product_id']);
		} else {
			$product_options = array();
		}

		$data['product_options'] = array();

		foreach ($product_options as $product_option) {
			$product_option_value_data = array();

			if (isset($product_option['product_option_value'])) {
				foreach ($product_option['product_option_value'] as $product_option_value) {
					$product_option_value_data[] = array(
						'product_option_value_id' => $product_option_value['product_option_value_id'],
						'option_value_id'         => $product_option_value['option_value_id'],
						'quantity'                => $product_option_value['quantity'],
						'subtract'                => $product_option_value['subtract'],
						'price'                   => $product_option_value['price'],
						'price_prefix'            => $product_option_value['price_prefix'],
						'points'                  => $product_option_value['points'],
						'points_prefix'           => $product_option_value['points_prefix'],
						'weight'                  => $product_option_value['weight'],
						'weight_prefix'           => $product_option_value['weight_prefix']
					);
				}
			}

			$data['product_options'][] = array(
				'product_option_id'    => $product_option['product_option_id'],
				'product_option_value' => $product_option_value_data,
				'option_id'            => $product_option['option_id'],
				'name'                 => $product_option['name'],
				'type'                 => $product_option['type'],
				'value'                => isset($product_option['value']) ? $product_option['value'] : '',
				'required'             => $product_option['required']
			);
		}

		$data['option_values'] = array();

		foreach ($data['product_options'] as $product_option) {
			if ($product_option['type'] == 'select' || $product_option['type'] == 'radio' || $product_option['type'] == 'checkbox' || $product_option['type'] == 'image') {
				if (!isset($data['option_values'][$product_option['option_id']])) {
					$data['option_values'][$product_option['option_id']] = $this->model_catalog_option->getOptionValues($product_option['option_id']);
				}
			}
		}

		$this->load->model('customer/customer_group');

		$data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();

		if (isset($this->request->post['product_discount'])) {
			$product_discounts = $this->request->post['product_discount'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_discounts = $this->model_catalog_product->getProductDiscounts($this->request->get['product_id']);
		} else {
			$product_discounts = array();
		}

		$data['product_discounts'] = array();

		foreach ($product_discounts as $product_discount) {
			$data['product_discounts'][] = array(
				'customer_group_id' => $product_discount['customer_group_id'],
				'quantity'          => $product_discount['quantity'],
				'priority'          => $product_discount['priority'],
				'price'             => $product_discount['price'],
				'date_start'        => ($product_discount['date_start'] != '0000-00-00') ? $product_discount['date_start'] : '',
				'date_end'          => ($product_discount['date_end'] != '0000-00-00') ? $product_discount['date_end'] : ''
			);
		}

		if (isset($this->request->post['product_special'])) {
			$product_specials = $this->request->post['product_special'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_specials = $this->model_catalog_product->getProductSpecials($this->request->get['product_id']);
		} else {
			$product_specials = array();
		}

		$data['product_specials'] = array();

		foreach ($product_specials as $product_special) {
			$data['product_specials'][] = array(
				'customer_group_id' => $product_special['customer_group_id'],
				'priority'          => $product_special['priority'],
				'price'             => $product_special['price'],
				'date_start'        => ($product_special['date_start'] != '0000-00-00') ? $product_special['date_start'] : '',
				'date_end'          => ($product_special['date_end'] != '0000-00-00') ? $product_special['date_end'] :  ''
			);
		}

		// Image
		if (isset($this->request->post['image'])) {
			$data['image'] = $this->request->post['image'];
		} elseif (!empty($product_info)) {
			$data['image'] = $product_info['image'];
		} else {
			$data['image'] = '';
		}

		$this->load->model('tool/image');

		if (isset($this->request->post['image']) && is_file(DIR_IMAGE . $this->request->post['image'])) {
			$data['thumb'] = $this->model_tool_image->resize($this->request->post['image'], 100, 100);
		} elseif (!empty($product_info) && is_file(DIR_IMAGE . $product_info['image'])) {
			$data['thumb'] = $this->model_tool_image->resize($product_info['image'], 100, 100);
		} else {
			$data['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
		}

		$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);

		// Images
		if (isset($this->request->post['product_image'])) {
			$product_images = $this->request->post['product_image'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_images = $this->model_catalog_product->getProductImages($this->request->get['product_id']);
		} else {
			$product_images = array();
		}

		$data['product_images'] = array();

		foreach ($product_images as $product_image) {
			if (is_file(DIR_IMAGE . $product_image['image'])) {
				$image = $product_image['image'];
				$thumb = $product_image['image'];
			} else {
				$image = '';
				$thumb = 'no_image.png';
			}

			$data['product_images'][] = array(
				'image'      => $image,
				'thumb'      => $this->model_tool_image->resize($thumb, 100, 100),
				'sort_order' => $product_image['sort_order']
			);
		}

		// Downloads
		$this->load->model('catalog/download');

		if (isset($this->request->post['product_download'])) {
			$product_downloads = $this->request->post['product_download'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_downloads = $this->model_catalog_product->getProductDownloads($this->request->get['product_id']);
		} else {
			$product_downloads = array();
		}

		$data['product_downloads'] = array();

		foreach ($product_downloads as $download_id) {
			$download_info = $this->model_catalog_download->getDownload($download_id);

			if ($download_info) {
				$data['product_downloads'][] = array(
					'download_id' => $download_info['download_id'],
					'name'        => $download_info['name']
				);
			}
		}

		if (isset($this->request->post['product_related'])) {
			$products = $this->request->post['product_related'];
		} elseif (isset($this->request->get['product_id'])) {
			$products = $this->model_catalog_product->getProductRelated($this->request->get['product_id']);
		} else {
			$products = array();
		}

		$data['product_relateds'] = array();

		foreach ($products as $product_id) {
			$related_info = $this->model_catalog_product->getProduct($product_id);

			if ($related_info) {
				$data['product_relateds'][] = array(
					'product_id' => $related_info['product_id'],
					'name'       => $related_info['name']
				);
			}
		}

		if (isset($this->request->post['points'])) {
			$data['points'] = $this->request->post['points'];
		} elseif (!empty($product_info)) {
			$data['points'] = $product_info['points'];
		} else {
			$data['points'] = '';
		}

		if (isset($this->request->post['product_reward'])) {
			$data['product_reward'] = $this->request->post['product_reward'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_reward'] = $this->model_catalog_product->getProductRewards($this->request->get['product_id']);
		} else {
			$data['product_reward'] = array();
		}

		if (isset($this->request->post['product_seo_url'])) {
			$data['product_seo_url'] = $this->request->post['product_seo_url'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_seo_url'] = $this->model_catalog_product->getProductSeoUrls($this->request->get['product_id']);
		} else {
			$data['product_seo_url'] = array();
		}

		if (isset($this->request->post['product_layout'])) {
			$data['product_layout'] = $this->request->post['product_layout'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_layout'] = $this->model_catalog_product->getProductLayouts($this->request->get['product_id']);
		} else {
			$data['product_layout'] = array();
		}
		
		$data['last_edited'] = '';
		if (isset($this->request->get['product_id'])) {
		    $added_by = $product_info['added_by'];
		    $updated_by = $product_info['updated_by'];
		    $updated_user = '';
		    if($updated_by){
			    $user_info = $this->db->query("SELECT firstname, lastname FROM " . DB_PREFIX . "user WHERE user_id = '" . $updated_by . "'")->row;
			    if(!empty($user_info)){
			        $updated_user = $user_info['firstname'].' '.$user_info['lastname'];
			        $history_date = $product_info['date_modified'];
                    $date_time = date('d F Y, h:i A', strtotime($history_date));
			        $data['last_edited'] = 'Last Updated by : '.$updated_user.' ('.$date_time.')';
			    }
			}else{
			    $added_user = '';
    		    if($added_by){
    			    $user_info = $this->db->query("SELECT firstname, lastname FROM " . DB_PREFIX . "user WHERE user_id = '" . $added_by . "'")->row;
    			    if(!empty($user_info)){
    			        $added_user = $user_info['firstname'].' '.$user_info['lastname'];
    			        $history_date = $product_info['date_added'];
                        $date_time = date('d F Y, h:i A', strtotime($history_date));
    			        $data['last_edited'] = 'Added by : '.$added_user.' ('.$date_time.')';
    			    }
    			}
			}
		}
		
		//for againcart settings start
		$data['config_product_summary'] = $this->config->get('config_product_summary') ?? 0;
		$data['config_upc'] = $this->config->get('config_upc') ?? 0;
		$data['config_ean'] = $this->config->get('config_ean') ?? 0;
		$data['config_jan'] = $this->config->get('config_jan') ?? 0;
		$data['config_isbn'] = $this->config->get('config_isbn') ?? 0;
		$data['config_mpn'] = $this->config->get('config_mpn') ?? 0;
		$data['config_tax_class'] = $this->config->get('config_tax_class') ?? 0;
		$data['config_location_field'] = $this->config->get('config_location_field') ?? 0;
		$data['config_recurring_tab'] = $this->config->get('config_recurring_tab') ?? 0;
		$data['config_discount_tab'] = $this->config->get('config_discount_tab') ?? 0;
		$data['config_reward_point_tab'] = $this->config->get('config_reward_point_tab') ?? 0;
		$data['config_design_tab'] = $this->config->get('config_design_tab') ?? 0;
        //for againcart settings end
        
		$this->load->model('design/layout');

		$data['layouts'] = $this->model_design_layout->getLayouts();

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('catalog/product_form', $data));
	}

	protected function validateForm() {
		if (!$this->user->hasPermission('modify', 'catalog/product')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		foreach ($this->request->post['product_description'] as $language_id => $value) {
			if ((utf8_strlen($value['name']) < 1) || (utf8_strlen($value['name']) > 255)) {
				$this->error['name'][$language_id] = $this->language->get('error_name');
			}

			if ((utf8_strlen($value['meta_title']) < 1) || (utf8_strlen($value['meta_title']) > 255)) {
				$this->error['meta_title'][$language_id] = $this->language->get('error_meta_title');
			}
		}

		if ((utf8_strlen($this->request->post['model']) < 1) || (utf8_strlen($this->request->post['model']) > 64)) {
			$this->error['model'] = $this->language->get('error_model');
		}

		if ($this->request->post['product_seo_url']) {
			$this->load->model('design/seo_url');

			foreach ($this->request->post['product_seo_url'] as $store_id => $language) {
				foreach ($language as $language_id => $keyword) {
					if (!empty($keyword)) {
						if (count(array_keys($language, $keyword)) > 1) {
							$this->error['keyword'][$store_id][$language_id] = $this->language->get('error_unique');
						}

						$seo_urls = $this->model_design_seo_url->getSeoUrlsByKeyword($keyword);

						foreach ($seo_urls as $seo_url) {
							if (($seo_url['store_id'] == $store_id) && (!isset($this->request->get['product_id']) || (($seo_url['query'] != 'product_id=' . $this->request->get['product_id'])))) {
								$this->error['keyword'][$store_id][$language_id] = $this->language->get('error_keyword');

								break;
							}
						}
					}
				}
			}
		}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}

		return !$this->error;
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'catalog/product')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}

	protected function validateCopy() {
		if (!$this->user->hasPermission('modify', 'catalog/product')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}

	public function autocomplete() {
		$json = array();

		if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
			$this->load->model('catalog/product');
			$this->load->model('catalog/option');

			if (isset($this->request->get['filter_name'])) {
				$filter_name = $this->request->get['filter_name'];
			} else {
				$filter_name = '';
			}

			if (isset($this->request->get['filter_model'])) {
				$filter_model = $this->request->get['filter_model'];
			} else {
				$filter_model = '';
			}

			if (isset($this->request->get['limit'])) {
				$limit = (int)$this->request->get['limit'];
			} else {
				$limit = 5;
			}

			$filter_data = array(
				'filter_name'  => $filter_name,
				'filter_model' => $filter_model,
				'start'        => 0,
				'limit'        => $limit
			);

			$results = $this->model_catalog_product->getProducts($filter_data);

			foreach ($results as $result) {
				$option_data = array();

				$product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

				foreach ($product_options as $product_option) {
					$option_info = $this->model_catalog_option->getOption($product_option['option_id']);

					if ($option_info) {
						$product_option_value_data = array();

						foreach ($product_option['product_option_value'] as $product_option_value) {
							$option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

							if ($option_value_info) {
								$product_option_value_data[] = array(
									'product_option_value_id' => $product_option_value['product_option_value_id'],
									'option_value_id'         => $product_option_value['option_value_id'],
									'name'                    => $option_value_info['name'],
									'price'                   => (float)$product_option_value['price'] ? $this->currency->format($product_option_value['price'], $this->config->get('config_currency')) : false,
									'price_prefix'            => $product_option_value['price_prefix']
								);
							}
						}

						$option_data[] = array(
							'product_option_id'    => $product_option['product_option_id'],
							'product_option_value' => $product_option_value_data,
							'option_id'            => $product_option['option_id'],
							'name'                 => $option_info['name'],
							'type'                 => $option_info['type'],
							'value'                => $product_option['value'],
							'required'             => $product_option['required']
						);
					}
				}

				$json[] = array(
					'product_id' => $result['product_id'],
					'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
					'model'      => $result['model'],
					'option'     => $option_data,
					'price'      => $result['price']
				);
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
	
	public function download() {
        // Clean buffer in case OpenCart or extensions added content
        if (ob_get_length()) ob_end_clean();
    
        // Disable gzip compression if enabled
        if (ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off');
    
        $this->load->model('catalog/product');
    
        $filters = array(
            'filter_id'            => isset($this->request->get['filter_id']) ? $this->request->get['filter_id'] : '',
            'filter_name'              => isset($this->request->get['filter_name']) ? $this->request->get['filter_name'] : '',
            'filter_model'    => isset($this->request->get['filter_model']) ? $this->request->get['filter_model'] : '',
            'filter_price'      => isset($this->request->get['filter_price']) ? $this->request->get['filter_price'] : '',
            'filter_quantity'      => isset($this->request->get['filter_quantity']) ? $this->request->get['filter_quantity'] : '',
            'filter_status'      => isset($this->request->get['filter_status']) ? $this->request->get['filter_status'] : '',
            'filter_category_id'      => isset($this->request->get['filter_category_id']) ? $this->request->get['filter_category_id'] : '',
            'filter_stock_status'      => isset($this->request->get['filter_stock_status']) ? $this->request->get['filter_stock_status'] : '',
            'filter_manufacture'      => isset($this->request->get['filter_manufacture']) ? $this->request->get['filter_manufacture'] : '',
            'filter_attribute_id'      => isset($this->request->get['filter_attribute_id']) ? $this->request->get['filter_attribute_id'] : '',
            'filter_attribute_group_id'      => isset($this->request->get['filter_attribute_group_id']) ? $this->request->get['filter_attribute_group_id'] : '',
            'filter_filter_group_id'      => isset($this->request->get['filter_filter_group_id']) ? $this->request->get['filter_filter_group_id'] : '',
            'filter_filter_id'      => isset($this->request->get['filter_filter_id']) ? $this->request->get['filter_filter_id'] : '',
            'filter_option_id'      => isset($this->request->get['filter_option_id']) ? $this->request->get['filter_option_id'] : '',
            'filter_option_value_id'      => isset($this->request->get['filter_option_value_id']) ? $this->request->get['filter_option_value_id'] : '',
            'filter_added_by'      => isset($this->request->get['filter_added_by']) ? $this->request->get['filter_added_by'] : '',
            'filter_date_added_from'      => isset($this->request->get['filter_date_added_from']) ? $this->request->get['filter_date_added_from'] : '',
            'filter_date_added_to'      => isset($this->request->get['filter_date_added_to']) ? $this->request->get['filter_date_added_to'] : '',
        );
        
        $results = $this->model_catalog_product->getProducts($filters);
    
        // Prepare bulk stock statuses (avoid query in loop)
        $stock_status_query = $this->db->query("SELECT stock_status_id, name FROM " . DB_PREFIX . "stock_status");
        $stock_statuses = [];
        foreach ($stock_status_query->rows as $row) {
            $stock_statuses[$row['stock_status_id']] = $row['name'];
        }
        
        $arrayToCsvLine = function(array $values) {
            $line = '';

            $values = array_map(function ($v) {
                return '"' . str_replace('"', '""', $v) . '"';
            }, $values);

            $line .= implode(',', $values);

            return $line;
        };
        
        $str = "ProductID,Name,Model,Price,Special Price,Quantity,Sort Order,Stock Status,Status".PHP_EOL;
        foreach ($results as $result) {
		    $special = false;

			$product_specials = $this->model_catalog_product->getProductSpecials($result['product_id']);

			foreach ($product_specials  as $product_special) {
				if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
					$special = $product_special['price'];

					break;
				}
			}
			
			$stock_status = isset($stock_statuses[$result['stock_status_id']]) ? $stock_statuses[$result['stock_status_id']] : '';

			$str = $str . $arrayToCsvLine(array(
				'product_id' => $result['product_id'],
				'name'       => html_entity_decode($result['name']),
				'model'       => html_entity_decode($result['model']),
				'price'      => $result['price'],
				'special'      => $special,
				'quantity'   => $result['quantity'],
				'sort_order'   => $result['sort_order'],
				'stock_status'   => $stock_status,
				'status'     => ($result['status']) ? 'Enabled' : 'Disabled',
			)) . PHP_EOL;
		}

        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="products.csv"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');

        echo($str);
    }
    
    public function getCategoryFilters() {
        $json = [];
    
        if (isset($this->request->get['category_id'])) {
            $category_id = (int)$this->request->get['category_id'];
    
            $this->load->model('catalog/category');
            $this->load->model('catalog/filter');
    
            $filter_data = $this->model_catalog_category->getCategoryFilters($category_id);
    
            foreach ($filter_data as $filter_id) {
                $filter_info = $this->model_catalog_filter->getFilter($filter_id);
            
                if ($filter_info) {
                    // Get filter group name
                    $filter_group_name = $this->getFilterGroupName($filter_info['filter_group_id']);
            
                    if (!isset($json[$filter_group_name])) {
                        $json[$filter_group_name] = [];
                    }
                    $json[$filter_group_name][] = [
                        'filter_id' => $filter_info['filter_id'],
                        'name'      => $filter_info['name']
                    ];
                }
            }
        }
    
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

	private function getFilterGroupName($filter_group_id) {
        $query = $this->db->query("SELECT name FROM " . DB_PREFIX . "filter_group_description WHERE filter_group_id = '" . (int)$filter_group_id . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");
        if ($query->num_rows) {
            return $query->row['name'];
        } else {
            return 'Unknown Group';
        }
    }

	public function seo() {
		$this->load->language('catalog/product');

		$this->document->setTitle($this->language->get('heading_title_seo'));

		$this->load->model('catalog/product');

		$this->getSeoList();
	}
	
	protected function getSeoList() {
		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
		} else {
			$filter_name = '';
		}

		if (isset($this->request->get['filter_model'])) {
			$filter_model = $this->request->get['filter_model'];
		} else {
			$filter_model = '';
		}

		if (isset($this->request->get['filter_price'])) {
			$filter_price = $this->request->get['filter_price'];
		} else {
			$filter_price = '';
		}

		if (isset($this->request->get['filter_quantity'])) {
			$filter_quantity = $this->request->get['filter_quantity'];
		} else {
			$filter_quantity = '';
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = '';
		}

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'p.product_id';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'DESC';
		}

		if (isset($this->request->get['page'])) {
			$page = (int)$this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

		$data['add'] = $this->url->link('catalog/product/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$data['copy'] = $this->url->link('catalog/product/copy', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$data['delete'] = $this->url->link('catalog/product/delete', 'user_token=' . $this->session->data['user_token'] . $url, true);

		$data['products'] = array();

		$filter_data = array(
			'filter_name'	  => $filter_name,
			'filter_model'	  => $filter_model,
			'filter_price'	  => $filter_price,
			'filter_quantity' => $filter_quantity,
			'filter_status'   => $filter_status,
			'sort'            => $sort,
			'order'           => $order,
			'start'           => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'           => $this->config->get('config_limit_admin')
		);

		$this->load->model('tool/image');

		$product_total = $this->model_catalog_product->getTotalProducts($filter_data);

		$results = $this->model_catalog_product->getProducts($filter_data);
		
		foreach ($results as $result) {
			
			$description_len = utf8_strlen($result['description']);

            // Focus Keyphrase in Description
            $focus = isset($result['focus_keyword']) ? trim(strtolower($result['focus_keyword'])) : '';

            // If the focus keyphrase is not set or empty, don't proceed with the check
            if ($focus) {
                $focus_in_description = stripos($result['description'], $focus) !== false;
            } else {
                // If focus keyphrase is missing, set the flag to false
                $focus_in_description = false;
            }
            
            $full_data = $this->model_catalog_product->getProductFullData($result['product_id']);
            $product_strength = $this->calculateProductStrength($full_data);
            $product_seo = $this->getProductSeoScore($full_data);
            
            $full_url = HTTPS_CATALOG . $full_data['seo_keyword'];
   
			$data['products'][] = array(
				'product_id' => $result['product_id'],
				'name'       => $result['name'],
				'meta_title'       => $result['meta_title'],
				'meta_description'       => $result['meta_description'],
				'meta_keyword'       => $result['meta_keyword'],
				'description'       => $result['description'],
				'description_length'       => $description_len,
				'focus_in_description'       => $focus_in_description,
                'product_strength_total_score'       => $product_strength['total_score'],
                'product_strength_out_of'       => $product_strength['out_of'],
                'product_strength_details'       => $product_strength['details'],
                'product_seo_total_score'       => $product_seo['total_score'],
                'product_seo_out_of'       => $product_seo['out_of'],
                'product_seo_details'       => $product_seo['details'],
				'model'      => $result['model'],
				'status'     => $result['status'],
				'edit'       => $this->url->link('catalog/product/edit', 'user_token=' . $this->session->data['user_token'] . '&product_id=' . $result['product_id'] . $url, true),
				'view'             => HTTP_CATALOG.'index.php?route=product/product&product_id=' . $result['product_id'],
				'google_search' => 'https://www.google.com/search?q='. $result['name'],
				'google_index_check' => 'https://www.google.com/search?q=site:' . urlencode($full_url),
			);
			
		}
		
		$data['user_token'] = $this->session->data['user_token'];

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		if (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['sort_name'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=pd.name' . $url, true);
		$data['sort_model'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.model' . $url, true);
		$data['sort_price'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.price' . $url, true);
		$data['sort_quantity'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.quantity' . $url, true);
		$data['sort_status'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.status' . $url, true);
		$data['sort_order'] = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . '&sort=p.sort_order' . $url, true);

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $product_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'] . $url . '&page={page}', true);

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($product_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($product_total - $this->config->get('config_limit_admin'))) ? $product_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $product_total, ceil($product_total / $this->config->get('config_limit_admin')));

		$data['filter_name'] = $filter_name;
		$data['filter_model'] = $filter_model;
		$data['filter_price'] = $filter_price;
		$data['filter_quantity'] = $filter_quantity;
		$data['filter_status'] = $filter_status;

		$data['sort'] = $sort;
		$data['order'] = $order;

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('catalog/product_seo_list', $data));
	}
	
	private function calculateProductStrength($product) {
            $score = 0;
            $total_possible = 84;
            $details = [];
            $issues = [];
        
            $checks = [
                ['Focus Keyword Field', 5, !empty($product['focus_keyword']), 'Focus keyword missing'],
                ['Description (min 300 words)', 5, str_word_count(strip_tags($product['description'])) >= 300, 'Description less than 300 words'],
                ['Meta Title (50–60 chars)', 5, strlen($product['meta_title']) >= 50 && strlen($product['meta_title']) <= 60, 'Meta title not between 50–60 characters'],
                ['Meta Keyword', 3, !empty($product['meta_keyword']), 'Meta keyword missing'],
                ['Meta Description (120–160 chars)', 5, strlen($product['meta_description']) >= 120 && strlen($product['meta_description']) <= 160, 'Meta description not 120–160 chars'],
                ['Product Tags', 3, !empty($product['tag']), 'Product tags missing'],
                ['Model', 3, !empty($product['model']), 'Model missing'],
                ['Price', 5, (float)$product['price'] > 0, 'Price not set or zero'],
                ['Stock Status', 3, isset($product['stock_status_id']), 'Stock status missing'],
                ['Quantity', 3, (int)$product['quantity'] > 0, 'Quantity zero or missing'],
                ['Sort Order', 2, isset($product['sort_order']), 'Sort order missing'],
                ['Weight Class', 2, isset($product['weight_class_id']), 'Weight class not selected'],
                ['SKU', 3, !empty($product['sku']), 'SKU missing'],
                ['Short Description', 3, !empty($product['short_description']), 'Short description missing'],
                ['CTA in Description (e.g., "Buy Now")', 3, stripos($product['description'], 'buy now') !== false, 'No call-to-action in description'],
                ['Attributes', 5, !empty($product['product_attribute']) && count($product['product_attribute']) >= 1, 'Attributes missing'],
                ['At least 2 Images', 5, !empty($product['images']) && count($product['images']) >= 2, 'Less than 2 images'],
                ['SEO URL', 3, !empty($product['seo_keyword']), 'SEO keyword missing'],
                ['Product Filter', 3, !empty($product['product_filter']), 'No filter assigned'],
                ['Related Products', 3, !empty($product['related']) && count($product['related']) > 0, 'No related products'],
                ['Special Price', 3, isset($product['special']), 'No special price set'],
                ['At least 1 Review', 2, isset($product['product_id']) && $product['review_count'] > 0, 'No reviews'],
                ['Manufacturer', 2, isset($product['manufacturer_id']), 'Manufacturer missing'],
                ['Category', 5, !empty($product['product_category']) && count($product['product_category']) > 0, 'Category not assigned'],
            ];
        
            foreach ($checks as [$label, $max, $condition, $failNote]) {
                $earned = $condition ? $max : 0;
                $score += $earned;
        
                $details[] = [
                    'label' => $label,
                    'earned' => $earned,
                    'max' => $max,
                    'status' => $condition ? 'pass' : 'fail',
                    'note' => $condition ? 'Passed' : $failNote
                ];
        
                if (!$condition) {
                    $issues[] = [
                        'label' => $label,
                        'missed' => $max,
                        'reason' => $failNote
                    ];
                }
            }
        
            return [
                'total_score' => $score,
                'out_of' => $total_possible,
                'details' => $details,
                'issues' => $issues
            ];
        }
    private function calculateProductStrength1($product) {
        $score = 0;
    
        // 1. Focus Keyword Field
        if (!empty($product['focus_keyword'])) $score += 5;
    
        // 2. Description (min 300 words)
        if (str_word_count(strip_tags($product['description'])) >= 300) $score += 5;
    
        // 3. Meta Title (50–60 chars)
        $len = strlen($product['meta_title']);
        if ($len >= 50 && $len <= 60) $score += 5;
    
        // 4. Meta Keyword
        if (!empty($product['meta_keyword'])) $score += 3;
    
        // 5. Meta Description (120–160 chars)
        $len = strlen($product['meta_description']);
        if ($len >= 120 && $len <= 160) $score += 5;
    
        // 6. Product Tags
        if (!empty($product['tag'])) $score += 3;
    
        // 7. Model
        if (!empty($product['model'])) $score += 3;
    
        // 8. Price
        if ((float)$product['price'] > 0) $score += 5;
    
        // 9. Stock Status
        if (isset($product['stock_status_id'])) $score += 3;
    
        // 10. Quantity
        if ((int)$product['quantity'] > 0) $score += 3;
    
        // 11. Sort Order
        if (isset($product['sort_order'])) $score += 2;
    
        // 12. Shipping Class / Weight Class
        if (isset($product['weight_class_id'])) $score += 2;
    
        // 13. SKU
        if (!empty($product['sku'])) $score += 3;
    
        // 14. Short Description
        if (!empty($product['short_description'])) $score += 3;
    
        // 15. CTA in Description
        if (stripos($product['description'], 'buy now') !== false) $score += 3;
    
        // 16. Attributes
        if (!empty($product['product_attribute']) && count($product['product_attribute']) >= 1) $score += 5;
    
        // 17. At least 2 images
        if (!empty($product['images']) && count($product['images']) >= 2) $score += 5;
    
        // 18. SEO URL
        if (!empty($product['seo_keyword'])) $score += 3;
    
        // 19. Product Filter
        if (!empty($product['product_filter'])) $score += 3;
    
        // 20. Related Products
        if (!empty($product['related']) && count($product['related']) > 0) $score += 3;
    
        // 21. Special Price
        if (isset($product['special'])) $score += 3;
    
        // 22. At least 1 Review
        if (isset($product['product_id']) && $product['review_count'] > 0) $score += 2;
    
        // 23. Manufacturer
        if (isset($product['manufacturer_id'])) $score += 2;
    
        // 24. Category
        if (!empty($product['product_category']) && count($product['product_category']) > 0) $score += 5;
    
        return $score;
    }
    
    private function getProductStrengthIssues($product) {
        $issues = [];
    
        if (empty($product['focus_keyword'])) $issues[] = 'Missing Focus Keyword';
        if (str_word_count(strip_tags($product['description'])) < 300) $issues[] = 'Description too short';
        
        $meta_title_len = strlen($product['meta_title']);
        if ($meta_title_len < 50 || $meta_title_len > 60) $issues[] = 'Meta Title length should be 50–60';
    
        if (empty($product['meta_keyword'])) $issues[] = 'Missing Meta Keyword';
    
        $meta_desc_len = strlen($product['meta_description']);
        if ($meta_desc_len < 120 || $meta_desc_len > 160) $issues[] = 'Meta Description length should be 120–160';
    
        if (empty($product['tag'])) $issues[] = 'No Product Tags';
        if (empty($product['model'])) $issues[] = 'Missing Model';
        if ((float)$product['price'] <= 0) $issues[] = 'Invalid or Zero Price';
        if (!isset($product['stock_status_id'])) $issues[] = 'Stock Status not set';
        if ((int)$product['quantity'] <= 0) $issues[] = 'Quantity not set or zero';
        if (!isset($product['sort_order'])) $issues[] = 'Sort Order not set';
        if (!isset($product['weight_class_id'])) $issues[] = 'Weight Class not set';
        if (empty($product['sku'])) $issues[] = 'SKU is missing';
        if (empty($product['short_description'])) $issues[] = 'Short Description is missing';
        if (stripos($product['description'], 'buy now') === false) $issues[] = 'No CTA like "Buy Now"';
        if (empty($product['product_attribute']) || count($product['product_attribute']) < 1) $issues[] = 'No Attributes set';
        if (empty($product['images']) || count($product['images']) < 2) $issues[] = 'Less than 2 images';
        if (empty($product['seo_keyword'])) $issues[] = 'SEO URL is missing';
        if (empty($product['product_filter'])) $issues[] = 'No Product Filters';
        if (empty($product['related']) || count($product['related']) == 0) $issues[] = 'No Related Products';
        if (!isset($product['special'])) $issues[] = 'Special Price not set';
        if (isset($product['product_id']) && $product['review_count'] == 0) $issues[] = 'No Reviews';
        if (!isset($product['manufacturer_id'])) $issues[] = 'Manufacturer not set';
        if (empty($product['product_category']) || count($product['product_category']) == 0) $issues[] = 'No Category assigned';
    
        return $issues;
    }
    
    protected function getProductSeoScore($product) {
        $focus_keyword = strtolower(trim($product['focus_keyword'] ?? ''));
        $meta_title = $product['meta_title'];
        $meta_description = $product['meta_description'];
        $seo_url = $product['seo_keyword'];
        $description = html_entity_decode($product['description'], ENT_QUOTES, 'UTF-8');
        $images = $product['images']; // returns array
        $your_domain = parse_url(defined('HTTPS_CATALOG') ? HTTPS_CATALOG : HTTP_CATALOG, PHP_URL_HOST);
        $previous_keywords = []; // load from DB if needed
    
        $score = 0;
        $total_possible = 100;
        $issues = [];
        $details = [];
    
        // Utility function
        $addDetail = function ($title, $got, $max, $error = null) use (&$score, &$issues, &$details) {
            $score += $got;
            $details[] = [
                'title' => $title,
                'score' => $got,
                'out_of' => $max,
                'issue' => $got < $max ? $error : null,
            ];
            if ($got < $max && $error) $issues[] = $error;
        };
    
        // 1. Focus Keyword Provided
        $has_keyword = !empty($focus_keyword);
        $addDetail('Focus Keyword Provided', $has_keyword ? 5 : 0, 5, "Focus keyword not provided.");
    
        // Only run keyword-based checks if keyword exists
        if ($has_keyword) {
            $addDetail('Keyword in Meta Title', strpos(strtolower($meta_title), $focus_keyword) !== false ? 5 : 0, 5, "Keyword missing in Meta Title.");
            $addDetail('Keyword in Meta Description', strpos(strtolower($meta_description), $focus_keyword) !== false ? 5 : 0, 5, "Keyword missing in Meta Description.");
            $addDetail('Focus Keyword in Meta Keywords', strpos(strtolower($product['meta_keyword']), $focus_keyword) !== false ? 3 : 0, 3, "Focus keyword not in Meta Keywords.");
            $addDetail('Keyword in SEO URL', strpos(strtolower($seo_url), $focus_keyword) !== false ? 5 : 0, 5, "Keyword not found in SEO URL.");
            $addDetail('Keyphrase Length ≤ 5 Words', str_word_count($focus_keyword) <= 5 ? 5 : 0, 5, "Focus keyword too long (more than 5 words).");
    
            $first_paragraph = strtok(strip_tags($description), "\n");
            $addDetail('Keyword in First Paragraph', strpos(strtolower($first_paragraph), $focus_keyword) !== false ? 5 : 0, 5, "Focus keyword missing in first paragraph.");
    
            $word_count = str_word_count(strip_tags($description));
            $keyword_count = substr_count(strtolower(strip_tags($description)), strtolower($focus_keyword));
            $density = ($word_count > 0) ? $keyword_count / $word_count : 0;
            $addDetail('Keyword Density (0.5% - 2%)', ($density >= 0.005 && $density <= 0.02) ? 5 : 0, 5, "Keyword density out of range (0.5% to 2%).");
    
            $addDetail('H1 Tag with Keyword', preg_match('/<h1[^>]*>.*?' . preg_quote($focus_keyword, '/') . '.*?<\/h1>/i', $description) ? 5 : 0, 5, "No H1 tag with focus keyword.");
        }
    
        // Meta Title Length
        $addDetail('Meta Title Length', (strlen($meta_title) >= 50 && strlen($meta_title) <= 60) ? 5 : 0, 5, "Meta Title length not between 50-60 chars.");
    
        // Meta Description Length
        $addDetail('Meta Description Length', (strlen($meta_description) >= 120 && strlen($meta_description) <= 160) ? 5 : 0, 5, "Meta Description length not between 120-160 chars.");
    
        // Word count
        $word_count = str_word_count(strip_tags($description));
        $addDetail('Minimum 300 Words', $word_count >= 300 ? 5 : 0, 5, "Description has less than 300 words.");
    
        // Headings
        $subhead_count = preg_match_all('/<h[2-6][^>]*>/', $description);
        $addDetail('Multiple Headings (H2-H6)', $subhead_count >= 2 ? 5 : 0, 5, "Less than 2 subheadings (H2-H6).");
    
        // Subheading distribution
        $addDetail('Good Subheading Distribution', ($subhead_count > 0 && ($word_count / $subhead_count) <= 100) ? 3 : 0, 3, "Poor subheading distribution.");
    
        // Images
        $addDetail('Minimum 2 Images', count($images) >= 2 ? 5 : 0, 5, "Less than 2 images in product.");
    
        // ALT text placeholder using filename (if keyword exists)
        $alt_found = false;
        if ($has_keyword) {
            foreach ($images as $img) {
                if (!empty($img['image']) && strpos(strtolower($img['image']), $focus_keyword) !== false) {
                    $alt_found = true;
                    break;
                }
            }
        }
        $addDetail('Image ALT Contains Keyword', $has_keyword && $alt_found ? 5 : 0, 5, "No image ALT contains the focus keyword.");
    
        // Links
        $addDetail('Internal Link Present', strpos($description, $your_domain) !== false ? 4 : 0, 4, "No internal link found.");
        $addDetail('External Link Present', preg_match('/<a[^>]+href=["\']https?:\/\/(?!' . preg_quote($your_domain, '/') . ')/i', $description) ? 3 : 0, 3, "No external link present.");
    
        // Keyword uniqueness
        if ($has_keyword) {
            $addDetail('Unique Focus Keyword', !in_array($focus_keyword, $previous_keywords) ? 3 : 0, 3, "Focus keyword already used in another product.");
        }
    
        return [
            'total_score' => $score,
            'out_of' => $total_possible,
            'details' => $details,
            'issues' => $issues
        ];
    }


    protected function getProductSeoScore1($product) {
        // Sample Variables
        $focus_keyword = strtolower(trim($product['focus_keyword'] ?? ''));
        $meta_title = $product['meta_title'];
        $meta_description = $product['meta_description'];
        $seo_url = $product['seo_keyword'];
        $description = html_entity_decode($product['description'], ENT_QUOTES, 'UTF-8');
        $images = $product['images']; // returns array
        $your_domain = parse_url(defined('HTTPS_CATALOG') ? HTTPS_CATALOG : HTTP_CATALOG, PHP_URL_HOST);
        $previous_keywords = []; // load from DB if needed
        
        $score = 0;
        $issues = [];
    
        // 1. Focus Keyword Provided
        if (!empty($focus_keyword)) {
            $score += 5;
        } else {
            $issues[] = "Focus keyword not provided.";
        }
    
        // 2. Keyword in Meta Title
        if (strpos($meta_title, $focus_keyword) !== false) {
            $score += 5;
        } else {
            $issues[] = "Keyword missing in Meta Title.";
        }
    
        // 3. Meta Title Length
        $len = strlen($meta_title);
        if ($len >= 50 && $len <= 60) {
            $score += 5;
        } else {
            $issues[] = "Meta Title length not between 50-60 chars.";
        }
    
        // 4. Keyword in Meta Description
        if (strpos($meta_description, $focus_keyword) !== false) {
            $score += 5;
        } else {
            $issues[] = "Keyword missing in Meta Description.";
        }
    
        // 5. Meta Description Length
        $len = strlen($meta_description);
        if ($len >= 120 && $len <= 160) {
            $score += 5;
        } else {
            $issues[] = "Meta Description length not between 120-160 chars.";
        }
    
        // 6. Meta Keyword Contains Focus Keyword
        if (strpos($product['meta_keyword'], $focus_keyword) !== false) {
            $score += 3;
        } else {
            $issues[] = "Focus keyword not in Meta Keywords.";
        }
    
        // 7. Keyword in SEO URL
        if (strpos($seo_url, $focus_keyword) !== false) {
            $score += 5;
        } else {
            $issues[] = "Keyword not found in SEO URL.";
        }
    
        // 8. Keyphrase Length ≤ 5 Words
        if (str_word_count($focus_keyword) <= 5) {
            $score += 5;
        } else {
            $issues[] = "Focus keyword too long (more than 5 words).";
        }
    
        // 9. Keyword in First Paragraph
        $first_paragraph = strtok(strip_tags($description), "\n");
        if (strpos($first_paragraph, $focus_keyword) !== false) {
            $score += 5;
        } else {
            $issues[] = "Focus keyword missing in first paragraph.";
        }
    
        // 10. Keyword Density (0.5% to 2%)
        $word_count = str_word_count(strip_tags($description));

        if (!empty($focus_keyword)) {
            $keyword_count = substr_count(strtolower(strip_tags($description)), strtolower($focus_keyword));
            $density = ($word_count > 0) ? $keyword_count / $word_count : 0;
        
            if ($density >= 0.005 && $density <= 0.02) {
                $score += 5;
            } else {
                $issues[] = "Keyword density out of range (0.5% to 2%).";
            }
        } else {
            $issues[] = "Focus keyword not provided — cannot calculate keyword density.";
        }
    
        // 11. Min 300 Words in Description
        if ($word_count >= 300) {
            $score += 5;
        } else {
            $issues[] = "Description has less than 300 words.";
        }
    
        // 12. H1 Tag Present with Focus Keyword
        if (preg_match('/<h1[^>]*>.*?' . preg_quote($focus_keyword, '/') . '.*?<\/h1>/i', $description)) {
            $score += 5;
        } else {
            $issues[] = "No H1 tag with focus keyword.";
        }
    
        // 13. Multiple Heading Tags (H2, H3, etc.)
        if (preg_match_all('/<h[2-6][^>]*>/', $description, $matches) >= 2) {
            $score += 5;
        } else {
            $issues[] = "Less than 2 subheadings (H2-H6).";
        }
    
        // 14. Image Count ≥ 2
        if (count($images) >= 2) {
            $score += 5;
        } else {
            $issues[] = "Less than 2 images in product.";
        }
    
        // 15. Image ALT Text Contains Focus Keyword
        $alt_found = false;
        foreach ($images as $img) {
            if (!empty($img['image']) && strpos($img['image'], $focus_keyword) !== false) {
                $alt_found = true;
                break;
            }
        }
        if ($alt_found) {
            $score += 5;
        } else {
            $issues[] = "No image ALT contains the focus keyword.";
        }
    
        // 16. Internal Link Present
        if (strpos($description, $your_domain) !== false) {
            $score += 4;
        } else {
            $issues[] = "No internal link found.";
        }
    
        // 17. External Link Present
        if (preg_match('/<a[^>]+href=["\']https?:\/\/(?!' . preg_quote($your_domain, '/') . ')/i', $description)) {
            $score += 3;
        } else {
            $issues[] = "No external link present.";
        }
    
        // 18. No Duplicate Keyword
        if (!in_array($focus_keyword, $previous_keywords)) {
            $score += 3;
        } else {
            $issues[] = "Focus keyword already used in another product.";
        }
    
        // 19. Subheading Distribution (every ~100 words)
        $heading_count = preg_match_all('/<h[2-6][^>]*>/', $description);
        if ($heading_count > 0 && ($word_count / $heading_count) <= 100) {
            $score += 3;
        } else {
            $issues[] = "Poor subheading distribution.";
        }
    
        return [
            'score' => $score,
            'issues' => $issues
        ];
    }

}
