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

class Dashboard extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		// Version check disabled - database already updated to 3.5
		// if($this->get_current_version_of_db()!=app_version()){ redirect(base_url('updates/update_db'),'refresh'); }
	}
	public function dashboard_values(){
		$this->load->model('dashboard_model');//Model
		$data=$this->dashboard_model->breadboard_values();//Model->Method
		echo json_encode($data);
	}

	public function test_dashboard_values(){
		$this->load->model('dashboard_model');//Model
		$data=$this->dashboard_model->breadboard_values();//Model->Method
		
		// Get sample sales data for debugging
		$this->db->select("grand_total, transaction_currency_id, exchange_rate, customer_id, sales_date");
		$this->db->from("db_sales");
		$this->db->where("sales_status", "Final");
		$this->db->where("store_id", get_current_store_id());
		$this->db->order_by("sales_date", "DESC");
		$this->db->limit(5);
		$sample_sales = $this->db->get()->result();
		
		// Get exchange rates for debugging
		$base_currency = get_base_currency();
		$exchange_rates = array();
		if ($base_currency) {
			$this->db->select("c.currency_code, c.currency_name, c.symbol, er.exchange_rate, er.from_currency_id, er.to_currency_id");
			$this->db->from("db_exchange_rates er");
			$this->db->join("db_currency c", "c.id = er.from_currency_id");
			$this->db->where("er.to_currency_id", $base_currency->id);
			$this->db->where("er.status", 1);
			$this->db->order_by("er.effective_date", "DESC");
			$exchange_rates = $this->db->get()->result();
		}
		
		// Test conversion with sample data
		$conversion_test = array();
		if (!empty($sample_sales)) {
			foreach ($sample_sales as $sale) {
				if (!empty($sale->transaction_currency_id) && $sale->transaction_currency_id != $base_currency->id) {
					$converted = convert_currency($sale->grand_total, $sale->transaction_currency_id, $base_currency->id);
					$conversion_test[] = array(
						'original_amount' => $sale->grand_total,
						'original_currency_id' => $sale->transaction_currency_id,
						'converted_amount' => $converted,
						'base_currency_id' => $base_currency->id,
						'exchange_rate_used' => get_exchange_rate($sale->transaction_currency_id, $base_currency->id)
					);
				}
			}
		}
		
		// Add debug information
		$debug_info = array(
			'base_currency' => $base_currency,
			'current_store_id' => get_current_store_id(),
			'date_filter' => $this->input->post('dates'),
			'user_permissions' => array(
				'is_admin' => is_admin(),
				'is_store_admin' => is_store_admin(),
				'current_user' => $this->session->userdata('inv_username')
			),
			'sample_sales' => $sample_sales,
			'exchange_rates' => $exchange_rates,
			'conversion_test' => $conversion_test
		);
		
		$response = array(
			'dashboard_data' => $data,
			'debug_info' => $debug_info,
			'timestamp' => date('Y-m-d H:i:s')
		);
		
		echo json_encode($response, JSON_PRETTY_PRINT);
	}

	public function index($val='')
	{	
	
		$this->load->model('dashboard_model');//Model

		$data=array_merge($this->data,$this->dashboard_model->get_bar_chart(),$this->dashboard_model->get_pie_chart());
		if(is_admin()){
			$data = array_merge($data,$this->dashboard_model->get_subscription_chart());
		}
		$data['page_title']=$this->lang->line('dashboard');
		if(isset($_POST['store_id'])){
			$data['store_id'] =$_POST['store_id'];
		}
		if(!$this->permissions('dashboard_view')){
			$this->load->view('role/dashboard_empty',$data);
		}
		else{
			$this->load->view('dashboard',$data);
		}
		
	}
	public function get_storewise_details($from='All'){

			//$from= $this->input->get_post('from');
			if(is_user()){
				$this->db->where("id!=1");
			}
			$q1=$this->db->select("*")->get("db_store");
		        if($q1->num_rows()>0){
		          $i=1;
		          foreach ($q1->result() as $row){
		          	
		          	/*SALES TOTAL*/
		            if($from=='Today'){
		          		$this->db->where("sales_date", date("Y-m-d"));
		          	}
		          	if($from=='Yesterday'){
		          		$this->db->where("sales_date", date("Y-m-d", strtotime("-1 day")));
		          	}
		          	if($from=='This Week'){
		          		$this->db->where("sales_date >= DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY)");
		          		$this->db->where("sales_date < DATE_ADD(DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY), INTERVAL 7 DAY)");
		          	}
		          	if($from=='Last Week'){
		          		$this->db->where("sales_date >= DATE_SUB(DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY), INTERVAL 7 DAY)");
		          		$this->db->where("sales_date < DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY)");
		          	}
		          	if($from=='This Month'){
		          		$this->db->where("sales_date >= DATE_FORMAT(NOW(), '%Y-%m-01')");
		          		$this->db->where("sales_date < DATE_ADD(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 1 MONTH)");
		          	}
		          	if($from=='Last Month'){
		          		$this->db->where("sales_date >= DATE_SUB(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 1 MONTH)");
		          		$this->db->where("sales_date < DATE_FORMAT(NOW(), '%Y-%m-01')");
		          	}
		          	if($from=='This Year'){
		          		$this->db->where("sales_date >= DATE_FORMAT(NOW(), '%Y-01-01')");
		          		$this->db->where("sales_date < DATE_ADD(DATE_FORMAT(NOW(), '%Y-01-01'), INTERVAL 1 YEAR)");
		          	}
		          	if($from=='Last Year'){
		          		$this->db->where("sales_date >= DATE_SUB(DATE_FORMAT(NOW(), '%Y-01-01'), INTERVAL 1 YEAR)");
		          		$this->db->where("sales_date < DATE_FORMAT(NOW(), '%Y-01-01')");
		          	}
		          	if($from=='Weekly'){
		          		$this->db->where("sales_date > DATE_SUB(NOW(), INTERVAL 1 WEEK)");
		          	}
		          	if($from=='Monthly'){
		          		$this->db->where("sales_date > DATE_SUB(NOW(), INTERVAL 1 MONTH)");
		          	}
		          	if($from=='Yearly'){
		          		$this->db->where("sales_date > DATE_SUB(NOW(), INTERVAL 1 YEAR)");
		          	}
		          	if($from=='Custom'){
		          		$from_date = $this->input->post('from_date');
		          		$to_date = $this->input->post('to_date');
		          		if(!empty($from_date) && !empty($to_date)){
		          			$this->db->where("sales_date >=", $from_date);
		          			$this->db->where("sales_date <=", $to_date);
		          		}
		          	}
		            $this->db->where("store_id",$row->id); 
		            $this->db->select("COALESCE(sum(grand_total),0) AS tot_sal_grand_total");
		            $this->db->from("db_sales");
		            $this->db->where("sales_status='Final'");
		            $sal_total=$this->db->get()->row()->tot_sal_grand_total;
		      		
		      		/*SALES DUE*/
		            if($from=='Today'){
		          		$this->db->where("sales_date", date("Y-m-d"));
		          	}
		          	if($from=='Yesterday'){
		          		$this->db->where("sales_date", date("Y-m-d", strtotime("-1 day")));
		          	}
		          	if($from=='This Week'){
		          		$this->db->where("sales_date >= DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY)");
		          		$this->db->where("sales_date < DATE_ADD(DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY), INTERVAL 7 DAY)");
		          	}
		          	if($from=='Last Week'){
		          		$this->db->where("sales_date >= DATE_SUB(DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY), INTERVAL 7 DAY)");
		          		$this->db->where("sales_date < DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY)");
		          	}
		          	if($from=='This Month'){
		          		$this->db->where("sales_date >= DATE_FORMAT(NOW(), '%Y-%m-01')");
		          		$this->db->where("sales_date < DATE_ADD(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 1 MONTH)");
		          	}
		          	if($from=='Last Month'){
		          		$this->db->where("sales_date >= DATE_SUB(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 1 MONTH)");
		          		$this->db->where("sales_date < DATE_FORMAT(NOW(), '%Y-%m-01')");
		          	}
		          	if($from=='This Year'){
		          		$this->db->where("sales_date >= DATE_FORMAT(NOW(), '%Y-01-01')");
		          		$this->db->where("sales_date < DATE_ADD(DATE_FORMAT(NOW(), '%Y-01-01'), INTERVAL 1 YEAR)");
		          	}
		          	if($from=='Last Year'){
		          		$this->db->where("sales_date >= DATE_SUB(DATE_FORMAT(NOW(), '%Y-01-01'), INTERVAL 1 YEAR)");
		          		$this->db->where("sales_date < DATE_FORMAT(NOW(), '%Y-01-01')");
		          	}
		          	if($from=='Weekly'){
		          		$this->db->where("sales_date > DATE_SUB(NOW(), INTERVAL 1 WEEK)");
		          	}
		          	if($from=='Monthly'){
		          		$this->db->where("sales_date > DATE_SUB(NOW(), INTERVAL 1 MONTH)");
		          	}
		          	if($from=='Yearly'){
		          		$this->db->where("sales_date > DATE_SUB(NOW(), INTERVAL 1 YEAR)");
		          	}
		          	if($from=='Custom'){
		          		$from_date = $this->input->post('from_date');
		          		$to_date = $this->input->post('to_date');
		          		if(!empty($from_date) && !empty($to_date)){
		          			$this->db->where("sales_date >=", $from_date);
		          			$this->db->where("sales_date <=", $to_date);
		          		}
		          	}
		            $this->db->where("store_id",$row->id); 
		            $this->db->select("COALESCE(sum(grand_total),0)-COALESCE(sum(paid_amount),0) AS sales_due_total");
		            $this->db->from("db_sales");
		            $this->db->where("sales_status='Final'");
		            $sales_due_total=$this->db->get()->row()->sales_due_total;

		            /*EXPENSE */
		            if($from=='Today'){
		          		$this->db->where("expense_date", date("Y-m-d"));
		          	}
		          	if($from=='Yesterday'){
		          		$this->db->where("expense_date", date("Y-m-d", strtotime("-1 day")));
		          	}
		          	if($from=='This Week'){
		          		$this->db->where("expense_date >= DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY)");
		          		$this->db->where("expense_date < DATE_ADD(DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY), INTERVAL 7 DAY)");
		          	}
		          	if($from=='Last Week'){
		          		$this->db->where("expense_date >= DATE_SUB(DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY), INTERVAL 7 DAY)");
		          		$this->db->where("expense_date < DATE_SUB(NOW(), INTERVAL WEEKDAY(NOW()) DAY)");
		          	}
		          	if($from=='This Month'){
		          		$this->db->where("expense_date >= DATE_FORMAT(NOW(), '%Y-%m-01')");
		          		$this->db->where("expense_date < DATE_ADD(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 1 MONTH)");
		          	}
		          	if($from=='Last Month'){
		          		$this->db->where("expense_date >= DATE_SUB(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 1 MONTH)");
		          		$this->db->where("expense_date < DATE_FORMAT(NOW(), '%Y-%m-01')");
		          	}
		          	if($from=='This Year'){
		          		$this->db->where("expense_date >= DATE_FORMAT(NOW(), '%Y-01-01')");
		          		$this->db->where("expense_date < DATE_ADD(DATE_FORMAT(NOW(), '%Y-01-01'), INTERVAL 1 YEAR)");
		          	}
		          	if($from=='Last Year'){
		          		$this->db->where("expense_date >= DATE_SUB(DATE_FORMAT(NOW(), '%Y-01-01'), INTERVAL 1 YEAR)");
		          		$this->db->where("expense_date < DATE_FORMAT(NOW(), '%Y-01-01')");
		          	}
		          	if($from=='Weekly'){
		          		$this->db->where("expense_date > DATE_SUB(NOW(), INTERVAL 1 WEEK)");
		          	}
		          	if($from=='Monthly'){
		          		$this->db->where("expense_date > DATE_SUB(NOW(), INTERVAL 1 MONTH)");
		          	}
		          	if($from=='Yearly'){
		          		$this->db->where("expense_date > DATE_SUB(NOW(), INTERVAL 1 YEAR)");
		          	}
		          	if($from=='Custom'){
		          		$from_date = $this->input->post('from_date');
		          		$to_date = $this->input->post('to_date');
		          		if(!empty($from_date) && !empty($to_date)){
		          			$this->db->where("expense_date >=", $from_date);
		          			$this->db->where("expense_date <=", $to_date);
		          		}
		          	}
		            $this->db->where("store_id",$row->id); 
		            // Use base_currency_amount if available, otherwise use expense_amt (for backward compatibility)
		            $this->db->select("COALESCE(SUM(CASE WHEN base_currency_amount IS NOT NULL AND base_currency_amount > 0 THEN base_currency_amount ELSE expense_amt END),0) AS exp_total");
		            $this->db->from("db_expense");
		            $exp_total=$this->db->get()->row()->exp_total;


		            echo "<tr>";
		            echo "<td>".$i++."</td>";
		            echo "<td>".$row->store_name."</td>";
		            echo "<td>".$this->store_wise_currency($row->id,store_number_format($sal_total))."</td>";
		            echo "<td>".$this->store_wise_currency($row->id,store_number_format($exp_total))."</td>";
		            echo "<td>".$this->store_wise_currency($row->id,store_number_format($sales_due_total))."</td>";
		            echo "</tr>";
		          }//foreach
		        }
		
	}

	public function ajax_list() {
		$this->load->model('dashboard_model','items');
		$list = $this->items->get_datatables();

		$data = array();
		$no = $_POST['start'];
		foreach ($list as $items) {
			$no++;
			$row = array();
			$row[] = $items->item_code;
			$row[] = $items->item_name;
			$row[] = $items->category_name;
			$row[] = $items->brand_name;
			$row[] = $items->stock;
			$data[] = $row;
		}

		$output = array(
			"draw" => $_POST['draw'],
			"recordsTotal" => $this->items->count_all(),
			"recordsFiltered" => $this->items->count_filtered(),
			"data" => $data,
		);
		//output to json format
		echo json_encode($output);
	}
	
	// Get enhanced stock alert data for dashboard (always return valid JSON for DataTables)
	public function get_enhanced_stock_alert() {
		// Send JSON headers first and clear any previous output so response is never HTML
		if (!headers_sent()) {
			header('Content-Type: application/json; charset=utf-8');
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header('X-Content-Type-Options: nosniff');
		}
		while (ob_get_level()) { ob_end_clean(); }
		$fallback = array(
			'out_of_stock_count' => 0,
			'critical_stock_count' => 0,
			'low_stock_count' => 0,
			'total_risk_value' => '',
			'stock_alert_items' => array()
		);
		try {
			$this->load->model('dashboard_model');
			$data = $this->dashboard_model->get_enhanced_stock_alert_data();
			if (!is_array($data) || !isset($data['stock_alert_items'])) {
				$data = $fallback;
			}
			// Ensure stock_alert_items is array of arrays (no objects that could break JSON)
			$data['stock_alert_items'] = array_values($data['stock_alert_items']);
			$json = json_encode($data);
			if ($json === false) {
				$json = json_encode($fallback);
			}
		} catch (Throwable $e) {
			log_message('error', 'get_enhanced_stock_alert: ' . $e->getMessage());
			$json = json_encode($fallback);
		}
		echo $json;
		exit;
	}

	// Sales at a glance: today and this week (for dashboard widget)
	public function get_sales_glance() {
		while (ob_get_level()) { ob_end_clean(); }
		header('Content-Type: application/json; charset=utf-8');
		try {
			$this->load->model('dashboard_model');
			$today = $this->dashboard_model->get_sales_total_for_period('today');
			$week = $this->dashboard_model->get_sales_total_for_period('week');
			$base = get_base_currency();
			$symbol = $base && isset($base->symbol) ? $base->symbol : '';
			echo json_encode(array(
				'success' => true,
				'today_sales' => $today,
				'week_sales' => $week,
				'today_formatted' => $this->currency(kmb($today)),
				'week_formatted' => $this->currency(kmb($week)),
				'currency_symbol' => $symbol
			));
		} catch (Throwable $e) {
			log_message('error', 'get_sales_glance: ' . $e->getMessage());
			echo json_encode(array('success' => false, 'today_sales' => 0, 'week_sales' => 0, 'today_formatted' => '0', 'week_formatted' => '0'));
		}
		exit;
	}

	// Top selling items for period (week or month)
	public function get_top_selling_items() {
		while (ob_get_level()) { ob_end_clean(); }
		header('Content-Type: application/json; charset=utf-8');
		$period = $this->input->get('period');
		if (!in_array($period, array('week', 'month'))) { $period = 'week'; }
		try {
			$this->load->model('dashboard_model');
			$items = $this->dashboard_model->get_top_selling_items($period);
			$base = get_base_currency();
			$symbol = $base && isset($base->symbol) ? $base->symbol : '';
			echo json_encode(array('success' => true, 'period' => $period, 'items' => $items, 'currency_symbol' => $symbol));
		} catch (Throwable $e) {
			log_message('error', 'get_top_selling_items: ' . $e->getMessage());
			echo json_encode(array('success' => false, 'period' => $period, 'items' => array(), 'currency_symbol' => ''));
		}
		exit;
	}
	
	// Debug method for stock alert
	public function debug_stock_alert() {
		$store_id = get_current_store_id();
		
		// Check items with alert_qty > 0
		$this->db->select("id, item_code, item_name, stock, alert_qty, status, service_bit, store_id, item_group");
		$this->db->from("db_items");
		$this->db->where("store_id", $store_id);
		$this->db->where("service_bit", 0);
		$this->db->where("status", 1);
		$this->db->where("COALESCE(alert_qty, 0) >", 0);
		$items_with_alert_qty = $this->db->get()->result();
		
		// Check low stock items
		$this->db->select("id, item_code, item_name, stock, alert_qty, status, service_bit, store_id, item_group");
		$this->db->from("db_items");
		$this->db->where("store_id", $store_id);
		$this->db->where("service_bit", 0);
		$this->db->where("status", 1);
		$this->db->where("item_group !=", "Variants");
		$this->db->where("COALESCE(alert_qty, 0) >", 0);
		$this->db->where("(stock <= alert_qty OR stock IS NULL)");
		$low_stock_items = $this->db->get()->result();
		
		$debug_data = array(
			'current_store_id' => $store_id,
			'items_with_alert_qty' => count($items_with_alert_qty),
			'low_stock_items' => count($low_stock_items),
			'items_with_alert_qty_sample' => array_slice($items_with_alert_qty, 0, 3),
			'low_stock_items_sample' => array_slice($low_stock_items, 0, 3),
			'query_used' => $this->db->last_query()
		);
		
		echo json_encode($debug_data, JSON_PRETTY_PRINT);
	}

	// Get expiring items for dashboard widget
	public function get_expiring_items() {
		// Allow both GET and POST requests
		$method = $this->input->method();
		
		try {
			// Get store_id filter
			$store_id = get_current_store_id();
			if(!is_admin() && !is_store_admin()){
				$store_id = get_current_store_id();
			}
			
			// Use db_item_batches as the authoritative source (accounts for sales, returns, adjustments)
			$where_conditions = array();
			$where_conditions[] = "i.batch_tracking_enabled = 1";
			$where_conditions[] = "ib.batch_number IS NOT NULL";
			$where_conditions[] = "ib.batch_number != ''";
			$where_conditions[] = "ib.expiry_date IS NOT NULL";
			$where_conditions[] = "ib.expiry_date != '0000-00-00'";
			$where_conditions[] = "ib.status = 1";
			$where_conditions[] = "ib.remaining_quantity > 0";
			$where_conditions[] = "DATEDIFF(ib.expiry_date, CURDATE()) <= 30";
			$where_conditions[] = "DATEDIFF(ib.expiry_date, CURDATE()) >= 0";
			
			if(!empty($store_id)){
				$where_conditions[] = "ib.store_id = " . (int)$store_id;
			}
			
			$where_clause = implode(' AND ', $where_conditions);
			
			// Get batches from db_item_batches that are expiring within 30 days
			$query = $this->db->query("
				SELECT 
					ib.item_id,
					i.item_name,
					i.item_code,
					ib.batch_number,
					ib.manufacturing_date,
					ib.expiry_date,
					ib.quantity as purchase_qty,
					(ib.quantity - ib.remaining_quantity) as sold_qty,
					ib.remaining_quantity,
					s.store_name,
					DATEDIFF(ib.expiry_date, CURDATE()) as days_until_expiry
				FROM db_item_batches ib
				JOIN db_items i ON ib.item_id = i.id
				LEFT JOIN db_store s ON s.id = ib.store_id
				WHERE $where_clause
				ORDER BY ib.expiry_date ASC
				LIMIT 10
			");
			
			$items = $query->result();
			
			// Format data for frontend
			$formatted_items = array();
			foreach ($items as $item) {
				$formatted_items[] = array(
					'item_id' => $item->item_id,
					'item_name' => $item->item_name,
					'item_code' => $item->item_code,
					'batch_number' => $item->batch_number,
					'expiry_date' => $item->expiry_date,
					'manufacturing_date' => $item->manufacturing_date,
					'remaining_quantity' => $item->remaining_quantity,
					'days_until_expiry' => $item->days_until_expiry,
					'store_name' => $item->store_name
				);
			}
			
			echo json_encode(array(
				'success' => true,
				'data' => $formatted_items
			));
			
		} catch (Exception $e) {
			echo json_encode(array(
				'success' => false,
				'message' => 'Error loading expiring items: ' . $e->getMessage()
			));
		}
	}

	// Get expired items for dashboard widget
	public function get_expired_items() {
		// Allow both GET and POST requests
		$method = $this->input->method();
		
		try {
			// Get store_id filter
			$store_id = get_current_store_id();
			if(!is_admin() && !is_store_admin()){
				$store_id = get_current_store_id();
			}
			
			// Use db_item_batches as the authoritative source (accounts for sales, returns, adjustments)
			$where_conditions = array();
			$where_conditions[] = "i.batch_tracking_enabled = 1";
			$where_conditions[] = "ib.batch_number IS NOT NULL";
			$where_conditions[] = "ib.batch_number != ''";
			$where_conditions[] = "ib.expiry_date IS NOT NULL";
			$where_conditions[] = "ib.expiry_date != '0000-00-00'";
			$where_conditions[] = "ib.status = 1";
			$where_conditions[] = "ib.remaining_quantity > 0";
			$where_conditions[] = "DATEDIFF(ib.expiry_date, CURDATE()) < 0";
			
			if(!empty($store_id)){
				$where_conditions[] = "ib.store_id = " . (int)$store_id;
			}
			
			$where_clause = implode(' AND ', $where_conditions);
			
			// Get batches from db_item_batches that have already expired
			$query = $this->db->query("
				SELECT 
					ib.item_id,
					i.item_name,
					i.item_code,
					ib.batch_number,
					ib.manufacturing_date,
					ib.expiry_date,
					ib.quantity as purchase_qty,
					(ib.quantity - ib.remaining_quantity) as sold_qty,
					ib.remaining_quantity,
					s.store_name,
					DATEDIFF(ib.expiry_date, CURDATE()) as days_until_expiry
				FROM db_item_batches ib
				JOIN db_items i ON ib.item_id = i.id
				LEFT JOIN db_store s ON s.id = ib.store_id
				WHERE $where_clause
				ORDER BY ib.expiry_date ASC
				LIMIT 10
			");
			
			$items = $query->result();
			
			// Format data for frontend
			$formatted_items = array();
			foreach ($items as $item) {
				$formatted_items[] = array(
					'item_id' => $item->item_id,
					'item_name' => $item->item_name,
					'item_code' => $item->item_code,
					'batch_number' => $item->batch_number,
					'expiry_date' => $item->expiry_date,
					'manufacturing_date' => $item->manufacturing_date,
					'remaining_quantity' => $item->remaining_quantity,
					'days_until_expiry' => $item->days_until_expiry,
					'store_name' => $item->store_name
				);
			}
			
			echo json_encode(array(
				'success' => true,
				'data' => $formatted_items
			));
			
		} catch (Exception $e) {
			echo json_encode(array(
				'success' => false,
				'message' => 'Error loading expired items: ' . $e->getMessage()
			));
		}
	}

}
