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

class Coupons extends CI_Controller {

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

		$orderbyfld = 'id';

		if (isset($param['couponCode']) && $param['couponCode'] != '') {
			$data['catID'] = $param['couponCode'];
			$where .= " id = '" . $param['couponCode'] . "' AND ";
		}
		if (isset($param['statusID']) && $param['statusID'] != '') {
			$data['statusD'] = $param['statusID'];
			$where .= " status = '" . $param['statusID'] . "' AND ";
		}else{
			$where .= " status = 1 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, 'DESC');
		$query = $this->CommonModel->RetriveRecordByWhere(TBL_COUPONS, $where_clause);
		$config['base_url']        = base_url() . "coupons?" . 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['couponFltr'] = $this->CommonModel->selectOrderByWhereRecord(array('id','coupon_code'),'id','DESC',TBL_COUPONS,array('status'=>1));
		$data['couponList'] = $this->CommonModel->selectOrderByWhereRecord(array('id','coupon_code','discount_type','discount_value','min_order_amount','expiry_date','status'),$orderbyfld,'DESC',TBL_COUPONS,$where_clause);
		
		$data['meta_title'] = 'Coupons List';
      	$data['meta_desc']  = 'Coupons List Description';
		$data['content'] 	= 'admin/coupons/index';
		$this->load->view('admin/layout_home', $data);
	}
	
	/**
	* Load Add Coupons Method
	* 
	* @param1       
	* @return       view page
	* @access       public
	* @author       M.K.Sah
	* @copyright    N/A
	* @link         application/Coupons
	* @since        27th Jan 2026
	* @deprecated   N/A
	**/
	
	public function add(){

		$params = $this->input->post();
		$params = array_map('trim', $params);
		$params = $this->security->xss_clean($params);

		//$this->form_validation->set_rules('coupon_code', 'Coupon Code', 'trim|required|callback_check_coupon_unique');
		$this->form_validation->set_rules('coupon_code', 'oupon name', 'trim|required|is_unique['.TBL_COUPONS.'.coupon_code]',array('is_unique' => 'This %s already exists.' ));

		if ($this->form_validation->run() === FALSE) {
			$data['status']   = 'validation_error';
			$data['msg']      = validation_errors();
			$data['csrfHash'] = $this->security->get_csrf_hash();
		} else {
			$insertArray = array(
				'coupon_code' 		=> $params['coupon_code'],
				'discount_type' 	=> $params['discount_type'],
				'discount_value' 	=> $params['discount_value'],
				'min_order_amount' 	=> $params['min_order_amount'],
				'expiry_date' 		=> date('Y-m-d 12:00:00', strtotime($params['expiry_date'])),
				'status' 			=> 1,
				'created_on' 		=> date('Y-m-d H:i:s')
			);
			$lastInsertId = $this->CommonModel->AddRecord($insertArray,TBL_COUPONS);

			if ($lastInsertId > 0) {
				$data['status'] = 'success';
				$data['msg']    = 'The oupon has been saved successfully.';
			} else {
				$data['status'] = 'error';
				$data['msg']    = 'Something went wrong while adding the oupon.';
			}

			$data['csrfHash'] = $this->security->get_csrf_hash();
		}
		echo json_encode($data);
	}
	
	
	/**
	* Load Delete Coupons Method
	* 
	* @param1       
	* @return       view page
	* @access       public
	* @author       M.K.Sah
	* @copyright    N/A
	* @link         application/Coupons
	* @since        27th Jan 2026
	* @deprecated   N/A
	**/
	
	public function check_coupon_unique($coupon_code)
	{
		$query = $this->CommonModel->getSelectedRecordByWhere(array('coupon_code'),TBL_COUPONS,array('coupon_code' => $coupon_code,'status' => 1));
		if ($query->num_rows() > 0) {
			$this->form_validation->set_message('check_coupon_unique', 'This coupon code already exists by Manoj.');
			return FALSE;
		}
		return TRUE;
	}
	
	
	public function delete($id){

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

		$prdID = (int) $id;
		$this->CommonModel->UpdateRecord(array('status' => 0),TBL_COUPONS,'id',$prdID);
		$this->session->set_flashdata('success', 'The coupons has been successfully deactivated.');
		redirect(base_url('adminex/list-coupons'));
	}
}
?>