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

class Services_model extends CI_Model {


	
	//Save Cutomers
	public function verify_and_save(){
		//Filtering XSS and html escape from user inputs 
		extract($this->security->xss_clean(html_escape(array_merge($this->data,$_POST))));
		
		// Initialize missing fields with default values
		$wholesale_price = isset($wholesale_price) ? $wholesale_price : 0;
		$retail_price = isset($retail_price) ? $retail_price : 0;
		$seller_points = isset($seller_points) ? $seller_points : 0;
		$custom_barcode = isset($custom_barcode) ? $custom_barcode : '';
		$description = isset($description) ? $description : '';
		$hsn = isset($hsn) ? $hsn : '';
		$sac = isset($sac) ? $sac : '';
		$discount_type = isset($discount_type) ? $discount_type : 'Percentage';
		$discount = isset($discount) ? $discount : 0;

		$this->db->trans_begin();
		$this->db->trans_strict(TRUE);

		$file_name='';
		if(!empty($_FILES['item_image']['name'])){

			$new_name = time();
			$config['file_name'] = $new_name;
			$config['upload_path']          = './uploads/items/';
	        $config['allowed_types']        = 'jpg|png|jpeg';
	        $config['max_size']             = 1024;
	        $config['max_width']            = 1500;
	        $config['max_height']           = 1500;
	       
	        $this->load->library('upload', $config);

	        if ( ! $this->upload->do_upload('item_image'))
	        {	
	                $error = array('error' => $this->upload->display_errors());
	                print($error['error']);
	                exit();
	        }
	        else
	        {		
	        	$file_name=$this->upload->data('file_name');
	        	/*Create Thumbnail*/
	        	$config['image_library'] = 'gd2';
				$config['source_image'] = 'uploads/items/'.$file_name;
				$config['create_thumb'] = TRUE;
				$config['maintain_ratio'] = TRUE;
				$config['width']         = 75;
				$config['height']       = 50;
				$this->load->library('image_lib', $config);
				$this->image_lib->resize();
				//end

	        	
	        }
		}
		
		//Validate This items already exist or not
		$store_id=(store_module() && is_admin()) ? $store_id : get_current_store_id();
		/*$query=$this->db->query("select * from db_items where upper(item_name)=upper('$item_name') and store_id=$store_id");
		if($query->num_rows()>0){
			return "Sorry! This Items Name already Exist.";
		}*/
		
		//Create items unique Number
		$this->db->query("ALTER TABLE db_items AUTO_INCREMENT = 1");
		//end

		
		//$stock = $current_opening_stock + $new_opening_stock;

		

		#------------------------------------
		$info = array(
							'count_id' 					=> get_count_id('db_items'), 
		    				'item_code' 				=> $item_code,//get_init_code('item'), 
		    				'item_name' 				=> $item_name,
		    				'category_id' 				=> $category_id,
		    				'price' 					=> $price,
		    				'tax_id' 					=> $tax_id,
		    				'purchase_price' 			=> $purchase_price,
		    				'tax_type' 					=> $tax_type,
		    				'sales_price' 				=> $sales_price,
		    				'wholesale_price' 			=> $wholesale_price,
		    				'retail_price' 				=> $retail_price,
		    				'item_currency_id' 		=> (!empty($service_currency_id)) ? $service_currency_id : get_base_currency()->id,
		    				'base_price' 				=> $sales_price,
		    				/*System Info*/
		    				'created_date' 				=> $CUR_DATE,
		    				'created_time' 				=> $CUR_TIME,
		    				'created_by' 				=> $CUR_USERNAME,
		    				'system_ip' 				=> $SYSTEM_IP,
		    				'system_name' 				=> $SYSTEM_NAME,
		    				'status' 					=> 1,
		    				'service_bit' 				=> 1,
		    				'seller_points'				=> $seller_points,
		    				'custom_barcode'			=> $custom_barcode,
		    				'description'				=> $description,
		    				'hsn'						=> $hsn,
		    				'sac'						=> $sac,
		    				'discount_type'				=> $discount_type,
		    				'discount'					=> $discount,
		    			);
		if(!empty($file_name)){
			$info['item_image'] = 'uploads/items/'.$file_name;
		}

		$info['store_id']=(store_module() && is_admin()) ? $store_id : get_current_store_id();	

		// Debug: Log the data being inserted
		log_message('debug', 'Services insert data: ' . print_r($info, TRUE));
		
		$query1 = $this->db->insert('db_items', $info);
		#------------------------------------
		if(!$query1){
			$this->db->trans_rollback();
			// Debug: Log the database error
			log_message('error', 'Services insert failed: ' . $this->db->last_query());
			log_message('error', 'Database error: ' . print_r($this->db->error(), TRUE));
			return "failed";
		}
		
		$item_id = $this->db->insert_id();
		
		$this->db->query("update db_items set expire_date=null where expire_date='0000-00-00'");
		$this->db->trans_commit();
		$this->session->set_flashdata('success', 'Success!! New Service Added Successfully!');
		return "success";
		
	}

	
	public function update_services(){
		//Filtering XSS and html escape from user inputs 
		extract($this->security->xss_clean(html_escape(array_merge($this->data,$_POST))));
		
		//Validate This items already exist or not
		$store_id=(store_module() && is_admin()) ? $store_id : get_current_store_id();
		$this->db->trans_begin();
		/*$query=$this->db->query("select * from db_items where upper(item_name)=upper('$item_name') and id<>$q_id and store_id=$store_id");
		if($query->num_rows()>0){
			return "This Items Name already Exist.";
		}
		else{*/

			$file_name=$item_image='';
			if(!empty($_FILES['item_image']['name'])){

				$new_name = time();
				$config['file_name'] = $new_name;
				$config['upload_path']          = './uploads/items/';
		        $config['allowed_types']        = 'jpg|png';
		        $config['max_size']             = 1024;
		        $config['max_width']            = 1500;
		        $config['max_height']           = 1500;
		       
		        $this->load->library('upload', $config);

		        if ( ! $this->upload->do_upload('item_image'))
		        {
		                $error = array('error' => $this->upload->display_errors());
		                print($error['error']);
		                exit();
		        }
		        else
		        {		
		        	$file_name=$this->upload->data('file_name');
		        	
		        	/*Create Thumbnail*/
		        	$config['image_library'] = 'gd2';
					$config['source_image'] = 'uploads/items/'.$file_name;
					$config['create_thumb'] = TRUE;
					$config['maintain_ratio'] = TRUE;
					$config['width']         = 75;
					$config['height']       = 50;
					$this->load->library('image_lib', $config);
					$this->image_lib->resize();
					//end

					//$item_image=" ,item_image='".$config['source_image']."' ";
					$item_image=$config['source_image'];

		        }
			}

			//$stock = $current_opening_stock + $new_opening_stock;
		

			$info = array(
		    				'item_name' 				=> $item_name,
		    				'item_code' 				=> $item_code,
		    				'category_id' 				=> $category_id,		    				
		    				'price' 					=> $price,
		    				'tax_id' 					=> $tax_id,
		    				'purchase_price' 			=> $purchase_price,
		    				'tax_type' 					=> $tax_type,
		    				'sales_price' 				=> $sales_price,
		    				'wholesale_price' 			=> $wholesale_price,
		    				'retail_price' 				=> $retail_price,
		    				'seller_points'				=> $seller_points,
		    				'custom_barcode'			=> $custom_barcode,
		    				'description'				=> $description,
		    				'hsn'						=> $hsn,
		    				'sac'						=> $sac,
		    				'discount_type'				=> $discount_type,
		    				'discount'					=> $discount,
		    			);
			//Image Path	
			if(!empty($file_name)){
				$info['item_image'] = 'uploads/items/'.$file_name;
			}

			//Store ID
			$info['store_id']=(store_module() && is_admin()) ? $store_id : get_current_store_id();	

			$query1 = $this->db->where('id',$q_id)->update('db_items', $info);


			if(!$query1){
				return "failed";
			}

			

			
			if ($query1){
				   $this->db->query("update db_items set expire_date=null where expire_date='0000-00-00'");
				   $this->db->trans_commit();
				   $this->session->set_flashdata('success', 'Success!! Service Item Updated Successfully!');
			        return "success";
			}
			else{
					$this->db->trans_rollback();
			        return "failed";
			}
		/*}*/
	}


}
