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

class Product extends CI_Controller {

	function __construct() {
		parent::__construct();
		date_default_timezone_set("Asia/Kolkata");
		if (!isLoggedIn()) {
			redirect(base_url('adminex'));
			exit();
		}
	}
	
	/**
	* Load Product List Page Method
	* 
	* @param1       
	* @return       view page
	* @access       public
	* @author       M.K.Sah
	* @copyright    N/A
	* @link         application/Product
	* @since        12th Jan 2026
	* @deprecated   N/A
	**/
	
	public function index(){
		
		$where = '';
		$where_clause = '';
		$data         = array();
		$param  = $this->input->get();
		$param  = array_map('trim', $param);
		$param = $this->security->xss_clean($param);

		$orderbyfld = 'product_name';

		if (isset($param['category_id']) && $param['category_id'] != '') {
			$data['catID'] = $param['category_id'];
			$where .= "cat_id = '" . $param['category_id'] . "' AND ";
		}

		if (isset($param['product_id']) && $param['product_id'] != '') {
			$data['prodID'] = $param['product_id'];
			$where .= "id = '" . $param['product_id'] . "' AND ";
		}
		
		if ($where != '') {
			$where_clause = substr($where, 0, -4);
		}
		$this->load->library('pagination');
		$offset = trim($this->input->get('per_page'));
		$this->db->order_by($orderbyfld, 'ASC');
		$query = $this->CommonModel->RetriveRecordByWhere(TBL_PRODUCT_LIST, $where_clause);
		$config['base_url']        = base_url() . "adminex/list-product?" . http_build_query($data);
		$config['total_rows']      = $query->num_rows();
		$config['per_page']        = PAGINATION_LIMIT;
		$config['full_tag_open']   = '<div class="paging_simple_numbers"><nav><ul class="pagination pagination-sm m-0 float-right">';
		$config['full_tag_close']  = '</ul></nav></div>';
		$config['num_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['num_tag_close']   = '</span></li>';
		$config['cur_tag_open']    = '<li class="page-item active"><span class="page-link">';
		$config['cur_tag_close']   = '<span class="sr-only">(current)</span></span></li>';
		$config['next_tag_open']   = '<li class="page-item"><span class="page-link">';
		$config['next_tag_close']  = '</span></li>';
		$config['prev_tag_open']   = '<li class="page-item"><span class="page-link">';
		$config['prev_tag_close']  = '</span></li>';
		$config['first_tag_open']  = '<li class="page-item"><span class="page-link">';
		$config['first_tag_close'] = '</span></li>';
		$config['last_tag_open']   = '<li class="page-item"><span class="page-link">';
		$config['last_tag_close']  = '</span></li>';
		$config['page_query_string'] = TRUE;
		$this->pagination->initialize($config);
		$data['links']      = $this->pagination->create_links();
		$data['TotalRec']   = $config['total_rows'];
		$data['page']       = !empty($offset) ? $offset : 0;
		
		$data['products'] = $this->CommonModel->RetriveSelectedRecordByWhereGroupBy(array('id','product_name'),TBL_PRODUCT,array('status'=>1),'product_name');
		$data['categories'] = $this->CommonModel->selectOrderByWhereRecord(array('id','category_name'),'category_name','ASC',TBL_CATEGORY,array('status'=>1));
		$data['productList'] = $this->CommonModel->RetriveRecordByWhereOrderbyLimit( array('id','category_name','product_name','product_price','sale_price','product_img','weight','weight_unit','quantity','product_short_desc') ,TBL_PRODUCT_LIST, $where_clause ,PAGINATION_LIMIT,$offset,$orderbyfld,'ASC');

		$data['meta_title'] = 'Product List';
      	$data['meta_desc']  = 'Product List Description';
		$data['content'] 	= 'admin/product/index';
		$this->load->view('admin/layout_home', $data);
	}
	
	/**
	* Load Add Product Method
	* 
	* @param1       
	* @return       view page
	* @access       public
	* @author       M.K.Sah
	* @copyright    N/A
	* @link         application/Product
	* @since        12th Jan 2026
	* @deprecated   N/A
	**/
	
	public function add(){

		$this->form_validation->set_rules('product_name', 'product name', 'trim|xss_clean|required|is_unique['.TBL_PRODUCT.'.product_name]',array('is_unique' => 'This %s already exists.' ));
		$this->form_validation->set_rules('product_price', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('sale_price', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('quantity', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('category_id', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('weight', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('weight_unit', 'product price', 'trim|xss_clean|required');
		
		if (!$this->form_validation->run() === FALSE )
		{
			$params = $this->input->post();
			$params = array_map('trim', $params);
			$params = $this->security->xss_clean($params);
			
			if( isset($_FILES['product_image']) && !empty($_FILES['product_image']) ){

				$config['upload_path']  = FCPATH . 'uploads/product/';
				$config['allowed_types']= ALLOWED_FILE_TYPE;
				$config['max_size'] 	= '';
				$config['max_width']    = '';
				$config['max_height']   = '';
				$config['file_name'] 	= 'image_'.time();

				// Create temp directory if missing
				if (!is_dir($config['upload_path'])) {
					mkdir($config['upload_path'], 0775, true);
				}
				
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				
				if ( ! $this->upload->do_upload('product_image') )
				{
					$data['error'] = $this->upload->display_errors();
					$this->session->set_flashdata('error', $data['error'] . ' Please note that only files in '.ALLOWED_FILE_TYPE.' format are allowed.');
					redirect(base_url('adminex/add-product'));
					exit();
				} else {
					$fileArray = $this->upload->data();
					$file_name = $fileArray['file_name'];
				}		
			}
			
			$insertArray = array(
				'product_name' 		=> $params['product_name'],
				'product_sale_price'=> $params['sale_price'],
				'product_img' 		=> isset($file_name)?$file_name:'',
				'cat_id' 			=> $params['category_id'],
				'status' 			=> 1,
				'created_on' 		=> date('Y-m-d H:i:s'),
				'updated_on' 		=> date('Y-m-d H:i:s')
			);
			$lastInsertId = $this->CommonModel->AddRecord($insertArray,TBL_PRODUCT);
			
			if($lastInsertId>0){
				$attributesArray = array(
					'product_id' 			=> $lastInsertId,
					'product_short_desc' 	=> $params['product_desc'],
					'product_price' 		=> $params['product_price'],
					'weight' 				=> $params['weight'],
					'weight_unit' 			=> $params['weight_unit'],
					'quantity' 				=> $params['quantity']
				);
				$this->CommonModel->AddRecord($attributesArray,TBL_PRODUCT_ATTRIBUTES);
				$this->session->set_flashdata('success', 'The product details have been saved successfully.');
				redirect(base_url('adminex/list-product'));
			}else{
				$this->session->set_flashdata('error', 'Some error occured while saving product details.');
				redirect(base_url('adminex/add-product'));
			}
		}
		else{
			$data['categories'] = $this->CommonModel->selectOrderByWhereRecord(array('id','category_name'),'category_name','ASC',TBL_CATEGORY,array('status'=>1));
			$data['meta_title']	= 'Add Product';
			$data['meta_desc']	= 'Add Product Description';
			$data['content'] 	= 'admin/product/add';
			$this->load->view('admin/layout_home', $data);
		}
	}
	
	/**
	* Load Edit Product Method
	* 
	* @param1       
	* @return       view page
	* @access       public
	* @author       M.K.Sah
	* @copyright    N/A
	* @link         application/Product
	* @since        12th Jan 2026
	* @deprecated   N/A
	**/
	
	public function edit($id){

		if (!ctype_digit($id)) {
			show_error('Invalid request. Please try again.', 400);
			exit();
		}
		$prdID = (int) $id;
		
		if($this->input->post('product_name') !=  $this->input->post('product_hdn')){
			$this->form_validation->set_rules('product_name', 'product name', 'trim|xss_clean|required|is_unique['.TBL_PRODUCT.'.product_name]',array('is_unique' => 'This %s already exists.' ));
		}else{
			$this->form_validation->set_rules('product_name', 'product name', 'trim|xss_clean|required');
		}
		$this->form_validation->set_rules('product_price', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('product_desc', 'product description', 'trim|xss_clean|required');
		$this->form_validation->set_rules('sale_price', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('quantity', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('category_id', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('weight', 'product price', 'trim|xss_clean|required');
		$this->form_validation->set_rules('weight_unit', 'product price', 'trim|xss_clean|required');
		
		if (!$this->form_validation->run() === FALSE )
		{
			$params = $this->input->post();
			$params = array_map('trim', $params);
			$params = $this->security->xss_clean($params);
			
			if( isset($_FILES['product_image']) && !empty($_FILES['product_image']) && $_FILES['product_image']['name'] !='' ){

				$config['upload_path']  = FCPATH . 'uploads/product/';
				$config['allowed_types']= ALLOWED_FILE_TYPE;
				$config['max_size'] 	= '';
				$config['max_width']    = '';
				$config['max_height']   = '';
				$config['file_name'] 	= 'image_'.time();

				// Create temp directory if missing
				if (!is_dir($config['upload_path'])) {
					mkdir($config['upload_path'], 0775, true);
				}
				
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				
				if ( ! $this->upload->do_upload('product_image') )
				{
					$data['error'] = $this->upload->display_errors();
					$this->session->set_flashdata('error', $data['error'] . ' Please note that only files in '.ALLOWED_FILE_TYPE.' format are allowed.');
					redirect(base_url('adminex/edit-product/'.$prdID));
					exit();
				} else {
					$fileArray = $this->upload->data();
					$file_name = $fileArray['file_name'];

					$img_path = FCPATH.'uploads/product/'.$this->input->post('image_hdn');
					if( isset($fileArray) && $file_name != '' ){
						@unlink($img_path);
					}
				}		
			}
			else{
				$file_name = $this->input->post('image_hdn');
			}
			
			$UpdateData = array(
				'product_name' 		=> $params['product_name'],
				'product_sale_price'=> $params['sale_price'],
				'product_img' 		=> isset($file_name)?$file_name:'',
				'cat_id' 			=> $params['category_id'],
				'status' 			=> 1,
				'updated_on' 		=> date('Y-m-d H:i:s')
			);
			$lastInsertId = $this->CommonModel->UpdateRecord($UpdateData,TBL_PRODUCT,'id',$prdID);
			
			if($lastInsertId>0){
				$updateAttributes = array(
					'product_short_desc' 	=> $params['product_desc'],
					'product_price' 		=> $params['product_price'],
					'weight' 				=> $params['weight'],
					'weight_unit' 			=> $params['weight_unit'],
					'quantity' 				=> $params['quantity']
				);
				
				$this->CommonModel->UpdateRecord($updateAttributes,TBL_PRODUCT_ATTRIBUTES,'product_id',$prdID);
				$this->session->set_flashdata('success', 'The product details have been successfully updated.');
				redirect(base_url('adminex/list-product'));
			}else{
				$this->session->set_flashdata('error', 'Some error occured while updating the product details.');
				redirect(base_url('adminex/edit-product/'.$prdID));
			}
		}
		else{
			$data['EditData'] = $this->CommonModel->getSelectedRecordByWhere( array('id','cat_id','category_name','product_name','product_price','sale_price','product_img','weight','weight_unit','quantity','product_short_desc') , TBL_PRODUCT_LIST , array('id' => trim($prdID)))->row();
			$data['categories'] = $this->CommonModel->selectOrderByWhereRecord(array('id','category_name'),'category_name','ASC',TBL_CATEGORY,array('status'=>1));
			$data['meta_title']	= 'Edit Product';
			$data['meta_desc']	= 'Edit Product Description';
			$data['content'] 	= 'admin/product/edit';
			$this->load->view('admin/layout_home', $data);
		}
	}
	
	/**
	* Load Delete Product Method
	* 
	* @param1       
	* @return       view page
	* @access       public
	* @author       M.K.Sah
	* @copyright    N/A
	* @link         application/Product
	* @since        12th Jan 2026
	* @deprecated   N/A
	**/
	
	public function delete($id, $file = ''){

		if (!ctype_digit($id)) {
			show_error('Invalid request. Please try again.', 400);
			exit();
		}
		$prdID = (int) $id;

		if($prdID !='' && $file != ''){
			$img_path = FCPATH.'uploads/product/'.$file;
			unlink($img_path);
		}
		$this->CommonModel->Delete(TBL_PRODUCT, $prdID, 'id');
		$this->CommonModel->Delete(TBL_PRODUCT_ATTRIBUTES, $prdID, 'product_id');
		$this->session->set_flashdata('success', 'The product has been successfully deleted.');
		redirect(base_url('adminex/list-product'));
	}
}
?>