<?php
class Sales_return_types_model extends CI_Model {

	var $table = 'db_sales_return_types';
	var $column_order = array('sales_return_type_name','sales_return_type_initial','description','status',null);
	var $column_search = array('sales_return_type_name','sales_return_type_initial','description');
	var $order = array('sales_return_type_name' => 'asc');

	public function __construct()
	{
		parent::__construct();
	}

	private function _get_datatables_query()
	{
		$this->db->from($this->table);
		$store_id = get_current_store_id();
		$this->db->where('store_id', $store_id);
		
		// Debug logging
		error_log("Store ID being used: " . $store_id);
		error_log("Table: " . $this->table);

		$i = 0;
		foreach ($this->column_search as $item) {
			if($_POST['search']['value']) {
				if($i===0) {
					$this->db->group_start();
					$this->db->like($item, $_POST['search']['value']);
				} else {
					$this->db->or_like($item, $_POST['search']['value']);
				}

				if(count($this->column_search) - 1 == $i)
					$this->db->group_end();
			}
			$i++;
		}

		if(isset($_POST['order'])) {
			$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
		} else if(isset($this->order)) {
			$order = $this->order;
			$this->db->order_by(key($order), $order[key($order)]);
		}
	}

	function get_datatables()
	{
		$this->_get_datatables_query();
		if($_POST['length'] != -1)
		$this->db->limit($_POST['length'], $_POST['start']);
		
		$query = $this->db->get();
		return $query->result();
	}

	function count_filtered()
	{
		$this->_get_datatables_query();
		$query = $this->db->get();
		return $query->num_rows();
	}

	public function count_all()
	{
		$this->db->from($this->table);
		$this->db->where('store_id',get_current_store_id());
		return $this->db->count_all_results();
	}

	public function verify_and_save(){
		// Initialize data array
		if (!isset($this->data)) {
			$this->data = array();
		}
		
		// Filtering XSS and html escape from user inputs 
		extract($this->security->xss_clean(html_escape(array_merge($this->data,$_POST))));
		$store_id=(store_module() && is_admin()) ? $store_id : get_current_store_id();  	
		
		// Validate this sales return type already exists or not
		$query=$this->db->query("select * from db_sales_return_types where (upper(sales_return_type_name)=upper('$sales_return_type_name') OR upper(sales_return_type_initial)=upper('$sales_return_type_initial')) and store_id=$store_id");
		if($query->num_rows()>0){
			return "This Sales Return Type Name or Initial already Exists.";
		} else {
			$info = array(
				'store_id' 					=> $store_id,
				'sales_return_type_name' 	=> $sales_return_type_name, 
				'sales_return_type_initial' => strtoupper($sales_return_type_initial),
				'description' 				=> $description,
				'status'					=> 1,
			);

			$q1 = $this->db->insert('db_sales_return_types', $info);
		
			if ($q1){
				$this->session->set_flashdata('success', 'Success!! Sales Return Type Added Successfully!');
				return "success";
			} else {
				return "failed";
			}
		}
	}

	public function get_details($id,$data){
		// Validate this sales return type exists or not
		$query=$this->db->query("select * from db_sales_return_types where upper(id)=upper('$id')");
		if($query->num_rows()==0){
			show_404();exit;
		} else {
			$query=$query->row();
			$data['q_id']=$query->id;
			$data['sales_return_type_name']=$query->sales_return_type_name;
			$data['sales_return_type_initial']=$query->sales_return_type_initial;
			$data['description']=$query->description;
			$data['store_id']=$query->store_id;
			return $data;
		}
	}

	public function update_sales_return_type(){
		// Filtering XSS and html escape from user inputs 
		extract($this->security->xss_clean(html_escape($_POST)));
		$store_id=(store_module() && is_admin()) ? $store_id : get_current_store_id();  	
		
		// Validate this sales return type already exists or not (excluding current record)
		$query=$this->db->query("select * from db_sales_return_types where (upper(sales_return_type_name)=upper('$sales_return_type_name') OR upper(sales_return_type_initial)=upper('$sales_return_type_initial')) and id<>$q_id and store_id=$store_id");
		if($query->num_rows()>0){
			return "This Sales Return Type Name or Initial already Exists.";
		} else {
			$info = array(
				'sales_return_type_name' 	=> $sales_return_type_name, 
				'sales_return_type_initial' => strtoupper($sales_return_type_initial),
				'description' 				=> $description,
			);
			
			$info['store_id']=(store_module() && is_admin()) ? $store_id : get_current_store_id();

			$q1 = $this->db->where('id',$q_id)->where('store_id',$store_id)->update('db_sales_return_types', $info);
		
			if ($q1){
				$this->session->set_flashdata('success', 'Success!! Sales Return Type Updated Successfully!');
				return "success";
			} else {
				return "failed";
			}
		}
	}

	public function update_status($id,$status){
		if (set_status_of_table($id,$status,'db_sales_return_types')){
			$this->session->set_flashdata('success', 'Success!! Status Updated Successfully!');
			return "success";
		} else {
			$this->session->set_flashdata('error', 'Error!! Failed to Update Status!');
			return "failed";
		}
	}

	public function delete_sales_return_type($id){
		// Check if used in other tables before deleting
		// You can add checks here if sales return types are referenced in other tables
		
		$store_id=get_current_store_id();
		$q1=$this->db->where('id',$id)->where('store_id',$store_id)->delete('db_sales_return_types');
		
		if($q1){
			$this->session->set_flashdata('success', 'Success!! Sales Return Type Deleted Successfully!');
			return "success";
		} else {
			$this->session->set_flashdata('error', 'Error!! Failed to Delete Sales Return Type!');
			return "failed";
		}
	}

	//Get all active sales return types for dropdown
	public function get_all_active_sales_return_types(){
		$store_id = get_current_store_id();
		$this->db->select('id, sales_return_type_name, sales_return_type_initial');
		$this->db->where('store_id', $store_id);
		$this->db->where('status', 1);
		$this->db->order_by('sales_return_type_name', 'asc');
		$query = $this->db->get('db_sales_return_types');
		return $query->result();
	}
}
