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

class Reports_model extends CI_Model {

	public function show_supplier_items_report(){
		extract($_POST);

		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';

		if(!empty($store_id)){
			$this->db->where("store_id",$store_id);
		}
		if($item_id!=''){
			$this->db->where("id=$item_id");
		}
		$q1 = $this->db->select("*")->from("db_items");
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_grand_total=0;
			$tot_paid_amount=0;
			$tot_due_amount=0;
			foreach ($q1->result() as $res1) {
				

				// Enhanced query with multi-currency support
				$this->db->select("a.unit_total_cost,b.store_id,b.warehouse_id, b.id,a.item_id,b.supplier_id,b.purchase_code,b.purchase_date");
				$this->db->select("COALESCE(CASE WHEN b.transaction_currency_id IS NOT NULL AND b.transaction_currency_id != 1 AND b.exchange_rate IS NOT NULL THEN a.unit_total_cost / b.exchange_rate ELSE a.unit_total_cost END, 0) as unit_total_cost_base");
				$this->db->select("b.transaction_currency_id, cur.currency_code, cur.symbol");
				$this->db->from("db_purchaseitems a");
				$this->db->where("a.item_id",$res1->id);
				$this->db->from("db_purchase b");
				$this->db->where("a.purchase_id=b.id");
				$this->db->join("db_currency cur", "cur.id = b.transaction_currency_id", "left");
				

				if($supplier_id!=''){
					$this->db->where("b.supplier_id=$supplier_id");
				}
				if(!empty($store_id)){
					$this->db->where("b.store_id",$store_id);
				}
				$this->db->order_by("a.id","desc");
				//$this->db->limit(1);

				$q2=$this->db->get();
				if($q2->num_rows()>0){
					foreach ($q2->result() as $res2){
						$supplier_name = $this->db->select("supplier_name")->from("db_suppliers")->where("id",$res2->supplier_id)->get()->row()->supplier_name;
						
						$q3 = $this->db->select("*")->from("db_items")->where("id",$res2->item_id)->get()->row();
						$item_code = $q3->item_code;
						$item_name = $q3->item_name;

						echo "<tr>";
						echo "<td>".++$i."</td>";
						
						if(store_module() && is_admin()){
							echo "<td>".get_store_name($res2->store_id)."</td>";	
						}
						if(warehouse_module() && warehouse_count()>0){
							echo "<td>".get_warehouse_name($res2->warehouse_id)."</td>";	
						}
						echo "<td><a title='View Invoice' href='".base_url("purchase/invoice/$res2->id")."'>".$res2->purchase_code."</a></td>";
						echo "<td>".show_date($res2->purchase_date)."</td>";
						echo "<td>".$supplier_name."</td>";
						echo "<td>".$item_code."</td>";
						echo "<td>".$item_name."</td>";
						
						// Display price with currency information
						$currency_symbol = $res2->symbol ?: $base_currency_symbol;
						$currency_code = $res2->currency_code ?: $base_currency_code;
						
						if($res2->transaction_currency_id && $res2->transaction_currency_id != 1) {
							echo "<td class='text-right'>".store_number_format($res2->unit_total_cost)." <small>(".$currency_code.")</small></td>";
						} else {
							echo "<td class='text-right'>".store_number_format($res2->unit_total_cost)."</td>";
						}
						echo "</tr>";

					}
				}


			}

		}
		else{
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan=8>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}

	public function show_sales_report(){
		extract($_POST);

		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		// Initialize item type filter variables
		$item_type_filter = isset($item_type_filter) ? $item_type_filter : 'all';
		$show_breakdown = isset($show_breakdown) ? (int)$show_breakdown : 1;
		
		// Debug logging
		// log_message('debug', 'Service/Product Filter - item_type_filter: ' . $item_type_filter . ', show_breakdown: ' . $show_breakdown);

		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
				$this->db->where("a.warehouse_id",$warehouse_id);
		}

		// Enhanced query with multi-currency support
		$this->db->select("a.id,a.warehouse_id,a.sales_code,a.sales_date,b.customer_name,b.customer_code,a.grand_total,a.paid_amount,a.store_id,a.created_by");
		$this->db->select("COALESCE(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN a.grand_total / a.exchange_rate ELSE a.grand_total END, 0) as grand_total_base");
		$this->db->select("COALESCE(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN a.paid_amount / a.exchange_rate ELSE a.paid_amount END, 0) as paid_amount_base");
		$this->db->select("a.transaction_currency_id, cur.currency_code, cur.symbol, cur.currency_position");
		
		// Add service/product filtering logic - MUTUALLY EXCLUSIVE: Pure services vs Pure products vs Mixed
		if($item_type_filter != 'all') {
			if($item_type_filter == 'services') {
				// Sales that have services ONLY (all items must be services)
				// OR sales that have both services and products (mixed)
				$this->db->where("EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = a.id AND COALESCE(i.service_bit, 0) = 1)");
			} elseif($item_type_filter == 'products') {
				// Sales that have ONLY products (no services at all)
				$this->db->where("EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = a.id AND COALESCE(i.service_bit, 0) != 1)");
				$this->db->where("NOT EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = a.id AND COALESCE(i.service_bit, 0) = 1)");
			}
		}
	    
		if($customer_id!=''){
			
			$this->db->where("a.customer_id=$customer_id");
		}
		if($view_all=="no"){
			$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");
		}
		$this->db->where("b.`id`= a.`customer_id`");
		$this->db->from("db_sales as a");
		$this->db->join("db_currency cur", "cur.id = a.transaction_currency_id", "left");
		$this->db->where("a.`sales_status`= 'Final'");

		if(!empty($created_by)){
			$this->db->where("upper(a.created_by)=upper('$created_by')");
		}
		
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		$this->db->from("db_customers as b");
		if($show_account_receivable==1){
			$this->db->where("a.grand_total!=a.paid_amount");
		}
		
		// Debug: Log the final query
		// log_message('debug', 'Final Sales Report Query: ' . $this->db->get_compiled_select());
		
		$q1=$this->db->get();
		// log_message('debug', 'Sales Report Query returned ' . $q1->num_rows() . ' records');
		
		if($q1->num_rows()>0){
			$i=0;
			$tot_grand_total=0;
			$tot_paid_amount=0;
			$tot_due_amount=0;
			$tot_grand_total_base=0;
			$tot_paid_amount_base=0;
			$tot_due_amount_base=0;
			
			// Initialize service/product totals for breakdown
			$service_total = 0;
			$product_total = 0;
			$service_count = 0;
			$product_count = 0;
			
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				if(warehouse_module() && warehouse_count()>0){
					echo "<td>".get_warehouse_name($res1->warehouse_id)."</td>";	
				}
				if($store_id==get_current_store_id()){
				echo "<td><a title='View Invoice' href='".base_url("sales/invoice/$res1->id")."'>".$res1->sales_code."</a></td>";
				}
				else{
				echo "<td>".$res1->sales_code."</td>";	
				}
				echo "<td>".show_date($res1->sales_date)."</td>";
				echo "<td>".$res1->customer_code."</td>";
				echo "<td>".$res1->customer_name."</td>";
				
				// Format amounts with currency display using _format_currency_with_base
				$grand_total_display = $this->_format_currency_with_base($res1->grand_total, $res1->transaction_currency_id, $res1->grand_total_base, get_base_currency_id());
				$paid_amount_display = $this->_format_currency_with_base($res1->paid_amount, $res1->transaction_currency_id, $res1->paid_amount_base, get_base_currency_id());
				$due_amount_display = $this->_format_currency_with_base(($res1->grand_total-$res1->paid_amount), $res1->transaction_currency_id, ($res1->grand_total_base-$res1->paid_amount_base), get_base_currency_id());
				
				echo "<td class='text-right'>".$grand_total_display."</td>";
				echo "<td class='text-right'>".$paid_amount_display."</td>";
				echo "<td class='text-right'>".$due_amount_display."</td>";
				echo "<td>".$res1->created_by."</td>";
				echo "</tr>";
				// Calculate totals in base currency for accurate reporting
				$tot_grand_total+=$res1->grand_total_base;
				$tot_paid_amount+=$res1->paid_amount_base;
				$tot_due_amount+=($res1->grand_total_base-$res1->paid_amount_base);

			}

			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			// Determine the appropriate total label based on filter
			$total_label = "Total (".$base_currency_code.")";
			if($item_type_filter == 'services') {
				$total_label = "Total Services (".$base_currency_code.")";
			} elseif($item_type_filter == 'products') {
				$total_label = "Total Products (".$base_currency_code.")";
			}
			
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>".$total_label." :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_grand_total)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_paid_amount)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_due_amount)." ".$base_currency_symbol."</td>
					  <td></td>
				  </tr>";
			
			// Show service/product breakdown if requested and not filtering by specific type
			if($show_breakdown == 1 && $item_type_filter == 'all') {
				$this->_show_service_product_breakdown($from_date, $to_date, $store_id, $customer_id, $created_by, $warehouse_id, $base_currency_symbol, $base_currency_code, $total_columns_count);
			}
			
			// Payment Method Breakdown
			// if($this->permissions('payment_method_breakdown_report')){
				$this->_show_payment_method_breakdown($from_date, $to_date, $store_id, $customer_id, $created_by, $warehouse_id, $base_currency_symbol, $base_currency_code, $total_columns_count, $item_type_filter);
			// }
		}
		else{
			$total_columns_count=9;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}

	/**
	 * Show service/product breakdown in sales report
	 */
	private function _show_service_product_breakdown($from_date, $to_date, $store_id, $customer_id, $created_by, $warehouse_id, $base_currency_symbol, $base_currency_code, $total_columns_count) {
		try {
			// Build where clause for filtering
			$where_clause = "s.sales_status = 'Final' AND (s.sales_date >= '$from_date' AND s.sales_date <= '$to_date')";
			
			if(!empty($store_id)) {
				$where_clause .= " AND s.store_id = $store_id";
			}
			if(!empty($customer_id)) {
				$where_clause .= " AND s.customer_id = $customer_id";
			}
			if(!empty($created_by)) {
				$where_clause .= " AND UPPER(s.created_by) = UPPER('$created_by')";
			}
			if(warehouse_module() && warehouse_count() > 0 && !empty($warehouse_id)) {
				$where_clause .= " AND s.warehouse_id = $warehouse_id";
			}
			
			// Query to get service vs product totals - FIXED TO PROPERLY HANDLE NULL VALUES
			$sql = "
				SELECT 
					CASE 
						WHEN COALESCE(i.service_bit, 0) = 1 THEN 'Services'
						ELSE 'Products'
					END as item_type,
					COUNT(DISTINCT s.id) as transaction_count,
					COALESCE(SUM(CASE 
						WHEN s.transaction_currency_id IS NOT NULL AND s.transaction_currency_id != 1 AND s.exchange_rate IS NOT NULL 
						THEN si.total_cost / s.exchange_rate 
						ELSE si.total_cost 
					END), 0) as total_amount_base
				FROM db_sales s
				INNER JOIN db_salesitems si ON si.sales_id = s.id
				INNER JOIN db_items i ON i.id = si.item_id
				WHERE $where_clause
				GROUP BY 
					CASE 
						WHEN COALESCE(i.service_bit, 0) = 1 THEN 'Services'
						ELSE 'Products'
					END
				ORDER BY item_type DESC
			";
			
			$breakdown_result = $this->db->query($sql);
			
			if($breakdown_result->num_rows() > 0) {
				echo "<tr><td colspan='" . ($total_columns_count + 4) . "' style='border-top: 2px solid #333; padding: 15px 0;'></td></tr>";
				echo "<tr><td colspan='" . ($total_columns_count + 4) . "' class='text-center text-bold' style='background-color: #f8f9fa; padding: 12px; font-size: 16px;'><b>SERVICE vs PRODUCT BREAKDOWN</b></td></tr>";
				
				$grand_total_services = 0;
				$grand_total_products = 0;
				$total_transactions = 0;
				
				foreach($breakdown_result->result() as $breakdown) {
					$grand_total_services += ($breakdown->item_type == 'Services') ? $breakdown->total_amount_base : 0;
					$grand_total_products += ($breakdown->item_type == 'Products') ? $breakdown->total_amount_base : 0;
					$total_transactions += $breakdown->transaction_count;
					
					echo "<tr style='background-color: #f8f9fa;'>";
					echo "<td colspan='" . ($total_columns_count + 4) . "' class='text-left' style='padding: 8px 15px; font-size: 13px;'>";
					echo "<b>Total " . htmlspecialchars($breakdown->item_type) . ":</b> " . store_number_format($breakdown->total_amount_base) . " " . $base_currency_symbol;
					echo " <span style='color: #666; font-size: 11px;'>(" . $breakdown->transaction_count . " transactions)</span>";
					echo "</td>";
					echo "</tr>";
				}
				
				// Summary row
				echo "<tr style='background-color: #e8f4fd; border-top: 2px solid #007bff;'>";
				echo "<td colspan='" . ($total_columns_count + 4) . "' class='text-center' style='padding: 12px; font-size: 15px; font-weight: bold;'>";
				echo "<b>TOTAL SERVICES: " . store_number_format($grand_total_services) . " " . $base_currency_symbol . " | ";
				echo "TOTAL PRODUCTS: " . store_number_format($grand_total_products) . " " . $base_currency_symbol . " | ";
				echo "COMBINED TOTAL: " . store_number_format($grand_total_services + $grand_total_products) . " " . $base_currency_symbol . "</b>";
				echo "</td>";
				echo "</tr>";
				
			} else {
				echo "<tr><td colspan='" . ($total_columns_count + 4) . "' style='border-top: 2px solid #333; padding: 10px 0;'></td></tr>";
				echo "<tr><td colspan='" . ($total_columns_count + 4) . "' class='text-center text-info' style='background-color: #f8f9fa; padding: 8px; font-size: 14px;'><b>SERVICE vs PRODUCT BREAKDOWN</b></td></tr>";
				echo "<tr><td colspan='" . ($total_columns_count + 4) . "' class='text-center text-muted' style='padding: 8px;'>No service/product data found for the selected period</td></tr>";
			}
			
		} catch (Exception $e) {
			log_message('error', 'Service/Product Breakdown Error: ' . $e->getMessage());
			echo "<tr><td colspan='" . ($total_columns_count + 4) . "' class='text-center text-danger' style='padding: 8px;'>Error generating service/product breakdown: " . $e->getMessage() . "</td></tr>";
		}
	}

	public function show_sales_return_report(){
		extract($_POST);

		// Initialize variables with defaults
		$store_id = isset($store_id) ? $store_id : get_current_store_id();
		$customer_id = isset($customer_id) ? $customer_id : '';
		$warehouse_id = isset($warehouse_id) ? $warehouse_id : '';
		$from_date = isset($from_date) ? $from_date : '';
		$to_date = isset($to_date) ? $to_date : '';
		$view_all = isset($view_all) ? $view_all : 'no';

		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';

		$from_date = !empty($from_date) ? system_fromatted_date($from_date) : '';
		$to_date = !empty($to_date) ? system_fromatted_date($to_date) : '';

		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
			$this->db->where("a.warehouse_id",$warehouse_id);
		}

		// Enhanced query with multi-currency support
		$this->db->select("a.id, a.warehouse_id, a.return_code, a.return_date, b.customer_name, b.customer_code, a.grand_total, a.paid_amount, a.store_id, a.sales_id");
		$this->db->select("a.currency_id, a.exchange_rate, a.base_currency_total, a.customer_id");
		$this->db->select("COALESCE(c.sales_code, '') AS sales_code", false);
		$this->db->select("cur.currency_code, cur.symbol");

		$this->db->from("db_salesreturn as a");
		$this->db->join("db_customers as b", "b.id = a.customer_id", "left");
		$this->db->join('db_sales as c', 'c.id = a.sales_id', 'left');
		$this->db->join('db_currency as cur', 'cur.id = a.currency_id', 'left');

		if($customer_id!=''){
			$this->db->where("a.customer_id", $customer_id);
		}
		if($view_all=="no"){
			$this->db->where("a.return_date >=", $from_date);
			$this->db->where("a.return_date <=", $to_date);
		}

		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}

		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_grand_total=0;
			$tot_paid_amount=0;
			$tot_due_amount=0;
			foreach ($q1->result() as $res1) {
				// Convert to base currency
				$grand_total_base = $res1->grand_total;
				$paid_amount_base = $res1->paid_amount;
				
				if (!empty($res1->currency_id) && $res1->currency_id != $base_currency->id) {
					// Use base_currency_total if available (most accurate)
					if (!empty($res1->base_currency_total) && $res1->base_currency_total > 0) {
						$grand_total_base = $res1->base_currency_total;
						// Calculate paid_amount_base proportionally
						if ($res1->grand_total > 0) {
							$paid_amount_base = ($res1->paid_amount / $res1->grand_total) * $grand_total_base;
						}
					} else {
						// Convert using exchange_rate
						$grand_total_base = convert_currency($res1->grand_total, $res1->currency_id, $base_currency->id);
						$paid_amount_base = convert_currency($res1->paid_amount, $res1->currency_id, $base_currency->id);
					}
				} elseif (empty($res1->currency_id) && !empty($res1->customer_id)) {
					// For old records, try to get customer's trading currency
					$customer_currency = get_customer_trading_currency($res1->customer_id);
					if ($customer_currency && $customer_currency->id != $base_currency->id) {
						$grand_total_base = convert_currency($res1->grand_total, $customer_currency->id, $base_currency->id);
						$paid_amount_base = convert_currency($res1->paid_amount, $customer_currency->id, $base_currency->id);
					}
				}
				
				echo "<tr>";
				echo "<td class='text-center'>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";
				}
				if(warehouse_module() && warehouse_count()>0){
					echo "<td>".get_warehouse_name($res1->warehouse_id)."</td>";
				}
				if($store_id==get_current_store_id()){
					echo "<td><a title='View Invoice' href='".base_url("sales_return/invoice/$res1->id")."'>".$res1->return_code."</a></td>";
				} else {
					echo "<td>".$res1->return_code."</td>";
				}

				echo "<td>".show_date($res1->return_date)."</td>";

				$sales_id = isset($res1->sales_id) ? $res1->sales_id : '';
				echo (!empty($res1->sales_code) && !empty($sales_id)) ? "<td><a title='Return Raised Against this Invoice' href='".base_url("sales/invoice/".$sales_id)."'>".$res1->sales_code."</a></td>" : '<td>'.(!empty($res1->sales_code) ? $res1->sales_code : '-NA-').'</td>';
				echo "<td>".$res1->customer_name."</td>";

				// Display amounts with both party currency and base currency
				$currency_symbol = !empty($res1->symbol) ? $res1->symbol : $base_currency_symbol;
				$currency_code = !empty($res1->currency_code) ? $res1->currency_code : $base_currency_code;
				
				if (!empty($res1->currency_id) && $res1->currency_id != $base_currency->id) {
					// Multi-currency: show party currency and base currency
					$grand_total_display = store_number_format($res1->grand_total) . ' ' . $currency_symbol . 
						' (' . store_number_format($grand_total_base) . ' ' . $base_currency_symbol . ')';
					$paid_amount_display = store_number_format($res1->paid_amount) . ' ' . $currency_symbol . 
						' (' . store_number_format($paid_amount_base) . ' ' . $base_currency_symbol . ')';
					$due_amount_display = store_number_format(($res1->grand_total - $res1->paid_amount)) . ' ' . $currency_symbol . 
						' (' . store_number_format(($grand_total_base - $paid_amount_base)) . ' ' . $base_currency_symbol . ')';
				} else {
					// Base currency only
					$grand_total_display = store_number_format($grand_total_base) . ' ' . $base_currency_symbol;
					$paid_amount_display = store_number_format($paid_amount_base) . ' ' . $base_currency_symbol;
					$due_amount_display = store_number_format(($grand_total_base - $paid_amount_base)) . ' ' . $base_currency_symbol;
				}
				
				echo "<td class='text-right'>".$grand_total_display."</td>";
				echo "<td class='text-right'>".$paid_amount_display."</td>";
				echo "<td class='text-right'>".$due_amount_display."</td>";
				echo "</tr>";

				// Calculate totals in base currency
				$tot_grand_total += $grand_total_base;
				$tot_paid_amount += $paid_amount_base;
				$tot_due_amount += ($grand_total_base - $paid_amount_base);
			}

			// Colspan for sales return: #, Invoice No, Date, Sales Code, Customer = 5 base
			$total_columns_count = 5;
			if(store_module() && is_admin()){
				$total_columns_count++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count++;
			}
			echo "<tr class='bg-gray'>";
			echo "<td class='text-right' colspan='$total_columns_count' style='font-weight:bold;'>Total (".$base_currency_code.") :</td>";
			echo "<td class='text-right' style='font-weight:bold;'>".store_number_format($tot_grand_total)."</td>";
			echo "<td class='text-right' style='font-weight:bold;'>".store_number_format($tot_paid_amount)."</td>";
			echo "<td class='text-right' style='font-weight:bold;'>".store_number_format($tot_due_amount)."</td>";
			echo "</tr>";
		} else {
			$total_columns_count = 8;
			if(store_module() && is_admin()){
				$total_columns_count++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}

	    exit;
	}

	public function show_purchase_report(){
		extract($_POST);
		
		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
			$this->db->where("a.warehouse_id",$warehouse_id);
		}

		// Enhanced query with multi-currency support
		$this->db->select("a.id,a.warehouse_id,a.purchase_code,a.purchase_date,b.supplier_name,b.supplier_code,a.grand_total,a.paid_amount,a.store_id");
		$this->db->select("COALESCE(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN a.grand_total / a.exchange_rate ELSE a.grand_total END, 0) as grand_total_base");
		$this->db->select("COALESCE(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN a.paid_amount / a.exchange_rate ELSE a.paid_amount END, 0) as paid_amount_base");
		$this->db->select("a.transaction_currency_id, cur.currency_code, cur.symbol");
	    
		if($supplier_id!=''){
			$this->db->where("a.supplier_id=$supplier_id");
		}
		if($view_all=="no"){
			$this->db->where("(a.purchase_date>='$from_date' and a.purchase_date<='$to_date')");
		}
		$this->db->where("b.`id`= a.`supplier_id`");
		$this->db->from("db_purchase as a");
		$this->db->join("db_currency cur", "cur.id = a.transaction_currency_id", "left");
		$this->db->where("a.`purchase_status`= 'Received'");
		$this->db->from("db_suppliers as b");
		
		
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		if($show_account_payble==1){
			$this->db->where("a.grand_total!=a.paid_amount");
		}
		
		//echo $this->db->get_compiled_select();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_grand_total=0;
			$tot_paid_amount=0;
			$tot_due_amount=0;
			$tot_grand_total_base=0;
			$tot_paid_amount_base=0;
			$tot_due_amount_base=0;
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				if(warehouse_module() && warehouse_count()>0){
					echo "<td>".get_warehouse_name($res1->warehouse_id)."</td>";	
				}
				if($store_id==get_current_store_id()){
				echo "<td><a title='View Invoice' href='".base_url("purchase/invoice/$res1->id")."'>".$res1->purchase_code."</a></td>";
				}
				else{
				echo "<td>".$res1->purchase_code."</td>";	
				}

				
				echo "<td>".show_date($res1->purchase_date)."</td>";
				echo "<td>".$res1->supplier_code."</td>";
				echo "<td>".$res1->supplier_name."</td>";
				
				// Display amounts with currency info
				$currency_symbol = $res1->symbol ?: $base_currency_symbol;
				$currency_code = $res1->currency_code ?: $base_currency_code;
				
				// Show original amount with currency
				if($res1->transaction_currency_id && $res1->transaction_currency_id != 1) {
					echo "<td class='text-right'>".store_number_format($res1->grand_total)." <small>(".$currency_code.")</small></td>";
					echo "<td class='text-right'>".store_number_format($res1->paid_amount)." <small>(".$currency_code.")</small></td>";
					echo "<td class='text-right'>".store_number_format(($res1->grand_total-$res1->paid_amount))." <small>(".$currency_code.")</small></td>";
				} else {
					echo "<td class='text-right'>".store_number_format($res1->grand_total)."</td>";
					echo "<td class='text-right'>".store_number_format($res1->paid_amount)."</td>";
					echo "<td class='text-right'>".store_number_format(($res1->grand_total-$res1->paid_amount))."</td>";
				}
				
				echo "</tr>";
				
				// Calculate totals in base currency for accurate reporting
				$tot_grand_total+=$res1->grand_total_base;
				$tot_paid_amount+=$res1->paid_amount_base;
				$tot_due_amount+=($res1->grand_total_base-$res1->paid_amount_base);

			}
			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total (".$base_currency_code.") :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_grand_total)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_paid_amount)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_due_amount)."</td>
				  </tr>";
		}
		else{
			$total_columns_count=8;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}

	public function show_purchase_return_report(){
		extract($_POST);

		// Initialize variables with defaults
		$store_id = isset($store_id) ? $store_id : get_current_store_id();
		$supplier_id = isset($supplier_id) ? $supplier_id : '';
		$warehouse_id = isset($warehouse_id) ? $warehouse_id : '';
		$from_date = isset($from_date) ? $from_date : '';
		$to_date = isset($to_date) ? $to_date : '';
		$view_all = isset($view_all) ? $view_all : 'no';

		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';

		$from_date = !empty($from_date) ? system_fromatted_date($from_date) : '';
		$to_date = !empty($to_date) ? system_fromatted_date($to_date) : '';

		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
			$this->db->where("a.warehouse_id",$warehouse_id);
		}

		// Enhanced query with multi-currency support
		$this->db->select("a.id, a.warehouse_id, a.return_code, a.return_date, b.supplier_name, a.grand_total, a.paid_amount, a.store_id, a.purchase_id");
		$this->db->select("a.currency_id, a.exchange_rate, a.base_currency_total, a.supplier_id");
		$this->db->select("COALESCE(c.purchase_code, '') AS purchase_code", false);
		$this->db->select("cur.currency_code, cur.symbol");

		$this->db->from("db_purchasereturn as a");
		$this->db->join("db_suppliers as b", "b.id = a.supplier_id", "left");
		$this->db->join('db_purchase as c', 'c.id = a.purchase_id', 'left');
		$this->db->join('db_currency as cur', 'cur.id = a.currency_id', 'left');

		if($supplier_id!=''){
			$this->db->where("a.supplier_id", $supplier_id);
		}
		if($view_all=="no"){
			$this->db->where("a.return_date >=", $from_date);
			$this->db->where("a.return_date <=", $to_date);
		}

		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}

		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_grand_total=0;
			$tot_paid_amount=0;
			$tot_due_amount=0;
			foreach ($q1->result() as $res1) {
				// Convert to base currency
				$grand_total_base = $res1->grand_total;
				$paid_amount_base = $res1->paid_amount;
				
				if (!empty($res1->currency_id) && $res1->currency_id != $base_currency->id) {
					// Use base_currency_total if available (most accurate)
					if (!empty($res1->base_currency_total) && $res1->base_currency_total > 0) {
						$grand_total_base = $res1->base_currency_total;
						// Calculate paid_amount_base proportionally
						if ($res1->grand_total > 0) {
							$paid_amount_base = ($res1->paid_amount / $res1->grand_total) * $grand_total_base;
						}
					} else {
						// Convert using exchange_rate
						$grand_total_base = convert_currency($res1->grand_total, $res1->currency_id, $base_currency->id);
						$paid_amount_base = convert_currency($res1->paid_amount, $res1->currency_id, $base_currency->id);
					}
				} elseif (empty($res1->currency_id) && !empty($res1->supplier_id)) {
					// For old records, try to get supplier's trading currency
					$supplier_currency = get_supplier_trading_currency($res1->supplier_id);
					if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
						$grand_total_base = convert_currency($res1->grand_total, $supplier_currency->id, $base_currency->id);
						$paid_amount_base = convert_currency($res1->paid_amount, $supplier_currency->id, $base_currency->id);
					}
				}
				
				echo "<tr>";
				echo "<td class='text-center'>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";
				}
				if(warehouse_module() && warehouse_count()>0){
					echo "<td>".get_warehouse_name($res1->warehouse_id)."</td>";
				}
				if($store_id==get_current_store_id()){
					echo "<td><a title='View Invoice' href='".base_url("purchase_return/invoice/$res1->id")."'>".$res1->return_code."</a></td>";
				} else {
					echo "<td>".$res1->return_code."</td>";
				}

				echo "<td>".show_date($res1->return_date)."</td>";

				$purchase_id = isset($res1->purchase_id) ? $res1->purchase_id : '';
				echo (!empty($res1->purchase_code) && !empty($purchase_id)) ? "<td><a title='Return Raised Against this Invoice' href='".base_url("purchase/invoice/".$purchase_id)."'>".$res1->purchase_code."</a></td>" : '<td>'.(!empty($res1->purchase_code) ? $res1->purchase_code : '-NA-').'</td>';
				echo "<td>".$res1->supplier_name."</td>";

				// Display amounts with both party currency and base currency
				$currency_symbol = !empty($res1->symbol) ? $res1->symbol : $base_currency_symbol;
				$currency_code = !empty($res1->currency_code) ? $res1->currency_code : $base_currency_code;
				
				if (!empty($res1->currency_id) && $res1->currency_id != $base_currency->id) {
					// Multi-currency: show party currency and base currency
					$grand_total_display = store_number_format($res1->grand_total) . ' ' . $currency_symbol . 
						' (' . store_number_format($grand_total_base) . ' ' . $base_currency_symbol . ')';
					$paid_amount_display = store_number_format($res1->paid_amount) . ' ' . $currency_symbol . 
						' (' . store_number_format($paid_amount_base) . ' ' . $base_currency_symbol . ')';
					$due_amount_display = store_number_format(($res1->grand_total - $res1->paid_amount)) . ' ' . $currency_symbol . 
						' (' . store_number_format(($grand_total_base - $paid_amount_base)) . ' ' . $base_currency_symbol . ')';
				} else {
					// Base currency only
					$grand_total_display = store_number_format($grand_total_base) . ' ' . $base_currency_symbol;
					$paid_amount_display = store_number_format($paid_amount_base) . ' ' . $base_currency_symbol;
					$due_amount_display = store_number_format(($grand_total_base - $paid_amount_base)) . ' ' . $base_currency_symbol;
				}
				
				echo "<td class='text-right'>".$grand_total_display."</td>";
				echo "<td class='text-right'>".$paid_amount_display."</td>";
				echo "<td class='text-right'>".$due_amount_display."</td>";
				echo "</tr>";

				// Calculate totals in base currency
				$tot_grand_total += $grand_total_base;
				$tot_paid_amount += $paid_amount_base;
				$tot_due_amount += ($grand_total_base - $paid_amount_base);
			}

			// Colspan for purchase return: #, Invoice No, Date, Purchase Code, Supplier = 5 base
			$total_columns_count = 5;
			if(store_module() && is_admin()){
				$total_columns_count++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count++;
			}
			echo "<tr class='bg-gray'>";
			echo "<td class='text-right' colspan='$total_columns_count' style='font-weight:bold;'>Total (".$base_currency_code.") :</td>";
			echo "<td class='text-right' style='font-weight:bold;'>".store_number_format($tot_grand_total)."</td>";
			echo "<td class='text-right' style='font-weight:bold;'>".store_number_format($tot_paid_amount)."</td>";
			echo "<td class='text-right' style='font-weight:bold;'>".store_number_format($tot_due_amount)."</td>";
			echo "</tr>";
		} else {
			$total_columns_count = 8;
			if(store_module() && is_admin()){
				$total_columns_count++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}

	    exit;
	}

	public function show_expense_report(){
		extract($_POST);
		
		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';

		// Convert dates properly
$from_date = date('Y-m-d', strtotime($from_date));
$to_date   = date('Y-m-d', strtotime($to_date));

		/*$q1=$this->db->query("SELECT a.*,b.category_name from db_expense as a,db_expense_category as b where b.id=a.category_id and a.expense_date>='$from_date' and expense_date<='$to_date'");*/
		
		$this->db->select("a.*, b.category_name");
$this->db->select("a.base_currency_amount");
$this->db->select("a.expense_currency_id, cur.currency_code, cur.symbol");

$this->db->from("db_expense as a");

// âœ… JOINS
$this->db->join("db_expense_category as b", "b.id = a.category_id", "left");
$this->db->join("db_currency cur", "cur.id = a.expense_currency_id", "left");

// âœ… FILTERS
if(!empty($category_id)){
    $this->db->where("a.category_id", $category_id);
}

// âœ… ðŸ”¥ FIXED: ALWAYS APPLY DATE FILTER
$this->db->where("DATE(a.expense_date) >=", $from_date);
$this->db->where("DATE(a.expense_date) <=", $to_date);

if(!empty($store_id)){
    $this->db->where("a.store_id", $store_id);
}
		//echo $this->db->get_compiled_select();
		
		$q1=$this->db->get();
		
		if($q1->num_rows()>0){
			$i=0;
			$tot_expense_amt=0;
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				echo "<td>".$res1->expense_code."</td>";
				echo "<td>".show_date($res1->expense_date)."</td>";
				echo "<td>".$res1->category_name."</td>";
				echo "<td>".$res1->reference_no."</td>";
				echo "<td>".$res1->expense_for."</td>";
				
				// Use base currency amount if available, otherwise convert
				$expense_amt_base = 0;
				if (!empty($res1->base_currency_amount) && $res1->base_currency_amount > 0) {
					// Use pre-calculated base currency amount
					$expense_amt_base = $res1->base_currency_amount;
				} else {
					// Convert expense amount to base currency for display
					$expense_amt_base = convert_currency($res1->expense_amt, $res1->expense_currency_id, 1, $res1->store_id);
					
					// Fallback: if conversion returns 0 or fails, use original amount
					if ($expense_amt_base <= 0) {
						$expense_amt_base = $res1->expense_amt;
					}
				}
				
				// Debug: Show both original and converted amounts temporarily
				$debug_info = "";
				if (ENVIRONMENT === 'development') {
					$debug_info = " (Orig: " . store_number_format($res1->expense_amt) . ")";
				}
				echo "<td class='text-right'>".store_number_format($expense_amt_base).$debug_info."</td>";
				echo "<td>".$res1->note."</td>";
				echo "<td>".ucfirst($res1->created_by)."</td>";
				echo "</tr>";
				
				// Use base currency amount for total calculation
				$tot_expense_amt+=$expense_amt_base;
			}
			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total Expense :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_expense_amt)."</td>
					  <td colspan='2'></td>
				  </tr>";
		}
		else{
			$total_columns_count=8;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}
	public function show_stock_report(){
		extract($_POST);
		
		// Load helper
		$this->load->helper('multi_currency_helper');
		
		// Simple test to see if method is called
		log_message('debug', 'Stock Report Method Called');
		
		try {
		// Debug logging
		log_message('debug', 'Stock Report - Store ID: ' . $store_id . ', Brand ID: ' . $brand_id . ', Category ID: ' . $category_id . ', Warehouse ID: ' . $warehouse_id . ', From Date: ' . $from_date . ', To Date: ' . $to_date);
			
			// Get base currency info using global function
			$base_currency = get_base_currency($store_id);
			$base_currency_code = $base_currency ? $base_currency->currency_code : 'UGX';
			$base_currency_symbol = $base_currency ? $base_currency->symbol : 'USh';
			$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
			
			log_message('debug', 'Base Currency: ' . json_encode($base_currency));
			
			// Simple test first
			if(empty($store_id)) {
				$store_id = get_current_store_id();
			}

			if(!empty($store_id)){
				$this->db->where("a.store_id",$store_id);
			}
			if(!is_admin()){
				$this->db->where("a.store_id",get_current_store_id());
			}
			$this->db->select("a.sales_price,a.item_code,a.price,a.purchase_price,a.item_name,a.tax_type,a.store_id,a.id as item_id,a.item_group,
				d.category_name,
				c.brand_name,
				a.conversion_factor,
				");
			$this->db->select("b.tax_name");
			$this->db->select("u1.unit_name as main_unit_name");
			$this->db->select("u2.unit_name as alternate_unit_name");
			$this->db->from("db_items as a");

			$this->db->from("db_tax as b");
			$this->db->where("b.id=a.tax_id");
			$this->db->where("a.service_bit=0");
			$this->db->join("db_brands as c","c.id=a.brand_id","left");
			$this->db->join("db_category as d","d.id=a.category_id","left");
			$this->db->join("db_units as u1","u1.id=a.unit_id","left");
			$this->db->join("db_units as u2","u2.id=a.alternate_unit_id","left");

			if(!empty($brand_id)){
				$this->db->where("a.brand_id",$brand_id);
			}
			if(!empty($category_id)){
				$this->db->where("a.category_id",$category_id);
			}

			$q1=$this->db->get();
			$str='';

			if($q1->num_rows()>0){
				$i=0;
				$tot_stock = 0;
				$tot_stock_alt = 0; // Total alternate unit quantity
				$tot_value = 0;
				$tot_stock_value_by_purchase_price = 0;
				foreach ($q1->result() as $res1) {

					if($res1->item_group=='Variants'){continue;}

					$available_qty_wh = $this->get_available_qty($warehouse_id,$res1->store_id,$res1->item_id);

					// Calculate multi-unit quantities
					$qty_main = $available_qty_wh; // Stock is always in main unit
					$qty_alt = 0;
					$conversion_factor = !empty($res1->conversion_factor) ? floatval($res1->conversion_factor) : 0;
					
					if($conversion_factor > 0 && $qty_main > 0){
						$qty_alt = $qty_main * $conversion_factor;
					}

					// Convert prices to base currency if needed
					$sales_price_base = $res1->sales_price;
					$purchase_price_base = $res1->purchase_price;
					$unit_price_base = $res1->price;

					$value = $available_qty_wh * $sales_price_base;
					$stock_value_by_purchase_price = $available_qty_wh * $purchase_price_base;

					$tax_type = ($res1->tax_type=='Inclusive') ? 'Inc.' : 'Exc.';
					$str .= "<tr>";
					$str .= "<td>".++$i."</td>";
					if(store_module() && is_admin()){
						$str .= "<td>".$this->get_store_name($res1->store_id)."</td>";	
					}
					$str .= "<td>".$res1->item_code."</td>";
					$str .= "<td>".$res1->item_name."</td>";
					$str .= "<td>".$res1->brand_name."</td>";
					$str .= "<td>".$res1->category_name."</td>";
					$str .= "<td class='text-right'>".$this->format_currency($unit_price_base, $base_currency_symbol, $base_currency_position)."</td>";
					$str .= "<td>".$res1->tax_name."[".$tax_type."]</td>";
					$str .= "<td class='text-right'>".$this->format_currency($purchase_price_base, $base_currency_symbol, $base_currency_position)."</td>";
					$str .= "<td class='text-right'>".$this->format_currency($sales_price_base, $base_currency_symbol, $base_currency_position)."</td>";
					
					// Main Unit column
					$main_unit_col = $this->format_qty($qty_main);
					if(!empty($res1->main_unit_name)){
						$main_unit_col .= " " . strtolower($res1->main_unit_name);
					}
					$str .= "<td class='text-center'>".$main_unit_col."</td>";
					
					// Alternate Unit column
					if($conversion_factor > 0 && !empty($res1->alternate_unit_name)){
						$alt_unit_col = $this->format_qty($qty_alt) . " " . strtolower($res1->alternate_unit_name);
					} else {
						$alt_unit_col = "-";
					}
					$str .= "<td class='text-center'>".$alt_unit_col."</td>";
					
					$str .= "<td class='text-right'>".$this->format_currency($value, $base_currency_symbol, $base_currency_position)."</td>";
					$str .= "<td class='text-right'>".$this->format_currency($stock_value_by_purchase_price, $base_currency_symbol, $base_currency_position)."</td>";
					$str .= "</tr>";
					$tot_stock +=$available_qty_wh;
					$tot_stock_alt += $qty_alt; // Sum alternate unit quantities
					$tot_value +=$value;
					$tot_stock_value_by_purchase_price += $stock_value_by_purchase_price;
				}
				
				// Calculate colspan for "Total" label (from # to Sales Price)
				// Columns: #, Store (if admin), Item Code, Item Name, Brand, Category, Unit Price, Tax, Purchase Cost, Sales Price = 10 columns if admin, 9 if not
				$total_label_colspan = 9; // Base columns before Sales Price
				if(store_module() && is_admin()){
					$total_label_colspan = 10; // Add Store column
				}
				
				// Format alternate unit total
				$tot_alt_display = $this->format_qty($tot_stock_alt);
				
				$str .= "<tr class='bg-info text-bold'>
						  <td class='text-right' colspan='$total_label_colspan'><b>Total :</b></td>
						  <td class='text-center text-bold'>".$this->format_qty($tot_stock)."</td>
						  <td class='text-center text-bold'>".$tot_alt_display."</td>
						  <td class='text-right text-bold'>".$this->format_currency($tot_value, $base_currency_symbol, $base_currency_position)."</td>
						  <td class='text-right text-bold'>".$this->format_currency($tot_stock_value_by_purchase_price, $base_currency_symbol, $base_currency_position)."</td>
					  </tr>";
			}
			else{
				$total_columns_count=13;
				if(store_module() && is_admin()){
					$total_columns_count ++;
				}
				$str .= "<tr>";
				$str .= "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
				$str .= "</tr>";
			}
			
			return $str;
		} catch (Exception $e) {
			log_message('error', 'Stock Report Error: ' . $e->getMessage());
			return "<tr><td class='text-center text-danger' colspan='11'>Error loading report. Please try again.</td></tr>";
		}
	}
	public function brand_wise_stock(){
		extract($_POST);
		
		// Load helper
		$this->load->helper('multi_currency_helper');
		
		try {
			// Get base currency info using global function
			$base_currency = get_base_currency($store_id);
			$base_currency_code = $base_currency ? $base_currency->currency_code : 'UGX';
			$base_currency_symbol = $base_currency ? $base_currency->symbol : 'USh';
			$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';

			if(!empty($store_id)){
				$this->db->where("b.store_id",$store_id);
			}
			if(!is_admin()){
				$this->db->where("b.store_id",get_current_store_id());
			}
			$this->db->from("db_brands as b");
			$this->db->select("b.id,b.brand_name,b.store_id");
			if(!empty($brand_id)){
				$this->db->where("b.id",$brand_id);
			}

			$q1=$this->db->get();
			$str1='';
			if($q1->num_rows()>0){
				$i=0;
				$tot_stock=0;
				$tot_stock_value=0;
				foreach ($q1->result() as $res1) {
					$available_qty=0;
					$stock_value=0;
					$brand_id=$res1->id;
					$store_id=$res1->store_id;

					$str='';
					if(!empty($store_id)){
					     $str =" and i.store_id= $store_id ";
					}
					if(!empty($warehouse_id)){
				         $str .= " and wi.warehouse_id= $warehouse_id ";
				    }
					
					// Get stock quantity and value for this brand
					$q3 = "select 
							COALESCE(sum(wi.available_qty),0) as available_qty,
							COALESCE(sum(wi.available_qty * i.sales_price),0) as stock_value
							from db_warehouseitems wi
							join db_items i on wi.item_id = i.id
							where i.brand_id = $brand_id
							$str";

					$q3=$this->db->query($q3);
					$result = $q3->row();
					$available_qty = $result->available_qty;
					$stock_value = $result->stock_value;
					
					$str1 .= "<tr>";
					$str1 .= "<td>".++$i."</td>";
					if(store_module() && is_admin()){
						$str1 .= "<td>".$this->get_store_name($res1->store_id)."</td>";	
					}
					$str1 .= "<td>".$res1->brand_name."</td>";
					$str1 .= "<td class='text-center'>".$this->format_qty($available_qty)."</td>";
					$str1 .= "<td class='text-right'>".$this->format_currency($stock_value, $base_currency_symbol, $base_currency_position)."</td>";
					$str1 .= "</tr>";
					$tot_stock+=$available_qty;
					$tot_stock_value+=$stock_value;
				}
				$total_columns_count=3;
				if(store_module() && is_admin()){
					$total_columns_count ++;
				}
				$str1 .= "<tr class='bg-info text-bold'>";
				$str1 .= "<td></td>"; // Empty first column
				if(store_module() && is_admin()){
					$str1 .= "<td></td>"; // Empty store column if admin
				}
				$str1 .= "<td class='text-right'><b>Total :</b></td>";
				$str1 .= "<td class='text-center text-bold'>".$this->format_qty($tot_stock)."</td>";
				$str1 .= "<td class='text-right text-bold'>".$this->format_currency($tot_stock_value, $base_currency_symbol, $base_currency_position)."</td>";
				$str1 .= "</tr>";

			}
			else{
				$total_columns_count=4;
				if(store_module() && is_admin()){
					$total_columns_count ++;
				}
				$str1 .= "<tr>";
				$str1 .= "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
				$str1 .= "</tr>";
			}
			
			return $str1;
		} catch (Exception $e) {
			log_message('error', 'Brand Wise Stock Report Error: ' . $e->getMessage());
			return "<tr><td class='text-center text-danger' colspan='4'>Error loading report. Please try again.</td></tr>";
		}
	}
	
	
	// Helper method to format currency
	private function format_currency($amount, $symbol, $position) {
		try {
			// Remove decimal places if it's a whole number
			if($amount == floor($amount)) {
				$formatted_amount = number_format($amount, 0);
			} else {
				$formatted_amount = number_format($amount, 2);
			}
			
			if($position == 'before') {
				return $symbol . ' ' . $formatted_amount;
			} else {
				return $formatted_amount . ' ' . $symbol;
			}
		} catch (Exception $e) {
			log_message('error', 'Currency Format Error: ' . $e->getMessage());
			return $symbol . ' ' . number_format($amount, 0);
		}
	}
	
	// Helper method to format quantity
	private function format_qty($qty) {
		try {
			// Remove decimal places if it's a whole number
			if($qty == floor($qty)) {
				return number_format($qty, 0);
			} else {
				return number_format($qty, 2);
			}
		} catch (Exception $e) {
			log_message('error', 'Quantity Format Error: ' . $e->getMessage());
			return number_format($qty, 0);
		}
	}
	
	// Helper method to get available quantity
	public function get_available_qty($warehouse_id, $store_id, $item_id) {
		try {
			$this->db->select('COALESCE(SUM(available_qty), 0) as available_qty');
			$this->db->from('db_warehouseitems');
			$this->db->where('item_id', $item_id);
			
			// If specific warehouse is selected, filter by warehouse
			if(!empty($warehouse_id)) {
				$this->db->where('warehouse_id', $warehouse_id);
			}
			// If "All warehouse" is selected, sum from all warehouses for this store
			else {
				// Get all warehouses for this store
				$this->db->join('db_warehouse w', 'w.id = db_warehouseitems.warehouse_id');
				$this->db->where('w.store_id', $store_id);
			}
			
			$query = $this->db->get();
			if($query->num_rows() > 0) {
				return $query->row()->available_qty;
			}
			return 0;
		} catch (Exception $e) {
			log_message('error', 'Available Qty Error: ' . $e->getMessage());
			return 0;
		}
	}
	
	// Helper method to get store name
	private function get_store_name($store_id) {
		try {
			$this->db->select('store_name');
			$this->db->from('db_store');
			$this->db->where('id', $store_id);
			$query = $this->db->get();
			if($query->num_rows() > 0) {
				return $query->row()->store_name;
			}
			return 'Unknown Store';
		} catch (Exception $e) {
			log_message('error', 'Store Name Error: ' . $e->getMessage());
			return 'Unknown Store';
		}
	}
	
	public function show_item_sales_report(){
		extract($_POST);

		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
			$this->db->where("a.warehouse_id",$warehouse_id);
		}
		
		// Enhanced query with multi-currency support
		$this->db->select("a.id,a.sales_code,a.sales_date,b.customer_name,b.customer_code,a.grand_total,a.paid_amount,a.store_id,c.unit_total_cost,c.total_cost,e.category_name");
		$this->db->select("c.sales_qty,d.item_name");
		$this->db->select("COALESCE(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN c.unit_total_cost / a.exchange_rate ELSE c.unit_total_cost END, 0) as unit_total_cost_base");
		$this->db->select("COALESCE(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN c.total_cost / a.exchange_rate ELSE c.total_cost END, 0) as total_cost_base");
		$this->db->select("a.transaction_currency_id, a.exchange_rate, cur.currency_code, cur.symbol, cur.currency_position");
	    
		$this->db->from("db_sales as a");
		$this->db->where("a.`sales_status`= 'Final'");
		
		if($view_all=="no"){
			$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");
		}
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		$this->db->order_by("a.`sales_date`,a.sales_code",'desc');

		$str = "" ; 
		if($item_id!=''){
			$str = " and c.item_id=$item_id"; 
		}
		$this->db->join("db_salesitems as c","c.sales_id = a.id $str","left");

		$this->db->join("db_items as d","d.`id`= c.`item_id`","left");

		$str = "" ; 
		if($category_id!=''){
			$str = " and e.id=$category_id"; 
		}

		$this->db->join("db_category as e","e.`id`= d.`category_id` $str","right");
		$this->db->join("db_customers as b","b.`id`= a.`customer_id`","left");
		$this->db->join("db_currency cur", "cur.id = a.transaction_currency_id", "left");

		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_total_cost=0;
			$tot_total_cost_base=0;
			$tot_sales_qty=0;
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				if($store_id==get_current_store_id()){
				echo "<td><a title='View Invoice' href='".base_url("sales/invoice/$res1->id")."'>".$res1->sales_code."</a></td>";
				}
				else{
				echo "<td>".$res1->sales_code."</td>";	
				}

				echo "<td>".show_date($res1->sales_date)."</td>";
				echo "<td>".$res1->customer_name."</td>";
				echo "<td>".$res1->item_name."</td>";
				echo "<td>".$res1->category_name."</td>";
				echo "<td class='text-right'>".format_qty($res1->sales_qty)."</td>";
				// Format unit cost with currency display
				$unit_cost_display = $this->_format_currency_with_base($res1->unit_total_cost, $res1->transaction_currency_id, $res1->unit_total_cost_base, get_base_currency_id());
				echo "<td class='text-right'>".$unit_cost_display."</td>";
				
				// Format total cost with currency display
				$total_cost_display = $this->_format_currency_with_base($res1->total_cost, $res1->transaction_currency_id, $res1->total_cost_base, get_base_currency_id());
				echo "<td class='text-right'>".$total_cost_display."</td>";
				
				
				echo "</tr>";
				$tot_sales_qty+=$res1->sales_qty;
				$tot_total_cost+=$res1->total_cost;
				$tot_total_cost_base+=$res1->total_cost_base;
			}

			$total_columns_count=7; // #, Store Name (if admin), Invoice No, Sales Date, Customer Name, Item Name, Category
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}

			echo "<tr class='bg-primary'>
					  <td class='text-right text-bold'><b>Total :</b></td>";
			if(store_module() && is_admin()){
				echo "<td class='text-right text-bold'>-</td>"; // Store Name
			}
			echo "<td class='text-right text-bold'>-</td>"; // Invoice No
			echo "<td class='text-right text-bold'>-</td>"; // Sales Date
			echo "<td class='text-right text-bold'>-</td>"; // Customer Name
			echo "<td class='text-right text-bold'>-</td>"; // Item Name
			echo "<td class='text-right text-bold'>-</td>"; // Category
			echo "<td class='text-right text-bold'>".format_qty($tot_sales_qty)."</td>"; // Quantity
			echo "<td class='text-right text-bold'>-</td>"; // Unit Price
			echo "<td class='text-right text-bold'>".store_number_format($tot_total_cost_base)." ".$base_currency_symbol."</td>"; // Total
			echo "</tr>";
		}
		else{
			$total_columns_count=10; // All columns: #, Store Name (if admin), Invoice No, Sales Date, Customer Name, Item Name, Category, Quantity, Unit Price, Total
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}
	public function show_purchase_payments_report(){
		extract($_POST);
		$supplier_id = $this->input->post('supplier_id');

		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';

		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);
		
		// Enhanced query with multi-currency support
		$this->db->select("c.id,c.purchase_code,a.payment_date,b.supplier_name,b.supplier_code,a.payment_type,a.payment_note,a.payment,a.store_id");
		$this->db->select("COALESCE(a.base_currency_amount, a.payment) as payment_base");
	    
		if($supplier_id!=''){
			$this->db->where("c.supplier_id=$supplier_id");
		}
		$this->db->where("b.id=c.`supplier_id`");
		$this->db->where("(a.payment_date>='$from_date' and a.payment_date<='$to_date')");
		
		$this->db->where("c.id=a.purchase_id");

		$this->db->from("db_purchasepayments as a");
		$this->db->from("db_suppliers as b");
		$this->db->from("db_purchase as c");
		$this->db->where("c.`purchase_status`= 'Received'");
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_payment=0;
			$tot_payment_base=0;
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				if($res1->store_id==get_current_store_id()){
				echo "<td><a title='View Invoice' href='".base_url("purchase/invoice/$res1->id")."'>".$res1->purchase_code."</a></td>";
				}
				else{
				echo "<td>".$res1->purchase_code."</td>";	
				}

				echo "<td>".show_date($res1->payment_date)."</td>";
				echo "<td>".$res1->supplier_code."</td>";
				echo "<td>".$res1->supplier_name."</td>";
				echo "<td>".$res1->payment_type."</td>";
				echo "<td>".$res1->payment_note."</td>";
				echo "<td class='text-right'>".store_number_format($res1->payment_base)." ".$base_currency_symbol."</td>";
				
				
				echo "</tr>";
				$tot_payment+=$res1->payment;
				$tot_payment_base+=$res1->payment_base;
			}
			echo "<tr class='bg-primary'>
					  <td class='text-right text-bold'><b>Total :</b></td>";
			if(store_module() && is_admin()){
				echo "<td class='text-right text-bold'>-</td>"; // Store Name
			}
			echo "<td class='text-right text-bold'>-</td>"; // Purchase Invoice
			echo "<td class='text-right text-bold'>-</td>"; // Payment Date
			echo "<td class='text-right text-bold'>-</td>"; // Supplier ID
			echo "<td class='text-right text-bold'>-</td>"; // Supplier Name
			echo "<td class='text-right text-bold'>-</td>"; // Payment Type
			echo "<td class='text-right text-bold'>-</td>"; // Payment Note
			echo "<td class='text-right text-bold'>".store_number_format($tot_payment_base)." ".$base_currency_symbol."</td>"; // Paid Amount
			echo "</tr>";
		}
		else{
			$total_columns_count=9; // All columns: #, Store Name (if admin), Purchase Invoice, Payment Date, Supplier ID, Supplier Name, Payment Type, Payment Note, Paid Amount
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}
	public function show_sales_payments_report(){
		extract($_POST);
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);
		
		
		$this->db->select("c.id,c.sales_code,a.payment_date,b.customer_name,b.customer_code,a.payment_type,a.payment_note,a.payment,c.store_id,c.created_by");
		
	    $this->db->from("db_sales as c");
	    $this->db->where("c.id=a.sales_id and c.`sales_status`= 'Final'");
	    

	    if($customer_id!=''){
			$this->db->where("c.customer_id",$customer_id);
		}
		if(!empty($created_by)){
			$this->db->where("upper(c.created_by)=upper('$created_by')");
		}
		if(!empty($store_id)){
			$this->db->where("c.store_id",$store_id);
		}

		$str = '';
		if(!empty($payment_type)){
			$str .= " and a.payment_type = '$payment_type'";
		}

		$str .=(" and (a.payment_date>='$from_date' and a.payment_date<='$to_date')");

	    $this->db->join("db_salespayments as a","a.sales_id = c.id $str","left");

		$this->db->join("db_customers as b","b.id=c.`customer_id`","left");
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_payment=0;
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				if($res1->store_id==get_current_store_id()){
				echo "<td><a title='View Invoice' href='".base_url("sales/invoice/$res1->id")."'>".$res1->sales_code."</a></td>";
				}
				else{
				echo "<td>".$res1->sales_code."</td>";	
				}
				
				echo "<td>".show_date($res1->payment_date)."</td>";
				echo "<td>".$res1->customer_code."</td>";
				echo "<td>".$res1->customer_name."</td>";
				echo "<td>".$res1->payment_type."</td>";
				echo "<td>".$res1->payment_note."</td>";
				echo "<td class='text-right'>".store_number_format(($res1->payment))."</td>";
				echo "<td>".$res1->created_by."</td>";
				echo "</tr>";
				$tot_payment+=$res1->payment;
			}
			$total_columns_count=7;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_payment)."</td>
				  </tr>";
		}
		else{
			$total_columns_count=8;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}



	public function show_sales_return_payments_report(){
		extract($_POST);
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);
		
		
		$this->db->select("c.id,c.return_code,a.payment_date,b.customer_name,b.customer_code,a.payment_type,a.payment_note,a.payment,c.store_id,c.created_by");
		
	    $this->db->from("db_salesreturn as c");
	    $this->db->where("c.id=a.return_id");
	    

	    if($customer_id!=''){
			$this->db->where("c.customer_id",$customer_id);
		}
		if(!empty($created_by)){
			$this->db->where("upper(c.created_by)=upper('$created_by')");
		}
		if(!empty($store_id)){
			$this->db->where("c.store_id",$store_id);
		}

		$str = '';
		if(!empty($payment_type)){
			$str .= " and a.payment_type = '$payment_type'";
		}

		$str .=(" and (a.payment_date>='$from_date' and a.payment_date<='$to_date')");

	    $this->db->join("db_salespaymentsreturn as a","a.return_id = c.id $str","left");

		$this->db->join("db_customers as b","b.id=c.`customer_id`","left");
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_payment=0;
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				if($res1->store_id==get_current_store_id()){
				echo "<td><a title='View Invoice' href='".base_url("sales_return/invoice/$res1->id")."'>".$res1->return_code."</a></td>";
				}
				else{
				echo "<td>".$res1->return_code."</td>";	
				}
				
				echo "<td>".show_date($res1->payment_date)."</td>";
				echo "<td>".$res1->customer_code."</td>";
				echo "<td>".$res1->customer_name."</td>";
				echo "<td>".$res1->payment_type."</td>";
				echo "<td>".$res1->payment_note."</td>";
				echo "<td class='text-right'>".store_number_format(($res1->payment))."</td>";
				echo "<td>".$res1->created_by."</td>";
				echo "</tr>";
				$tot_payment+=$res1->payment;
			}
			$total_columns_count=7;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_payment)."</td>
				  </tr>";
		}
		else{
			$total_columns_count=8;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}


	/*Expired Items Report*/
	public function show_expired_items_report(){
		extract($_POST);

		
		//$to_date=date("Y-m-d",strtotime($to_date));
		$to_date = system_fromatted_date($to_date);

		$this->db->select("id,item_code,item_name,expire_date,stock,lot_number,store_id");
	    
		if($item_id!=''){
			
			$this->db->where("id=$item_id");
		}
		if($view_all=="no"){
			$this->db->where("(expire_date<='$to_date')");
		}
		$this->db->from("db_items");
		if(!empty($store_id)){
			$this->db->where("store_id",$store_id);
		}
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			foreach ($q1->result() as $res1) {
				if(get_total_qty_of_warehouse_item($res1->id,$warehouse_id,$res1->store_id) > 0 && !empty($warehouse_id)){
					echo "<tr>";
					echo "<td>".++$i."</td>";
					if(store_module() && is_admin()){
						echo "<td>".get_store_name($res1->store_id)."</td>";	
					}
					echo "<td>".$res1->item_code."</td>";
					echo "<td>".$res1->item_name."</td>";
					echo "<td>".$res1->lot_number."</td>";
					echo "<td>".show_date($res1->expire_date)."</td>";
					echo "<td>".format_qty(get_total_qty_of_warehouse_item($res1->id,$warehouse_id,$res1->store_id))."</td>";

				}
				else{
					echo "<tr>";
					echo "<td>".++$i."</td>";
					if(store_module() && is_admin()){
						echo "<td>".get_store_name($res1->store_id)."</td>";	
					}
					echo "<td>".$res1->item_code."</td>";
					echo "<td>".$res1->item_name."</td>";
					echo "<td>".$res1->lot_number."</td>";
					echo "<td>".show_date($res1->expire_date)."</td>";
					echo "<td>".format_qty($res1->stock)."</td>";
				}

			}
		}
		else{
			$total_columns_count=6;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}

	function _create_query($store_id='',$table_name,$table_column,$from_date,$to_date){
		$ids = array();

		if($table_column=='db_purchase'){
			$this->db->where("purchase_status='Received'");
		}
		else if($table_column=='db_sales'){
			$this->db->where("sales_status='Final'");
		}

		$this->db->where("(".$table_column.">='$from_date' and ".$table_column."<='$to_date')");

		if(is_admin()){
			if(!empty($store_id)){
				$this->db->where("store_id",$store_id);
			}
		}else{
			$this->db->where("store_id",get_current_store_id());
		}

		$this->db->select("id");
		$this->db->from($table_name);
		$query = $this->db->get();
		if($query->num_rows()>0){
			foreach ($query->result() as $res) {
				$ids[] = $res->id;
	    	}	
		}
		return (count($ids)>0) ? implode (", ", $ids) : 'null';
	}
	function _get_db_sales_ids($store_id='',$from_date,$to_date){

		return $this->_create_query($store_id,'db_sales','sales_date',$from_date,$to_date);

	}
	function _get_db_sales_return_ids($store_id='',$from_date,$to_date){

		return $this->_create_query($store_id,'db_salesreturn','return_date',$from_date,$to_date);

	}
	function _get_db_purchase_ids($store_id='',$from_date,$to_date){

		return $this->_create_query($store_id,'db_purchase','purchase_date',$from_date,$to_date);

	}
	function _get_db_purchase_return_ids($store_id='',$from_date,$to_date){

		return $this->_create_query($store_id,'db_purchasereturn','return_date',$from_date,$to_date);

	}
	function _get_db_expense_ids($store_id='',$from_date,$to_date){
		
		return $this->_create_query($store_id,'db_expense','expense_date',$from_date,$to_date);

	}

	public function get_comprehensive_pl_report(){
		$store_id = $this->input->post('store_id');
		$from_date = $this->input->post('from_date');
		$to_date = $this->input->post('to_date');
		$warehouse_id = $this->input->post('warehouse_id');
		$currency_id = $this->input->post('currency_id');
		
		// Debug logging
		log_message('debug', 'Comprehensive P&L Report - Store ID: ' . $store_id . ', From: ' . $from_date . ', To: ' . $to_date . ', Warehouse: ' . $warehouse_id . ', Currency: ' . $currency_id);
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		$sales_ids = $this->_get_db_sales_ids($store_id, $from_date, $to_date);
		$sales_return_ids = $this->_get_db_sales_return_ids($store_id, $from_date, $to_date);
		$purchase_ids = $this->_get_db_purchase_ids($store_id, $from_date, $to_date);
		$purchase_return_ids = $this->_get_db_purchase_return_ids($store_id, $from_date, $to_date);
		$expense_ids = $this->_get_db_expense_ids($store_id, $from_date, $to_date);

		$report_data = array();

		// SALES DATA
		$report_data['sales'] = $this->_get_sales_summary($sales_ids, $warehouse_id);
		
		// SALES RETURN DATA
		$report_data['sales_return'] = $this->_get_sales_return_summary($sales_return_ids, $warehouse_id);
		
		// COST OF GOODS SOLD (COGS) - Calculate from actual sales items, not all purchases
		// This is the correct accounting method: COGS = cost of items actually sold
		$report_data['cogs'] = $this->_get_cogs_from_sales($sales_ids, $warehouse_id);
		$report_data['cogs_return'] = $this->_get_cogs_from_sales_returns($sales_return_ids, $warehouse_id);
		
		// PURCHASE DATA (for reference/information only - not used in COGS calculation)
		$report_data['purchase'] = $this->_get_purchase_summary($purchase_ids, $warehouse_id);
		
		// PURCHASE RETURN DATA (for reference/information only)
		$report_data['purchase_return'] = $this->_get_purchase_return_summary($purchase_return_ids, $warehouse_id);
		
		// EXPENSE DATA
		$report_data['expenses'] = $this->_get_expense_summary($expense_ids);
		
		// TAX DATA
		$report_data['sales_tax'] = $this->_get_sales_tax_summary($sales_ids, $warehouse_id);
		
		// Ensure all values are numeric
		$report_data['sales']['total'] = floatval($report_data['sales']['total']);
		$report_data['sales_return']['total'] = floatval($report_data['sales_return']['total']);
		$report_data['cogs']['total'] = floatval($report_data['cogs']['total']);
		$report_data['cogs_return']['total'] = floatval($report_data['cogs_return']['total']);
		$report_data['purchase']['total'] = floatval($report_data['purchase']['total']);
		$report_data['purchase_return']['total'] = floatval($report_data['purchase_return']['total']);
		$report_data['expenses']['total'] = floatval($report_data['expenses']['total']);
		$report_data['sales_tax']['total'] = floatval($report_data['sales_tax']['total']);
		
		// CALCULATE GROSS PROFIT
		// Gross Profit = Net Sales - COGS (cost of items actually sold)
		$net_sales = $report_data['sales']['total'] - $report_data['sales_return']['total'];
		$net_cogs = $report_data['cogs']['total'] - $report_data['cogs_return']['total'];
		$gross_profit = $net_sales - $net_cogs;
		$report_data['gross_profit'] = $gross_profit;
		
		// CALCULATE NET PROFIT
		$net_profit = $gross_profit - $report_data['expenses']['total'] - $report_data['sales_tax']['total'];
		$report_data['net_profit'] = $net_profit;

		// CURRENCY CONVERSION
		if (!empty($currency_id)) {
			$report_data = $this->_convert_currency_data($report_data, $currency_id, $store_id);
		}

		// Debug logging
		log_message('debug', 'Comprehensive P&L Report - Final data: ' . json_encode($report_data));

		return $report_data;
	}

	private function _convert_currency_data($report_data, $currency_id, $store_id) {
		// Get base currency
		$base_currency = get_base_currency($store_id);
		if (!$base_currency) {
			return $report_data;
		}

		// Get target currency info
		$this->db->select('*');
		$this->db->from('db_currency');
		$this->db->where('id', $currency_id);
		$this->db->where('status', 1);
		$query = $this->db->get();
		$target_currency = $query->row();

		if (!$target_currency) {
			return $report_data;
		}

		// Get exchange rate
		$exchange_rate = get_exchange_rate($base_currency->id, $currency_id, $store_id);
		if ($exchange_rate === false) {
			$exchange_rate = 1.0; // Fallback to 1:1 if no rate found
		}

		// Convert all amounts
		$report_data['sales']['total'] = $report_data['sales']['total'] * $exchange_rate;
		$report_data['sales_return']['total'] = $report_data['sales_return']['total'] * $exchange_rate;
		$report_data['purchase']['total'] = $report_data['purchase']['total'] * $exchange_rate;
		$report_data['purchase_return']['total'] = $report_data['purchase_return']['total'] * $exchange_rate;
		$report_data['expenses']['total'] = $report_data['expenses']['total'] * $exchange_rate;
		$report_data['sales_tax']['total'] = $report_data['sales_tax']['total'] * $exchange_rate;
		$report_data['gross_profit'] = $report_data['gross_profit'] * $exchange_rate;
		$report_data['net_profit'] = $report_data['net_profit'] * $exchange_rate;

		// Add currency info
		$report_data['currency_info'] = array(
			'currency_id' => $currency_id,
			'currency_name' => $target_currency->currency_name,
			'symbol' => $target_currency->currency_symbol ?: $target_currency->symbol,
			'position' => $target_currency->currency_position ?: 'before',
			'exchange_rate' => $exchange_rate,
			'base_currency' => $base_currency->currency_name
		);

		return $report_data;
	}

	private function _convert_to_base_currency_professional($info, $store_id) {
		// Get base currency
		$base_currency = get_base_currency($store_id);
		if (!$base_currency) {
			// Fallback to default currency if base currency not found
			$this->db->select('*');
			$this->db->from('db_currency');
			$this->db->where('is_base_currency', 1);
			$this->db->where('status', 1);
			$this->db->limit(1);
			$base_currency = $this->db->get()->row();
		}

		// Add base currency info
		$info['currency_info'] = array(
			'currency_id' => $base_currency ? $base_currency->id : 1,
			'currency_name' => $base_currency ? $base_currency->currency_name : 'Ugandan Shilling',
			'currency_code' => $base_currency ? $base_currency->currency_code : 'UGX',
			'symbol' => $base_currency ? ($base_currency->currency_symbol ?: $base_currency->symbol) : 'USh',
			'position' => $base_currency ? ($base_currency->currency_position ?: 'before') : 'before',
			'exchange_rate' => 1.0,
			'base_currency' => $base_currency ? $base_currency->currency_name : 'Ugandan Shilling',
			'is_base_currency' => true
		);

		// The amounts are already in base currency from the database queries
		// since we're using base_currency_amount fields where available
		// and the system automatically converts to base currency when storing transactions

		return $info;
	}

	private function _get_sales_summary($sales_ids, $warehouse_id = '') {
		if ($sales_ids == 'null') {
			return array('total' => 0, 'count' => 0);
		}

		try {
			// Reset query builder to avoid alias conflicts
			$this->db->reset_query();
			
			$base_currency_id = get_base_currency_id();
			// Use base_currency_total if available, otherwise convert grand_total using exchange_rate
			$this->db->select("COALESCE(SUM(CASE 
				WHEN base_currency_total IS NOT NULL AND base_currency_total > 0 
				THEN base_currency_total 
				WHEN transaction_currency_id IS NOT NULL AND transaction_currency_id != $base_currency_id AND exchange_rate IS NOT NULL AND exchange_rate > 0 
				THEN grand_total / exchange_rate 
				ELSE grand_total 
			END),0) AS total, COUNT(*) AS count");
			$this->db->from("db_sales");
			$this->db->where("id IN ($sales_ids)");
			$this->db->where("sales_status", "Final");
			
			if (!empty($warehouse_id)) {
				$this->db->where("warehouse_id", $warehouse_id);
			}

			$query = $this->db->get();
			$result = $query->row();
			
			return array(
				'total' => $result->total,
				'count' => $result->count
			);
		} catch (Exception $e) {
			log_message('error', 'Sales summary error: ' . $e->getMessage());
			return array('total' => 0, 'count' => 0);
		}
	}

	private function _get_sales_return_summary($sales_return_ids, $warehouse_id = '') {
		if ($sales_return_ids == 'null') {
			return array('total' => 0, 'count' => 0);
		}

		try {
			// Reset query builder to avoid alias conflicts
			$this->db->reset_query();
			
			$base_currency_id = get_base_currency_id();
			// Use base_currency_total if available, otherwise convert grand_total using exchange_rate
			$this->db->select("COALESCE(SUM(CASE 
				WHEN base_currency_total IS NOT NULL AND base_currency_total > 0 
				THEN base_currency_total 
				WHEN transaction_currency_id IS NOT NULL AND transaction_currency_id != $base_currency_id AND exchange_rate IS NOT NULL AND exchange_rate > 0 
				THEN grand_total / exchange_rate 
				ELSE grand_total 
			END),0) AS total, COUNT(*) AS count");
			$this->db->from("db_salesreturn");
			$this->db->where("id IN ($sales_return_ids)");
			$this->db->where("return_status", "Final");
			
			if (!empty($warehouse_id)) {
				$this->db->where("warehouse_id", $warehouse_id);
			}

			$query = $this->db->get();
			$result = $query->row();
			
			return array(
				'total' => $result->total,
				'count' => $result->count
			);
		} catch (Exception $e) {
			log_message('error', 'Sales return summary error: ' . $e->getMessage());
			return array('total' => 0, 'count' => 0);
		}
	}

	private function _get_purchase_summary($purchase_ids, $warehouse_id = '') {
		if ($purchase_ids == 'null') {
			return array('total' => 0, 'count' => 0);
		}

		try {
			// Reset query builder to avoid alias conflicts
			$this->db->reset_query();
			
			$base_currency_id = get_base_currency_id();
			// Use base_currency_total if available, otherwise convert grand_total using exchange_rate
			$this->db->select("COALESCE(SUM(CASE 
				WHEN base_currency_total IS NOT NULL AND base_currency_total > 0 
				THEN base_currency_total 
				WHEN transaction_currency_id IS NOT NULL AND transaction_currency_id != $base_currency_id AND exchange_rate IS NOT NULL AND exchange_rate > 0 
				THEN grand_total / exchange_rate 
				ELSE grand_total 
			END),0) AS total, COUNT(*) AS count");
			$this->db->from("db_purchase");
			$this->db->where("id IN ($purchase_ids)");
			$this->db->where("purchase_status", "Received");
			
			if (!empty($warehouse_id)) {
				$this->db->where("warehouse_id", $warehouse_id);
			}

			$query = $this->db->get();
			$result = $query->row();
			
			return array(
				'total' => $result->total,
				'count' => $result->count
			);
		} catch (Exception $e) {
			log_message('error', 'Purchase summary error: ' . $e->getMessage());
			return array('total' => 0, 'count' => 0);
		}
	}

	private function _get_purchase_return_summary($purchase_return_ids, $warehouse_id = '') {
		if ($purchase_return_ids == 'null') {
			return array('total' => 0, 'count' => 0);
		}

		try {
			// Reset query builder to avoid alias conflicts
			$this->db->reset_query();
			
			$base_currency_id = get_base_currency_id();
			// Use base_currency_total if available, otherwise convert grand_total using exchange_rate
			$this->db->select("COALESCE(SUM(CASE 
				WHEN base_currency_total IS NOT NULL AND base_currency_total > 0 
				THEN base_currency_total 
				WHEN transaction_currency_id IS NOT NULL AND transaction_currency_id != $base_currency_id AND exchange_rate IS NOT NULL AND exchange_rate > 0 
				THEN grand_total / exchange_rate 
				ELSE grand_total 
			END),0) AS total, COUNT(*) AS count");
			$this->db->from("db_purchasereturn");
			$this->db->where("id IN ($purchase_return_ids)");
			$this->db->where("return_status", "Final");
			
			if (!empty($warehouse_id)) {
				$this->db->where("warehouse_id", $warehouse_id);
			}

			$query = $this->db->get();
			$result = $query->row();
			
			return array(
				'total' => $result->total,
				'count' => $result->count
			);
		} catch (Exception $e) {
			log_message('error', 'Purchase return summary error: ' . $e->getMessage());
			return array('total' => 0, 'count' => 0);
		}
	}

	private function _get_expense_summary($expense_ids) {
		if ($expense_ids == 'null') {
			return array('total' => 0, 'count' => 0);
		}

		try {
			// Reset query builder to avoid alias conflicts
			$this->db->reset_query();
			
			// 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 total, COUNT(*) AS count");
			$this->db->from("db_expense");
			$this->db->where("id IN ($expense_ids)");

			$query = $this->db->get();
			$result = $query->row();
			
			return array(
				'total' => $result->total,
				'count' => $result->count
			);
		} catch (Exception $e) {
			log_message('error', 'Expense summary error: ' . $e->getMessage());
			return array('total' => 0, 'count' => 0);
		}
	}

	private function _get_sales_tax_summary($sales_ids, $warehouse_id = '') {
		if ($sales_ids == 'null') {
			return array('total' => 0);
		}

		try {
			// Reset query builder to avoid alias conflicts
			$this->db->reset_query();
			
			$this->db->select("COALESCE(SUM(tax_amt),0) AS total");
			$this->db->from("db_salesitems");
			$this->db->where("sales_id IN ($sales_ids)");
			
			if (!empty($warehouse_id)) {
				$this->db->join("db_sales as s_tax", "s_tax.id = db_salesitems.sales_id");
				$this->db->where("s_tax.warehouse_id", $warehouse_id);
			}

			$query = $this->db->get();
			$result = $query->row();
			
			return array(
				'total' => $result->total
			);
		} catch (Exception $e) {
			log_message('error', 'Sales tax summary error: ' . $e->getMessage());
			return array('total' => 0);
		}
	}

	/**
	 * Calculate Cost of Goods Sold (COGS) from actual sales items
	 * This is the correct way - only count cost of items that were actually sold
	 */
	private function _get_cogs_from_sales($sales_ids, $warehouse_id = '') {
		if ($sales_ids == 'null') {
			return array('total' => 0);
		}

		try {
			// Reset query builder to avoid alias conflicts
			$this->db->reset_query();
			
			$total_cogs = 0;
			
			// Get all sales items for the period
			$this->db->select("si.item_id, si.sales_qty, si.unit_total_cost, si.total_cost, si.item_currency_id, si.item_exchange_rate, si.base_currency_price, si.unit_type, si.sales_qty_main, si.sales_qty_alternate, si.purchase_price as si_purchase_price, i.item_name, i.purchase_price, i.service_bit, i.conversion_factor, i.unit_id, i.alternate_unit_id");
			$this->db->from("db_salesitems si");
			$this->db->join("db_items i", "i.id = si.item_id", "left");
			$this->db->join("db_sales s", "s.id = si.sales_id", "left");
			$this->db->where("si.sales_id IN ($sales_ids)");
			$this->db->where("s.sales_status", "Final");
			
			if (!empty($warehouse_id)) {
				$this->db->where("s.warehouse_id", $warehouse_id);
			}
			
			$query = $this->db->get();
			
			if($query->num_rows() > 0){
				foreach($query->result() as $item){
					// Only calculate cost for non-service items
					if($item->service_bit == 0){
						// Get conversion factor
						$conversion_factor = !empty($item->conversion_factor) ? floatval($item->conversion_factor) : 0;
						
						// Determine sales_qty in main units - CRITICAL for multi-unit items
						// Always recalculate from unit_type if available (most reliable)
						$sales_qty_main = 0;
						
						// Method 1: Calculate from unit_type (most reliable - explicit unit used)
						if(!empty($item->unit_type)){
							if($item->unit_type == 'alternate'){
								// Sale was in alternate units - convert to main units
								if($conversion_factor > 0 && $conversion_factor != 1){
									$sales_qty_main = floatval($item->sales_qty) / $conversion_factor;
								} else {
									// No conversion factor, assume 1:1
									$sales_qty_main = floatval($item->sales_qty);
								}
							} else if($item->unit_type == 'main'){
								// Sale was in main units - use as is
								$sales_qty_main = floatval($item->sales_qty);
							}
						}
						// Method 2: Use stored sales_qty_main if unit_type not available
						else if(isset($item->sales_qty_main) && $item->sales_qty_main !== null && $item->sales_qty_main !== ''){
							$sales_qty_main_val = floatval($item->sales_qty_main);
							if($sales_qty_main_val > 0){
								$sales_qty_main = $sales_qty_main_val;
							}
						}
						// Method 3: Use sales_qty_alternate to detect unit type
						else if(!empty($item->sales_qty_alternate) && floatval($item->sales_qty_alternate) > 0){
							// If sales_qty equals sales_qty_alternate, it's in alternate units
							if(abs(floatval($item->sales_qty) - floatval($item->sales_qty_alternate)) < 0.01){
								if($conversion_factor > 0 && $conversion_factor != 1){
									$sales_qty_main = floatval($item->sales_qty) / $conversion_factor;
								} else {
									$sales_qty_main = floatval($item->sales_qty);
								}
							} else {
								// sales_qty is in main units
								$sales_qty_main = floatval($item->sales_qty);
							}
						}
						// Method 4: Fallback - assume main unit if no other info
						else {
							$sales_qty_main = floatval($item->sales_qty);
						}
						
						// Safety check - ensure we have a valid quantity
						if($sales_qty_main <= 0){
							$sales_qty_main = floatval($item->sales_qty);
						}
						
						// Now calculate cost - purchase prices are ALWAYS per main unit
						// Use actual cost calculation with proper unit handling
						$purchase_price_per_main = 0;
						
						// Priority 1: Use base_currency_price from salesitems (if stored correctly, per main unit)
						if(!empty($item->base_currency_price) && floatval($item->base_currency_price) > 0 && floatval($item->base_currency_price) < 100000){
							$purchase_price_per_main = floatval($item->base_currency_price);
						}
						// Priority 2: Use purchase_price from salesitems (stored from items table, per main unit)
						else if(!empty($item->si_purchase_price) && floatval($item->si_purchase_price) > 0 && floatval($item->si_purchase_price) < 100000){
							$purchase_price_per_main = floatval($item->si_purchase_price);
						}
						// Priority 3: Use purchase_price from items table (per main unit)
						else if(!empty($item->purchase_price) && floatval($item->purchase_price) > 0){
							$purchase_price_per_main = floatval($item->purchase_price);
						}
						
						// Calculate total cost: purchase_price_per_main (per main unit) Ã— sales_qty_main (in main units)
						if($purchase_price_per_main > 0 && $sales_qty_main > 0){
							$item_cost = $purchase_price_per_main * $sales_qty_main;
							
							// Final validation - cost should be reasonable
							if($item_cost > 0 && $item_cost <= 100000){
								$total_cogs += $item_cost;
							}
						}
					}
				}
			}
			
			return array('total' => $total_cogs);
		} catch (Exception $e) {
			log_message('error', 'COGS calculation error: ' . $e->getMessage());
			return array('total' => 0);
		}
	}

	/**
	 * Calculate COGS reduction from sales returns
	 */
	private function _get_cogs_from_sales_returns($sales_return_ids, $warehouse_id = '') {
		if ($sales_return_ids == 'null') {
			return array('total' => 0);
		}

		try {
			// Reset query builder to avoid alias conflicts
			$this->db->reset_query();
			
			$total_cogs_return = 0;
			
			// Get all sales return items
			$this->db->select("sri.item_id, sri.return_qty, sri.unit_total_cost, sri.total_cost, sri.item_currency_id, sri.item_exchange_rate, sri.base_currency_price, sri.unit_type, sri.return_qty_main, sri.return_qty_alternate, sri.purchase_price as sri_purchase_price, i.item_name, i.purchase_price, i.service_bit, i.conversion_factor, i.unit_id, i.alternate_unit_id");
			$this->db->from("db_salesreturnitems sri");
			$this->db->join("db_items i", "i.id = sri.item_id", "left");
			$this->db->join("db_salesreturn sr", "sr.id = sri.return_id", "left");
			$this->db->where("sri.return_id IN ($sales_return_ids)");
			$this->db->where("sr.return_status", "Final");
			
			if (!empty($warehouse_id)) {
				$this->db->where("sr.warehouse_id", $warehouse_id);
			}
			
			$query = $this->db->get();
			
			if($query->num_rows() > 0){
				foreach($query->result() as $item){
					// Only calculate cost for non-service items
					if($item->service_bit == 0){
						// Get conversion factor
						$conversion_factor = !empty($item->conversion_factor) ? floatval($item->conversion_factor) : 0;
						
						// Determine return_qty in main units
						$return_qty_main = 0;
						
						// Priority 1: Use stored return_qty_main if available
						if(isset($item->return_qty_main) && $item->return_qty_main !== null && $item->return_qty_main !== '' && floatval($item->return_qty_main) > 0){
							$return_qty_main = floatval($item->return_qty_main);
						}
						// Priority 2: Calculate based on unit_type field
						else if(!empty($item->unit_type)){
							if($item->unit_type == 'alternate'){
								if($conversion_factor > 0 && $conversion_factor != 1){
									$return_qty_main = floatval($item->return_qty) / $conversion_factor;
								} else {
									$return_qty_main = floatval($item->return_qty);
								}
							} else if($item->unit_type == 'main'){
								$return_qty_main = floatval($item->return_qty);
							}
						}
						// Priority 3: Fallback
						else if(!empty($item->return_qty_alternate) && floatval($item->return_qty_alternate) > 0 && abs(floatval($item->return_qty) - floatval($item->return_qty_alternate)) < 0.01){
							if($conversion_factor > 0 && $conversion_factor != 1){
								$return_qty_main = floatval($item->return_qty) / $conversion_factor;
							} else {
								$return_qty_main = floatval($item->return_qty);
							}
						} else {
							$return_qty_main = floatval($item->return_qty);
						}
						
						// Final safety check
						if($return_qty_main <= 0){
							$return_qty_main = floatval($item->return_qty);
						}
						
						// Now calculate cost - purchase prices are ALWAYS per main unit
						// Use actual cost calculation with proper unit handling
						$purchase_price_per_main = 0;
						
						// Priority 1: Use base_currency_price from sales return items (if stored correctly, per main unit)
						if(!empty($item->base_currency_price) && floatval($item->base_currency_price) > 0 && floatval($item->base_currency_price) < 100000){
							$purchase_price_per_main = floatval($item->base_currency_price);
						}
						// Priority 2: Use purchase_price from sales return items (stored from items table, per main unit)
						else if(!empty($item->sri_purchase_price) && floatval($item->sri_purchase_price) > 0 && floatval($item->sri_purchase_price) < 100000){
							$purchase_price_per_main = floatval($item->sri_purchase_price);
						}
						// Priority 3: Use purchase_price from items table (per main unit)
						else if(!empty($item->purchase_price) && floatval($item->purchase_price) > 0){
							$purchase_price_per_main = floatval($item->purchase_price);
						}
						
						// Calculate total cost reduction: purchase_price_per_main (per main unit) Ã— return_qty_main (in main units)
						if($purchase_price_per_main > 0 && $return_qty_main > 0){
							$item_cost = $purchase_price_per_main * $return_qty_main;
							
							// Final validation - cost should be reasonable
							if($item_cost > 0 && $item_cost <= 100000){
								$total_cogs_return += $item_cost;
							}
						}
					}
				}
			}
			
			return array('total' => $total_cogs_return);
		} catch (Exception $e) {
			log_message('error', 'COGS return calculation error: ' . $e->getMessage());
			return array('total' => 0);
		}
	}

	public function get_profit_loss_report(){

			$store_id=$this->input->post('store_id');
			$from_date=$this->input->post('from_date');
			$to_date=$this->input->post('to_date');
			$from_date = system_fromatted_date($from_date);
			$to_date = system_fromatted_date($to_date);

			$sales_ids = $this->_get_db_sales_ids($store_id,$from_date,$to_date);
			$sales_return_ids = $this->_get_db_sales_return_ids($store_id,$from_date,$to_date);
			$purchase_ids = $this->_get_db_purchase_ids($store_id,$from_date,$to_date);
			$purchase_return_ids = $this->_get_db_purchase_return_ids($store_id,$from_date,$to_date);
			$expense_ids = $this->_get_db_expense_ids($store_id,$from_date,$to_date);

			
			
			$info=array();

			//Get opening Balance
			if(store_module() && is_admin()){if(!empty($store_id)){ 
						$this->db->where("a.store_id",$store_id);}
					}else{ 
						$this->db->where("a.store_id",get_current_store_id());	
				}
			$this->db->select("SUM(b.adjustment_qty * a.purchase_price) AS  opening_stock_price");
			$this->db->from("db_items AS a , db_stockadjustmentitems AS b");
			$this->db->where("a.id=b.item_id");
			$query = $this->db->get()->row();
            $opening_stock_price=$query->opening_stock_price;
            $info['opening_stock_price']=(store_number_format($opening_stock_price));
            


            //total purchase amt
			$this->db->select("COALESCE(SUM(a.tax_amt),0) AS tax_amt");
			$this->db->select("COALESCE(SUM(a.discount_amt),0) AS discount_amt");
			$this->db->from("db_purchaseitems as a");
			$this->db->where("a.purchase_id in (".$purchase_ids.")");
			$query = $this->db->get()->row();
            $purchase_discount_amt=$query->discount_amt;
            $purchase_tax_amt=$query->tax_amt;
            $info['purchase_tax_amt']=(store_number_format($purchase_tax_amt));
            

            //total purchase amt
			$this->db->select("COALESCE(SUM(grand_total),0) AS pur_total");
			$this->db->select("COALESCE(SUM(other_charges_amt),0) AS other_charges_amt");
			$this->db->select("COALESCE(SUM(tot_discount_to_all_amt),0) AS tot_discount_to_all_amt");
			$this->db->select("COALESCE(SUM(paid_amount),0) AS paid_amount");
			$this->db->from("db_purchase");
			$this->db->where("id in (".$purchase_ids.")");

			$query = $this->db->get()->row();

            $pur_total=$query->pur_total;
            $pur_total-=$purchase_tax_amt;
            $info['pur_total']=(store_number_format($pur_total));

            //Other Charge of Purchase entry
            $pur_other_charges_amt=$query->other_charges_amt;
            $info['pur_other_charges_amt']=(store_number_format($pur_other_charges_amt));

            //Disount purchase entry
			$purchase_discount_amt+=$query->tot_discount_to_all_amt;
            $info['purchase_discount_amt']=(store_number_format($purchase_discount_amt));

            //purchase Paid Amount
            $purchase_paid_amount=$query->paid_amount;
            $info['purchase_paid_amount']=(store_number_format($purchase_paid_amount));
            
            //total purchase due
            $purchase_due_total=$pur_total - $query->paid_amount;
            $info['purchase_due_total']=(store_number_format($purchase_due_total));





            /***********Purchase Return**********/
            //return tax amt
			$this->db->select("COALESCE(SUM(tax_amt),0) AS tax_amt");
			$this->db->select("COALESCE(SUM(discount_amt),0) AS discount_amt");
			$this->db->where("return_id in (".$purchase_return_ids.")");
			$this->db->from("db_purchaseitemsreturn");
			$query = $this->db->get()->row();
			
			//Disount purchase return entry
            $purchase_return_discount_amt=$query->discount_amt;

            $purchase_return_tax_amt=$query->tax_amt;
            $info['purchase_return_tax_amt']=(store_number_format($purchase_return_tax_amt));
            
            //total purchase return amt
			$this->db->select("COALESCE(SUM(grand_total),0) AS pur_total");
			$this->db->select("COALESCE(SUM(other_charges_amt),0) AS other_charges_amt");
			$this->db->select("COALESCE(SUM(tot_discount_to_all_amt),0) AS tot_discount_to_all_amt");
			$this->db->select("COALESCE(SUM(paid_amount),0) AS paid_amount");
			$this->db->where("id in (".$purchase_return_ids.")");
			$this->db->from("db_purchasereturn");
			$query = $this->db->get()->row();
			
            $pur_return_total=$query->pur_total;
            $pur_return_total-=$purchase_return_tax_amt;
            $info['pur_return_total']=(store_number_format($pur_return_total));

            //Due
            $purchase_return_due_total=$pur_return_total - $query->paid_amount;
            $info['purchase_return_due_total']=(store_number_format($purchase_return_due_total));

            //Other Charge of Purchase return entry
            $pur_return_other_charges_amt=$query->other_charges_amt;
            $info['pur_return_other_charges_amt']=(store_number_format($pur_return_other_charges_amt));
            
            //Disount purchase return entry
            $purchase_return_discount_amt+=$query->tot_discount_to_all_amt;
            $info['purchase_return_discount_amt']=(store_number_format($purchase_return_discount_amt));

            //Purchase Return Paid Amount
            $purchase_return_paid_amount=$query->paid_amount;
            $info['purchase_return_paid_amount']=(store_number_format($purchase_return_paid_amount));
            
            
            /***********Sales Entry**********/
			$this->db->select("COALESCE(SUM(tax_amt),0) AS tax_amt");
			$this->db->select("COALESCE(SUM(discount_amt),0) AS discount_amt");
			$this->db->where("sales_id in (".$sales_ids.")");
			$this->db->from("db_salesitems");
			$query = $this->db->get()->row();
			
            
			//total sales amt
            $sales_tax_amt=$query->tax_amt;
            $info['sales_tax_amt']=(store_number_format($sales_tax_amt));
            
            
            
            //Disount sales entry
            $sales_discount_amt=$query->discount_amt;
            

            //Coupon Disount sales entry
			$this->db->select("COALESCE(SUM(b.coupon_amt),0) AS coupon_amt");
			$this->db->select("COALESCE(SUM(other_charges_amt),0) AS other_charges_amt");
			$this->db->select("COALESCE(SUM(tot_discount_to_all_amt),0) AS tot_discount_to_all_amt");
			$this->db->select("COALESCE(sum(grand_total),0) AS tot_sal_grand_total");
			$this->db->select("COALESCE(SUM(paid_amount),0) AS paid_amount");
			$this->db->from("db_sales as b");
			$this->db->where("id in (".$sales_ids.")");
			$this->db->where("b.sales_status='Final'");
			$query = $this->db->get()->row();

            $coupon_discount_amt=$query->coupon_amt;
            $info['coupon_discount_amt']=(store_number_format($coupon_discount_amt));

            //Other Charge of Sales entry
            $sal_other_charges_amt=$query->other_charges_amt;
            $info['sal_other_charges_amt']=(store_number_format($sal_other_charges_amt));

            //Discount Amount
            $sales_discount_amt+=$query->tot_discount_to_all_amt;
            $info['sales_discount_amt']=(store_number_format($sales_discount_amt));
            
            
            //Total SAles amount
            $sal_total=$query->tot_sal_grand_total;
            $tot_sal_total=($sal_total-$sales_tax_amt+$coupon_discount_amt);
            $info['sal_total']=(store_number_format($tot_sal_total));

            //Due
            $sales_due_total=$sal_total - $query->paid_amount;
            $info['sales_due_total']=(store_number_format($sales_due_total));
        
            //sales Paid Amount
            $sales_paid_amount=$query->paid_amount;
            $info['sales_paid_amount']=(store_number_format($sales_paid_amount));
            


            /***********Sales Return**********/
			$this->db->select("COALESCE(SUM(tax_amt),0) AS tax_amt");
			$this->db->select("COALESCE(SUM(discount_amt),0) AS discount_amt");
			$this->db->from("db_salesitemsreturn");
			$this->db->where("return_id in (".$sales_return_ids.")");
			$query = $this->db->get()->row();

			//Disount sales return entry
            $sales_return_discount_amt=$query->discount_amt;

			//total sales return amt
            $sales_return_tax_amt=$query->tax_amt;
            $info['sales_return_tax_amt']=(store_number_format($sales_return_tax_amt));
            
            
			$this->db->select("COALESCE(SUM(grand_total),0) AS sal_total");
			$this->db->select("COALESCE(SUM(other_charges_amt),0) AS other_charges_amt");
			$this->db->select("COALESCE(SUM(coupon_amt),0) AS coupon_amt");
			$this->db->select("COALESCE(SUM(tot_discount_to_all_amt),0) AS tot_discount_to_all_amt");
			$this->db->select("COALESCE(SUM(paid_amount),0) AS paid_amount");
			$this->db->where("id in (".$sales_return_ids.")");
			$this->db->from("db_salesreturn");
			$query = $this->db->get()->row();
			

			//total sales return amt
            $sal_return_total=$query->sal_total;
            $sal_return_total-=$sales_return_tax_amt;
            $info['sal_return_total']=(store_number_format($sal_return_total));

            //Due
            $sales_return_due_total=$sal_return_total - $query->paid_amount;
            $info['sales_return_due_total']=(store_number_format($sales_return_due_total));

            //Other Charge of Sales return entry
            $sal_return_other_charges_amt=$query->other_charges_amt;
            $info['sal_return_other_charges_amt']=(store_number_format($sal_return_other_charges_amt));
            
            //Coupon Disount sales entry
            $coupon_discount_amt=$query->coupon_amt;
            $info['return_coupon_discount_amt']=(store_number_format($coupon_discount_amt));

            //Discount 
            $sales_return_discount_amt+=$query->tot_discount_to_all_amt;
            $info['sales_return_discount_amt']=(store_number_format($sales_return_discount_amt));
            
            //sales Return Paid Amount;
            $sales_return_paid_amount=$query->paid_amount;
            $info['sales_return_paid_amount']=(store_number_format($sales_return_paid_amount));
            
            
            /***********Sales Return**********/
			// 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->where("id in (".$expense_ids.")");
			$this->db->from("db_expense");
			$query = $this->db->get()->row();

			//expense total
            $exp_total=$query->exp_total;
            $info['exp_total']=(store_number_format($exp_total));;
                        
           	//GROSS PROFIT & NET PROFIT
            $sales_details = $this->get_sales_item_sum($sales_ids);
            $sal_item_pur_price = $sales_details['purchase_price'];
            $sal_cost = $sales_details['sales_price'];
            $sal_tax_amt = $sales_details['tax_amt'];
            $net_sales = $sal_cost-$sal_item_pur_price;//ACTUAL SALES VALUE


            $return_details = $this->get_sales_return_item_sum($sales_return_ids);
            $ret_item_pur_price = $return_details['purchase_price'];
            $ret_cost = $return_details['return_price'];
            $ret_tax_amt = $return_details['tax_amt'];
            $net_return = $ret_cost - $ret_item_pur_price;//ACTUAL RETURN VALUE
            

            //TO FIND GROSS PROFIT = (SALES PRICE - PURCHASE PRICE OF ITEM) - (SALES RETURN - PURCHASE PRICE OF ITEM)
            /**
             * Gorss prfit = Sales - Purchase price
             * To find gross prfit we are also want deduct return sales records
            */
            $gross_profit = $net_sales - $net_return;

            $info['net_sales']=(store_number_format($sal_cost));
            $info['sales_return_total']=(store_number_format($ret_cost));
            $info['gross_profit']=(store_number_format($gross_profit));

            
            //Tax
            //Sales & Retuern tax, because we are calculating sum
            $tot_tax = $sal_tax_amt - $ret_tax_amt;
            //Now you got valid tax

            //To find net profit now need to deduct valid tax from gross profit
            //also deduct expenses
            $net_profit = ($gross_profit - $tot_tax) - $exp_total;
            $info['tot_net_profit']=(store_number_format($net_profit));

            //Find purchase price of the sales item
            

            return $info;
	}
	
	//Professional Profit & Loss Report - Returns raw data for JSON response
	public function get_professional_pl_report(){
		try {
			$store_id=$this->input->post('store_id');
			$from_date=$this->input->post('from_date');
			$to_date=$this->input->post('to_date');
			$from_date = system_fromatted_date($from_date);
			$to_date = system_fromatted_date($to_date);

		$sales_ids = $this->_get_db_sales_ids($store_id,$from_date,$to_date);
		$sales_return_ids = $this->_get_db_sales_return_ids($store_id,$from_date,$to_date);
		$purchase_ids = $this->_get_db_purchase_ids($store_id,$from_date,$to_date);
		$purchase_return_ids = $this->_get_db_purchase_return_ids($store_id,$from_date,$to_date);
		$expense_ids = $this->_get_db_expense_ids($store_id,$from_date,$to_date);

		$info=array();

		//Get opening Balance
		if(store_module() && is_admin()){if(!empty($store_id)){ 
					$this->db->where("a.store_id",$store_id);}
				}else{ 
					$this->db->where("a.store_id",get_current_store_id());	
			}
		$this->db->select("SUM(b.adjustment_qty * a.purchase_price) AS  opening_stock_price");
		$this->db->from("db_items AS a , db_stockadjustmentitems AS b");
		$this->db->where("a.id=b.item_id");
		$query = $this->db->get()->row();
        $opening_stock_price=$query->opening_stock_price;
        $info['opening_stock_price']=($opening_stock_price);
        
        //Closing stock
        $info['closing_stock_price']=0; // Will be calculated if needed

        //total purchase amt
		$this->db->select("COALESCE(SUM(CASE WHEN p.transaction_currency_id IS NOT NULL AND p.transaction_currency_id != 1 AND p.exchange_rate IS NOT NULL THEN a.tax_amt / p.exchange_rate ELSE a.tax_amt END),0) AS tax_amt");
		$this->db->select("COALESCE(SUM(CASE WHEN p.transaction_currency_id IS NOT NULL AND p.transaction_currency_id != 1 AND p.exchange_rate IS NOT NULL THEN a.discount_amt / p.exchange_rate ELSE a.discount_amt END),0) AS discount_amt");
		$this->db->from("db_purchaseitems as a");
		$this->db->join("db_purchase p", "p.id = a.purchase_id", "left");
		$this->db->where("a.purchase_id in (".$purchase_ids.")");
		$query = $this->db->get()->row();
        $purchase_discount_amt=$query->discount_amt;
        $purchase_tax_amt=$query->tax_amt;
        $info['purchase_tax_amt']=($purchase_tax_amt);
        
        //total purchase amt - use base currency amounts if available
		$this->db->select("COALESCE(SUM(CASE WHEN base_currency_total IS NOT NULL AND base_currency_total > 0 THEN base_currency_total ELSE grand_total END),0) AS pur_total");
		$this->db->select("COALESCE(SUM(CASE WHEN transaction_currency_id IS NOT NULL AND transaction_currency_id != 1 AND exchange_rate IS NOT NULL THEN other_charges_amt / exchange_rate ELSE other_charges_amt END),0) AS other_charges_amt");
		$this->db->select("COALESCE(SUM(CASE WHEN transaction_currency_id IS NOT NULL AND transaction_currency_id != 1 AND exchange_rate IS NOT NULL THEN tot_discount_to_all_amt / exchange_rate ELSE tot_discount_to_all_amt END),0) AS tot_discount_to_all_amt");
		$this->db->select("COALESCE(SUM(paid_amount),0) AS paid_amount");
		$this->db->from("db_purchase");
		$this->db->where("id in (".$purchase_ids.")");

		$query = $this->db->get()->row();

        $pur_total=$query->pur_total;
        $pur_total-=$purchase_tax_amt;
        $info['pur_total']=($pur_total);

        //Other Charge of Purchase entry
        $pur_other_charges_amt=$query->other_charges_amt;
        $info['pur_other_charges_amt']=($pur_other_charges_amt);

        //Disount purchase entry
		$purchase_discount_amt+=$query->tot_discount_to_all_amt;
        $info['purchase_discount_amt']=($purchase_discount_amt);

        //purchase Paid Amount - calculate from payment records in base currency
        if($purchase_ids != 'null') {
            $this->db->select("COALESCE(SUM(CASE WHEN base_currency_amount IS NOT NULL AND base_currency_amount > 0 THEN base_currency_amount ELSE payment END),0) AS paid_amount");
            $this->db->from("db_purchasepayments");
            $this->db->where("purchase_id in (".$purchase_ids.")");
            $payment_query = $this->db->get()->row();
            $purchase_paid_amount = $payment_query->paid_amount;
        } else {
            $purchase_paid_amount = 0;
        }
        $info['purchase_paid_amount']=($purchase_paid_amount);
        
        //total purchase due
        $purchase_due_total=$pur_total - $purchase_paid_amount;
        $info['purchase_due_total']=($purchase_due_total);

        /***********Purchase Return**********/
        //return tax amt
		$this->db->select("COALESCE(SUM(tax_amt),0) AS tax_amt");
		$this->db->select("COALESCE(SUM(discount_amt),0) AS discount_amt");
		$this->db->where("return_id in (".$purchase_return_ids.")");
		$this->db->from("db_purchaseitemsreturn");
		$query = $this->db->get()->row();
		
		//Disount purchase return entry
        $purchase_return_discount_amt=$query->discount_amt;

        $purchase_return_tax_amt=$query->tax_amt;
        $info['purchase_return_tax_amt']=($purchase_return_tax_amt);
        
        //total purchase return amt - use base currency amounts if available
		$this->db->select("COALESCE(SUM(CASE WHEN base_currency_total IS NOT NULL AND base_currency_total > 0 THEN base_currency_total ELSE grand_total END),0) AS pur_total");
		$this->db->select("COALESCE(SUM(other_charges_amt),0) AS other_charges_amt");
		$this->db->select("COALESCE(SUM(tot_discount_to_all_amt),0) AS tot_discount_to_all_amt");
		$this->db->select("COALESCE(SUM(paid_amount),0) AS paid_amount");
		$this->db->where("id in (".$purchase_return_ids.")");
		$this->db->from("db_purchasereturn");
		$query = $this->db->get()->row();
		
        $pur_return_total=$query->pur_total;
        $pur_return_total-=$purchase_return_tax_amt;
        $info['pur_return_total']=($pur_return_total);

        //Purchase Return Paid Amount - calculate from payment records in base currency
        if($purchase_return_ids != 'null') {
            $this->db->select("COALESCE(SUM(CASE WHEN base_currency_amount IS NOT NULL AND base_currency_amount > 0 THEN base_currency_amount ELSE payment END),0) AS paid_amount");
            $this->db->from("db_purchasepaymentsreturn");
            $this->db->where("return_id in (".$purchase_return_ids.")");
            $payment_query = $this->db->get()->row();
            $purchase_return_paid_amount = $payment_query->paid_amount;
        } else {
            $purchase_return_paid_amount = 0;
        }
        $info['purchase_return_paid_amount']=($purchase_return_paid_amount);

        //Due
        $purchase_return_due_total=$pur_return_total - $purchase_return_paid_amount;
        $info['purchase_return_due_total']=($purchase_return_due_total);

        //Other Charge of Purchase return entry
        $pur_return_other_charges_amt=$query->other_charges_amt;
        $info['pur_return_other_charges_amt']=($pur_return_other_charges_amt);
        
        //Disount purchase return entry
        $purchase_return_discount_amt+=$query->tot_discount_to_all_amt;
        $info['purchase_return_discount_amt']=($purchase_return_discount_amt);
        
        /***********Sales Entry**********/
		$this->db->select("COALESCE(SUM(CASE WHEN s.transaction_currency_id IS NOT NULL AND s.transaction_currency_id != 1 AND s.exchange_rate IS NOT NULL THEN si.tax_amt / s.exchange_rate ELSE si.tax_amt END),0) AS tax_amt");
		$this->db->select("COALESCE(SUM(CASE WHEN s.transaction_currency_id IS NOT NULL AND s.transaction_currency_id != 1 AND s.exchange_rate IS NOT NULL THEN si.discount_amt / s.exchange_rate ELSE si.discount_amt END),0) AS discount_amt");
		$this->db->from("db_salesitems si");
		$this->db->join("db_sales s", "s.id = si.sales_id", "left");
		$this->db->where("si.sales_id in (".$sales_ids.")");
		$query = $this->db->get()->row();
		
        //total sales amt
        $sales_tax_amt=$query->tax_amt;
        $info['sales_tax_amt']=($sales_tax_amt);
        
        //Disount sales entry
        $sales_discount_amt=$query->discount_amt;
        
        //Coupon Disount sales entry
		$this->db->select("COALESCE(SUM(CASE WHEN b.transaction_currency_id IS NOT NULL AND b.transaction_currency_id != 1 AND b.exchange_rate IS NOT NULL THEN b.coupon_amt / b.exchange_rate ELSE b.coupon_amt END),0) AS coupon_amt");
		$this->db->select("COALESCE(SUM(CASE WHEN b.transaction_currency_id IS NOT NULL AND b.transaction_currency_id != 1 AND b.exchange_rate IS NOT NULL THEN other_charges_amt / b.exchange_rate ELSE other_charges_amt END),0) AS other_charges_amt");
		$this->db->select("COALESCE(SUM(CASE WHEN b.transaction_currency_id IS NOT NULL AND b.transaction_currency_id != 1 AND b.exchange_rate IS NOT NULL THEN tot_discount_to_all_amt / b.exchange_rate ELSE tot_discount_to_all_amt END),0) AS tot_discount_to_all_amt");
		$this->db->select("COALESCE(SUM(CASE WHEN base_currency_total IS NOT NULL AND base_currency_total > 0 THEN base_currency_total ELSE grand_total END),0) AS tot_sal_grand_total");
		$this->db->select("COALESCE(SUM(paid_amount),0) AS paid_amount");
		$this->db->from("db_sales as b");
		$this->db->where("id in (".$sales_ids.")");
		$this->db->where("b.sales_status='Final'");
		$query = $this->db->get()->row();

        $coupon_discount_amt=$query->coupon_amt;
        $info['coupon_discount_amt']=($coupon_discount_amt);

        //Other Charge of Sales entry
        $sal_other_charges_amt=$query->other_charges_amt;
        $info['sal_other_charges_amt']=($sal_other_charges_amt);

        //Discount Amount
        $sales_discount_amt+=$query->tot_discount_to_all_amt;
        $info['sales_discount_amt']=($sales_discount_amt);
        
        //Total SAles amount
        $sal_total=$query->tot_sal_grand_total;
        $tot_sal_total=($sal_total-$sales_tax_amt+$coupon_discount_amt);
        $info['sal_total']=($tot_sal_total);

        //sales Paid Amount - calculate from payment records in base currency
        if($sales_ids != 'null') {
            $this->db->select("COALESCE(SUM(CASE WHEN base_currency_amount IS NOT NULL AND base_currency_amount > 0 THEN base_currency_amount ELSE payment END),0) AS paid_amount");
            $this->db->from("db_salespayments");
            $this->db->where("sales_id in (".$sales_ids.")");
            $payment_query = $this->db->get()->row();
            $sales_paid_amount = $payment_query->paid_amount;
        } else {
            $sales_paid_amount = 0;
        }
        $info['sales_paid_amount']=($sales_paid_amount);
    
        //Due
        $sales_due_total=$sal_total - $sales_paid_amount;
        $info['sales_due_total']=($sales_due_total);
        
        /***********Sales Return**********/
		$this->db->select("COALESCE(SUM(tax_amt),0) AS tax_amt");
		$this->db->select("COALESCE(SUM(discount_amt),0) AS discount_amt");
		$this->db->from("db_salesitemsreturn");
		$this->db->where("return_id in (".$sales_return_ids.")");
		$query = $this->db->get()->row();

		//Disount sales return entry
        $sales_return_discount_amt=$query->discount_amt;

		//total sales return amt
        $sales_return_tax_amt=$query->tax_amt;
        $info['sales_return_tax_amt']=($sales_return_tax_amt);
        
		$this->db->select("COALESCE(SUM(CASE WHEN base_currency_total IS NOT NULL AND base_currency_total > 0 THEN base_currency_total ELSE grand_total END),0) AS sal_total");
		$this->db->select("COALESCE(SUM(other_charges_amt),0) AS other_charges_amt");
		$this->db->select("COALESCE(SUM(coupon_amt),0) AS coupon_amt");
		$this->db->select("COALESCE(SUM(tot_discount_to_all_amt),0) AS tot_discount_to_all_amt");
		$this->db->select("COALESCE(SUM(paid_amount),0) AS paid_amount");
		$this->db->where("id in (".$sales_return_ids.")");
		$this->db->from("db_salesreturn");
		$query = $this->db->get()->row();
		
        $sal_return_total=$query->sal_total;
        $sal_return_total-=$sales_return_tax_amt;
        $info['sal_return_total']=($sal_return_total);

        //Sales Return Paid Amount - calculate from payment records in base currency
        if($sales_return_ids != 'null') {
            $this->db->select("COALESCE(SUM(CASE WHEN base_currency_amount IS NOT NULL AND base_currency_amount > 0 THEN base_currency_amount ELSE payment END),0) AS paid_amount");
            $this->db->from("db_salespaymentsreturn");
            $this->db->where("return_id in (".$sales_return_ids.")");
            $payment_query = $this->db->get()->row();
            $sales_return_paid_amount = $payment_query->paid_amount;
        } else {
            $sales_return_paid_amount = 0;
        }
        $info['sales_return_paid_amount']=($sales_return_paid_amount);

        //Due
        $sales_return_due_total=$sal_return_total - $sales_return_paid_amount;
        $info['sales_return_due_total']=($sales_return_due_total);

        //Other Charge of Sales return entry
        $sal_return_other_charges_amt=$query->other_charges_amt;
        $info['sal_return_other_charges_amt']=($sal_return_other_charges_amt);
        
        //Disount sales return entry
        $sales_return_discount_amt+=$query->tot_discount_to_all_amt;
        $info['sales_return_discount_amt']=($sales_return_discount_amt);
        
        /***********Expense Entry**********/
        if($expense_ids != 'null') {
            $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 expense_amt");
            $this->db->from("db_expense");
            $this->db->where("id in (".$expense_ids.")");
            $query = $this->db->get()->row();
            $expense_total=$query->expense_amt;
        } else {
            $expense_total = 0;
        }
        $info['expense_total']=($expense_total);
        
        //Calculate Gross Profit
        $gross_profit = $tot_sal_total - $sal_return_total - ($pur_total - $pur_return_total);
        $info['gross_profit'] = $gross_profit;
        
        //Calculate Net Profit
        $net_profit = $gross_profit - $expense_total;
        $info['net_profit'] = $net_profit;
        
        //Add period information
        $info['from_date'] = $from_date;
        $info['to_date'] = $to_date;
        $info['store_id'] = $store_id;
        
        // CONVERT ALL TRANSACTIONS TO BASE CURRENCY
        $info = $this->_convert_to_base_currency_professional($info, $store_id);
        
        return $info;
		} catch (Exception $e) {
			log_message('error', 'P&L Report Error: ' . $e->getMessage());
			return array('error' => true, 'message' => 'Error generating report: ' . $e->getMessage());
		}
	}


	public function get_sales_item_sum($sales_ids){
		$this->db->select("a.sales_qty,a.purchase_price,a.total_cost,a.tax_amt,a.tax_type");
		$this->db->select("b.tax");
		$this->db->from('db_salesitems a');
		$this->db->where("a.sales_id in (".$sales_ids.")");

		$this->db->join('db_tax b','b.id=a.tax_id','left');
		

		$Q1 = $this->db->get();
		$sum_pur_price = 0;
		$sum_sal_price = 0;
		$sum_tax_amt = 0;
		if($Q1->num_rows()>0){
			foreach ($Q1->result() as $res1){

				$sales_tax_amt = $res1->tax_amt;
				$sales_qty = $res1->sales_qty;

				$purchase_price = ($res1->tax_type == 'Exclusive') ? $res1->purchase_price : original_cost($res1->purchase_price,$res1->tax,'Inclusive');

				

				$sales_price = $res1->total_cost;

				$tot_pur_price = $sales_qty * $purchase_price;

				$sum_pur_price+=$tot_pur_price;
				$sum_sal_price+=$sales_price;
				$sum_tax_amt+=$sales_tax_amt;
			}
		}

		return array(
					'purchase_price' => $sum_pur_price,
					'sales_price' => $sum_sal_price,
					'tax_amt' => $sum_tax_amt,
				);
	}
	public function get_sales_return_item_sum($sales_return_ids){
		$this->db->select("a.return_qty,a.purchase_price,a.total_cost,a.tax_amt,a.tax_type");
		$this->db->select("b.tax");
		
		$this->db->from('db_salesitemsreturn a');
		$this->db->where("a.return_id in (".$sales_return_ids.")");

		$this->db->join('db_tax b','b.id=a.tax_id','left');

		$Q1 = $this->db->get();
		$sum_pur_price = 0;
		$sum_return_price = 0;
		$sum_tax_amt = 0;
		if($Q1->num_rows()>0){
			foreach ($Q1->result() as $res1){
				$return_qty = $res1->return_qty;

				$purchase_price = ($res1->tax_type == 'Exclusive') ? $res1->purchase_price : original_cost($res1->purchase_price,$res1->tax,'Inclusive');


				$return_price = $res1->total_cost;
				$tax_amt = $res1->tax_amt;

				$tot_pur_price = $return_qty * $purchase_price;

				$sum_pur_price+=$tot_pur_price;
				$sum_return_price+=$return_price;
				$sum_tax_amt+=$tax_amt;
			}
		}

		return array(
					'purchase_price' => $sum_pur_price,
					'return_price' => $sum_return_price,
					'tax_amt' => $sum_tax_amt,
				);
	}
	
	
	public function get_profit_by_item(){
		
		extract($_POST);
	
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		
		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
			$this->db->where("c.warehouse_id",$warehouse_id);
		}
		if(store_module() && is_admin()){
			if(!empty($store_id)){ $this->db->where("c.store_id",$store_id);}
			}else{ $this->db->where("c.store_id",get_current_store_id());	
		}
		$this->db->select("a.service_bit, b.tax_amt,b.item_id,a.item_name,COALESCE(sum(b.sales_qty),0) as sales_qty,a.purchase_price,
						COALESCE(SUM(total_cost),0) as total_cost");
		$this->db->from("db_items as a, db_salesitems as b, db_sales as c");
		$this->db->where("c.id=b.sales_id and a.id=b.item_id and c.sales_status='Final'");
		$this->db->where("( c.sales_date>='".$from_date."' and  c.sales_date<='".$to_date."')");
		$this->db->group_by("item_id");
		//echo $this->db->get_compiled_select();exit();
        $q1=$this->db->get();
		
		if($q1->num_rows()>0){
			$i=0;
			$tot_purchase_price=0;
			$tot_sales_cost=0;
			$gross_profit=0;
			$tot_purchase_return_price=0;
			$tot_sales_return_price=0;
			$tot_sales_qty=0;
			$tot_purchase_return_qty=0;
			$tot_sales_return_qty=0;
			$grand_profit=0;
			$tot_net_profit=0;
			foreach ($q1->result() as $res1) {
				/*Purchase Return Quantity*/
				$purchase_return_qty=$this->db->query("
						SELECT COALESCE(sum(return_qty),0) as return_qty
						FROM db_purchaseitemsreturn
						WHERE 
						item_id =".$res1->item_id)->row()->return_qty;

				/*Sales Return Quantity*/
				$q3=$this->db->query("
						SELECT COALESCE(sum(total_cost),0) as total_cost,COALESCE(sum(return_qty),0) as return_qty
						FROM db_salesitemsreturn
						WHERE 
						item_id =".$res1->item_id);
				$sales_return_total_cost=$q3->row()->total_cost;
				$sales_return_qty=$q3->row()->return_qty;
				
				$qty = $res1->sales_qty-$sales_return_qty;
				//$purchase_price =  $res1->purchase_price * $qty;
				$purchase_price = ($res1->service_bit==0) ? $res1->purchase_price * $qty : 0;

				$total_cost = ($res1->total_cost - $sales_return_total_cost);
				//$purchase_return_price = $res1->purchase_price*$purchase_return_qty;
				$profit = $total_cost - $purchase_price;

				$tax_amt = $res1->tax_amt/$res1->sales_qty;

			    $net_profit =$profit-($tax_amt*$qty);

				echo "<tr>";
				echo "<td>".++$i."</td>";
				echo "<td>".$res1->item_name."</td>";
				echo "<td>".format_qty($qty)."</td>";
				echo "<td style='text-align:right;'>".store_number_format($total_cost)."</td>";
				echo "<td style='text-align:right;'>".(store_number_format($purchase_price))."</td>";
				/*echo "<td style=''>".$purchase_return_qty."</td>";
				echo "<td style='text-align:right;'>".(store_number_format($purchase_return_price))."</td>";*/
				/*echo "<td style=''>".$sales_return_qty."</td>";
				echo "<td style='text-align:right;'>".($sales_return_total_cost)."</td>";*/
				echo "<td style='text-align:right;'>".(store_number_format($profit))."</td>";
				//echo "<td style='text-align:right;'>".(store_number_format($net_profit))."</td>";
				echo "</tr>";
				$tot_purchase_price+=$purchase_price;
				//$tot_purchase_return_price+=$purchase_return_price;
				$tot_sales_cost+=$total_cost;
				//$tot_sales_return_cost+=$sales_return_total_cost;
				//$gross_profit+=(($profit + $purchase_return_price)-$sales_return_total_cost);
				$tot_sales_qty+=($res1->sales_qty-$sales_return_qty);
				$tot_purchase_return_qty+=$purchase_return_qty;
				$tot_sales_return_qty+=$sales_return_qty;
				$gross_profit+=$profit;
				$tot_net_profit+=$net_profit;
			}
			echo "<tr>
					  <td class='text-right text-bold' colspan='2'><b>Total :</b></td>
					  <td class='text-bold'>".format_qty($tot_sales_qty)."</td>
					  <td class='text-right text-bold'>".(store_number_format($tot_sales_cost))."</td>
					  <td class='text-right text-bold'>".(store_number_format($tot_purchase_price))."</td>
					  
					  <td class='text-right text-bold'>".(store_number_format($gross_profit))."</td>
				  </tr>";
				  /*<td class='text-bold'>".$tot_purchase_return_qty."</td>
					  <td class='text-right text-bold'>".(store_number_format($tot_purchase_return_price))."</td>
					  <td class='text-bold'>".$tot_sales_return_qty."</td>
					  <td class='text-right text-bold'>".(store_number_format($tot_sales_return_cost))."</td>
					  */
		}
		else{
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan=7>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}
	public function get_profit_by_invoice(){
		
		extract($_POST);
		/*$from_date=date("Y-m-d",strtotime($from_date));
		$to_date=date("Y-m-d",strtotime($to_date));*/

		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);
		

		
		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
			$this->db->where("a.warehouse_id",$warehouse_id);
		}
		if(store_module() && is_admin()){
			if(!empty($store_id)){ $this->db->where("a.store_id",$store_id);}
			}else{ $this->db->where("a.store_id",get_current_store_id());	
		}
		$this->db->select("a.coupon_amt,a.id,a.sales_date,a.sales_code,b.customer_name");
		$this->db->from("db_sales as a,db_customers as b");
		$this->db->where("a.sales_status='Final' and b.id=a.customer_id");

		$q1=$this->db->get();

		if($q1->num_rows()>0){
			$i=0;
			$tot_purchase_price=0;
			$tot_sales_cost=0;
			$tot_profit=0;
			$net_profit=0;
			$tot_net_profit=0;

			foreach ($q1->result() as $res1) {
				$q2=$this->db->query("SELECT b.sales_qty,COALESCE(SUM(a.purchase_price*sales_qty),0) AS purchase_price, COALESCE(SUM(total_cost),0) AS total_cost FROM db_items AS a, db_salesitems AS b, db_sales AS c WHERE c.id=b.sales_id AND a.id=b.item_id and c.sales_status='Final'
					AND b.sales_id=".$res1->id);

				$q3=$this->db->query("SELECT COALESCE(SUM(a.purchase_price*return_qty),0) AS purchase_price, COALESCE(SUM(total_cost),0) AS total_cost FROM db_items AS a, db_salesitemsreturn AS b, db_salesreturn AS c WHERE c.id=b.return_id AND a.id=b.item_id and c.return_status!='Final'
					AND b.sales_id=".$res1->id);
				$purchase_return_price=$q3->row()->purchase_price;



				//Total price item_purchase_price * qty
				$purchase_price = ($q2->row()->purchase_price-$purchase_return_price);
				//Total price item_sales_price * qty
				$sales_price = ($q2->row()->total_cost-$q3->row()->total_cost);

				$coupon_amt = $res1->coupon_amt;
				$profit = $sales_price - $purchase_price;
				
				/*$sales_tax_amt =$this->db->query("select COALESCE(SUM(tax_amt),0) AS tax_amt from db_salesitems where sales_id=".$res1->id)->row()->tax_amt;
				
				$sales_return_tax_amt =$this->db->query("select COALESCE(SUM(tax_amt),0) AS tax_amt from db_salesitemsreturn where sales_id=".$res1->id)->row()->tax_amt;

				$net_profit = $profit + ($sales_tax_amt-$sales_return_tax_amt);*/
				echo "<tr>";
				echo "<td>".++$i."</td>";
				echo "<td>".$res1->sales_code."</td>";
				echo "<td>".show_date($res1->sales_date)."</td>";
				echo "<td>".$res1->customer_name."</td>";
				echo "<td style='text-align:right;'>".store_number_format($sales_price)."</td>";
				echo "<td style='text-align:right;'>".store_number_format($purchase_price)."</td>";
				echo "<td style='text-align:right;'>".store_number_format($profit)."</td>";
				//echo "<td style='text-align:right;'>".(store_number_format($net_profit))."</td>";
				echo "</tr>";
				$tot_purchase_price+=$purchase_price;
				$tot_sales_cost+=$sales_price;
				$tot_profit+=$profit;
				$tot_net_profit+=$net_profit;
			}
			echo "<tr>
					  <td class='text-right text-bold' colspan='4'><b>Total :</b></td>
					  <td class='text-right text-bold'>".(store_number_format($tot_sales_cost))."</td>
					  <td class='text-right text-bold'>".(store_number_format($tot_purchase_price))."</td>
					  <td class='text-right text-bold'>".(store_number_format($tot_profit))."</td>
					  
				  </tr>";
		}
		else{
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan=7>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}

	public function show_seller_points_report(){
		extract($_POST);

		/*$from_date=date("Y-m-d",strtotime($from_date));
		$to_date=date("Y-m-d",strtotime($to_date));*/
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
			$this->db->where("a.warehouse_id",$warehouse_id);
		}
		
		$this->db->select("a.created_by,c.seller_points, a.id,a.sales_code,a.sales_date,b.customer_name,b.customer_code,a.grand_total,a.paid_amount,a.store_id");
		$this->db->select("c.sales_qty,d.item_name");
	    
	    
		if($view_all=="no"){
			$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");
		}
//		$this->db->group_by("c.`item_id`");
		$this->db->order_by("a.`sales_date`,a.sales_code",'desc');
		$this->db->from("db_sales as a");
		$this->db->where("a.`id`= c.`sales_id`");
		$this->db->where("a.`sales_status`= 'Final'");
		$this->db->from("db_items as d");
		$this->db->where("d.`id`= c.`item_id`");
		$this->db->from("db_customers as b");
		$this->db->where("b.`id`= a.`customer_id`");
		$this->db->from("db_salesitems as c");
		if(!empty($created_by)){
			$this->db->where("upper(a.created_by)=upper('$created_by')");
		}
		if($item_id!=''){
			$this->db->where("c.item_id=$item_id");
		}
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_seller_points=0;
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				if($store_id==get_current_store_id()){
				echo "<td><a title='View Invoice' href='".base_url("sales/invoice/$res1->id")."'>".$res1->sales_code."</a></td>";
				}
				else{
				echo "<td>".$res1->sales_code."</td>";	
				}

				
				echo "<td>".show_date($res1->sales_date)."</td>";
				echo "<td>".$res1->customer_name."</td>";
				echo "<td>".$res1->item_name."</td>";
				echo "<td>".format_qty($res1->sales_qty)."</td>";
				echo "<td>".ucfirst($res1->created_by)."</td>";
				echo "<td>".$res1->seller_points."</td>";
				echo "</tr>";
				$tot_seller_points+=$res1->seller_points;
			}

			$total_columns_count=6;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}

			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-left text-bold'>".number_format($tot_seller_points,2)."</td>
				  </tr>";
		}
		else{
			$total_columns_count=7;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}//report end

	public function show_sales_tax_report(){
		extract($_POST);
		
		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);


		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
				$this->db->where("a.warehouse_id",$warehouse_id);
		}

		$this->db->select("a.warehouse_id,a.store_id,");
		$this->db->select("a.id,a.sales_code,a.sales_date,b.customer_name,a.grand_total,b.tax_number");
		$this->db->select("a.tot_discount_to_all_amt");
		$this->db->select("a.round_off");
		$this->db->select("a.exchange_rate");
		// Add multi-currency support with proper SQL conversion
		$this->db->select("COALESCE(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN a.grand_total / a.exchange_rate ELSE a.grand_total END, 0) as grand_total_base");
		$this->db->select("a.transaction_currency_id, cur.currency_code, cur.symbol");
		
		/*if($customer_id!=''){	
			$this->db->where("a.customer_id=$customer_id");
		}*/
		
		$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");
		
		$this->db->from("db_sales as a");
		$this->db->join("db_currency cur", "cur.id = a.transaction_currency_id", "left");

		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		$this->db->from("db_customers as b");
		$this->db->where("b.`id`= a.`customer_id`");
		
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_price_per_unit=0;
			$tot_discount_amt=0;
			$tot_tax_amt=0;
			$tot_round_off=0;
			$tot_grand_total=0;
			foreach ($q1->result() as $res1) {

				/*Find Tax Amount and Tax Rate*/
				$q2 = $this->db->select("COALESCE(sum(tax_amt),0) as tax_amt")
								->select("COALESCE(sum(price_per_unit),0) as price_per_unit")
								->select("COALESCE(sum(discount_amt),0) as discount_amt")
								->select("COALESCE(avg(t.tax),0) as avg_tax_rate")
								->join("db_tax t", "t.id = db_salesitems.tax_id", "left")
								->where("sales_id",$res1->id)->get("db_salesitems")->row();
				
				$tax_amt = $q2->tax_amt;
				$discount_amt = $q2->discount_amt;
				$price_per_unit = $q2->price_per_unit;
				$avg_tax_rate = $q2->avg_tax_rate;

				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}

				if($res1->store_id==get_current_store_id()){
				echo "<td><a data-toggle='tooltip' target='_blank' title='View Invoice' href='".base_url("sales/invoice/$res1->id")."'>".$res1->sales_code."</a></td>";
				}
				else{
				echo "<td>".$res1->sales_code."</td>";	
				}

				echo "<td>".show_date($res1->sales_date)."</td>";
				echo "<td>".$res1->customer_name."</td>";
				echo "<td>".$res1->tax_number."</td>";
				
				// Use SQL-based conversion for proper currency conversion
				$price_per_unit_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$price_per_unit / $res1->exchange_rate : $price_per_unit;
				$discount_amt_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$discount_amt / $res1->exchange_rate : $discount_amt;
				$tax_amt_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$tax_amt / $res1->exchange_rate : $tax_amt;
				$round_off_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$res1->round_off / $res1->exchange_rate : $res1->round_off;
				$grand_total_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$res1->grand_total / $res1->exchange_rate : $res1->grand_total;
				
				// Display tax rate information
				$tax_rate_info = "";
				if ($avg_tax_rate > 0) {
					$tax_rate_info = " (" . number_format($avg_tax_rate, 2) . "%)";
				}
				
				echo "<td class='text-right'>".store_number_format($price_per_unit_base)." ".$base_currency_symbol."</td>";
				echo "<td class='text-right'>".store_number_format($discount_amt_base)." ".$base_currency_symbol."</td>";
				echo "<td class='text-right'>".store_number_format($tax_amt_base)." ".$base_currency_symbol.$tax_rate_info."</td>";
				echo "<td class='text-right'>".store_number_format($round_off_base)." ".$base_currency_symbol."</td>";
				echo "<td class='text-right'>".store_number_format($grand_total_base)." ".$base_currency_symbol."</td>";
				echo "</tr>";
				$tot_price_per_unit+=$price_per_unit_base;
				$tot_discount_amt+=$discount_amt_base;
				$tot_tax_amt+=$tax_amt_base;
				$tot_round_off+=$round_off_base;
				$tot_grand_total+=$grand_total_base;

			}

			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_price_per_unit)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_discount_amt)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_tax_amt)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_round_off)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_grand_total)." ".$base_currency_symbol."</td>
				  </tr>";
		}
		else{
			$total_columns_count=10;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}//end

	public function show_purchase_tax_report(){
		extract($_POST);
		
		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);


		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
				$this->db->where("a.warehouse_id",$warehouse_id);
		}

		$this->db->select("a.warehouse_id,a.store_id,");
		$this->db->select("a.id,a.purchase_code,a.purchase_date,b.supplier_name,a.grand_total,b.tax_number");
		$this->db->select("a.tot_discount_to_all_amt");
		$this->db->select("a.round_off");
		$this->db->select("a.exchange_rate");
		// Add multi-currency support with proper SQL conversion
		$this->db->select("COALESCE(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN a.grand_total / a.exchange_rate ELSE a.grand_total END, 0) as grand_total_base");
		$this->db->select("a.transaction_currency_id, cur.currency_code, cur.symbol");
		
		/*if($supplier_id!=''){	
			$this->db->where("a.supplier_id=$supplier_id");
		}*/
		
		$this->db->where("(a.purchase_date>='$from_date' and a.purchase_date<='$to_date')");
		
		$this->db->from("db_purchase as a");
		$this->db->join("db_currency cur", "cur.id = a.transaction_currency_id", "left");

		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		$this->db->from("db_suppliers as b");
		$this->db->where("b.`id`= a.`supplier_id`");
		
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_price_per_unit=0;
			$tot_discount_amt=0;
			$tot_tax_amt=0;
			$tot_round_off=0;
			$tot_grand_total=0;
			foreach ($q1->result() as $res1) {

				/*Find Tax Amount and Tax Rate*/
				$q2 = $this->db->select("COALESCE(sum(tax_amt),0) as tax_amt")
								->select("COALESCE(sum(price_per_unit),0) as price_per_unit")
								->select("COALESCE(sum(discount_amt),0) as discount_amt")
								->select("COALESCE(avg(t.tax),0) as avg_tax_rate")
								->join("db_tax t", "t.id = db_purchaseitems.tax_id", "left")
								->where("purchase_id",$res1->id)->get("db_purchaseitems")->row();
				
				$tax_amt = $q2->tax_amt;
				$discount_amt = $q2->discount_amt;
				$price_per_unit = $q2->price_per_unit;
				$avg_tax_rate = $q2->avg_tax_rate;

				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}

				if($res1->store_id==get_current_store_id()){
				echo "<td><a data-toggle='tooltip' target='_blank' title='View Invoice' href='".base_url("purchase/invoice/$res1->id")."'>".$res1->purchase_code."</a></td>";
				}
				else{
				echo "<td>".$res1->purchase_code."</td>";	
				}

				echo "<td>".show_date($res1->purchase_date)."</td>";
				echo "<td>".$res1->supplier_name."</td>";
				echo "<td>".$res1->tax_number."</td>";
				
				// Use SQL-based conversion for proper currency conversion
				$price_per_unit_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$price_per_unit / $res1->exchange_rate : $price_per_unit;
				$discount_amt_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$discount_amt / $res1->exchange_rate : $discount_amt;
				$tax_amt_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$tax_amt / $res1->exchange_rate : $tax_amt;
				$round_off_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$res1->round_off / $res1->exchange_rate : $res1->round_off;
				$grand_total_base = $res1->transaction_currency_id && $res1->transaction_currency_id != 1 && $res1->exchange_rate ? 
					$res1->grand_total / $res1->exchange_rate : $res1->grand_total;
				
				// Display tax rate information
				$tax_rate_info = "";
				if ($avg_tax_rate > 0) {
					$tax_rate_info = " (" . number_format($avg_tax_rate, 2) . "%)";
				}
				
				echo "<td class='text-right'>".store_number_format($price_per_unit_base)." ".$base_currency_symbol."</td>";
				echo "<td class='text-right'>".store_number_format($discount_amt_base)." ".$base_currency_symbol."</td>";
				echo "<td class='text-right'>".store_number_format($tax_amt_base)." ".$base_currency_symbol.$tax_rate_info."</td>";
				echo "<td class='text-right'>".store_number_format($round_off_base)." ".$base_currency_symbol."</td>";
				echo "<td class='text-right'>".store_number_format($grand_total_base)." ".$base_currency_symbol."</td>";
				echo "</tr>";
				$tot_price_per_unit+=$price_per_unit_base;
				$tot_discount_amt+=$discount_amt_base;
				$tot_tax_amt+=$tax_amt_base;
				$tot_round_off+=$round_off_base;
				$tot_grand_total+=$grand_total_base;

			}

			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_price_per_unit)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_discount_amt)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_tax_amt)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_round_off)." ".$base_currency_symbol."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_grand_total)." ".$base_currency_symbol."</td>
				  </tr>";
		}
		else{
			$total_columns_count=10;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}//end

	public function show_gstr_1_report(){
		extract($_POST);
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);


		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
				$this->db->where("a.warehouse_id",$warehouse_id);
		}

		$this->db->select("a.warehouse_id,a.store_id,a.return_bit");
		$this->db->select("a.id,a.sales_code,a.sales_date,b.customer_name,a.grand_total,b.gstin,a.customer_id,b.state_id,a.coupon_amt");
		$this->db->select("a.tot_discount_to_all_amt");
		$this->db->select("a.round_off");
		
		
		$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");
		
		$this->db->from("db_sales as a");

		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		$this->db->join("db_customers as b","b.`id`= a.`customer_id`","left");
		
		
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_price_per_unit=0;
			$tot_discount_amt=0;
			$tot_tax_amt=0;
			$tot_round_off=0;
			$tot_grand_total=0;

			$tot_cgst_amt=0;
			$tot_sgst_amt=0;
			$tot_igst_amt=0;

			foreach ($q1->result() as $res1) {
				$coupon_amt = $res1->coupon_amt;

				/*Find Tax Amount*/
				$q2 = $this->db->select("tax_amt,tax_id")
								->select("price_per_unit")
								->select("discount_amt")
								->where("sales_id",$res1->id)
								->from("db_salesitems")
								->get();

				//echo $this->db->get_compiled_select();exit;

				foreach($q2->result() as $res2){

						$tax_amt = $res2->tax_amt;
						$discount_amt = $res2->discount_amt;
						$discount_amt += $coupon_amt;
						$price_per_unit = $res2->price_per_unit;


						/*Find Customer State*/
						$customer_state=get_state($res1->state_id);
						
						/*Set GST type*/
						$sgst_amt =$cgst_amt=$igst_amt = 0;

						$total_before_tax = $res1->grand_total - $discount_amt - $tax_amt;

						$total_after_tax = $total_before_tax + $tax_amt;

						

						if(empty($customer_state) || (strtoupper($customer_state) == strtoupper(get_store_details($res1->store_id)->state))){
						    $sgst_amt = $cgst_amt = $tax_amt / 2;
						}else{
						    $sgst_amt = $cgst_amt = 0;
						    $igst_amt = $tax_amt;
						}


						echo "<tr>";
						echo "<td>".++$i."</td>";
						if(store_module() && is_admin()){
							echo "<td>".get_store_name($res1->store_id)."</td>";	
						}

						$return_label = ($res1->return_bit==1) ? '<br><span class="text-danger">(Returned)</span>' : '';
						if($res1->store_id==get_current_store_id()){
						echo "<td><a data-toggle='tooltip' target='_blank' title='View Invoice' href='".base_url("sales/invoice/$res1->id")."'>".$res1->sales_code."</a>".$return_label."</td>";
						}
						else{
						echo "<td>".$res1->sales_code.$return_label."</td>";	
						}

						echo "<td>".show_date($res1->sales_date)."</td>";
						echo "<td>".$res1->customer_name."</td>";
						echo "<td>".$res1->gstin."</td>";
						echo "<td class='text-right'>".store_number_format($price_per_unit)."</td>";
						echo "<td class='text-right'>".store_number_format($discount_amt)."</td>";
						echo "<td class='text-right'>".get_tax_details($res2->tax_id)->tax_name."</td>";
						echo "<td class='text-right'>".store_number_format($cgst_amt)."</td>";
						echo "<td class='text-right'>".store_number_format($sgst_amt)."</td>";
						echo "<td class='text-right'>".store_number_format($igst_amt)."</td>";

						// echo "<td class='text-right'>".store_number_format($res1->round_off)."</td>";
						// echo "<td class='text-right'>".store_number_format($res1->grand_total)."</td>";
						echo "</tr>";
						$tot_price_per_unit+=$price_per_unit;
						$tot_discount_amt+=$discount_amt;
						$tot_tax_amt+=$tax_amt;
						$tot_round_off+=$res1->round_off;
						$tot_grand_total+=$res1->grand_total;

						$tot_cgst_amt+=$cgst_amt;
						$tot_sgst_amt+=$sgst_amt;
						$tot_igst_amt+=$igst_amt;

				}//foreach 2
			}//foreach 1

			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_price_per_unit)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_discount_amt)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_cgst_amt)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_sgst_amt)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_igst_amt)."</td>";

					  /*echo "<td class='text-right text-bold'>".store_number_format($tot_round_off)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_grand_total)."</td>";*/

				  echo "</tr>";
		}
		else{
			$total_columns_count=13;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}//end
	
	public function show_gstr_2_report(){
		extract($_POST);
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);


		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
				$this->db->where("a.warehouse_id",$warehouse_id);
		}

		$this->db->select("a.warehouse_id,a.store_id,");
		$this->db->select("a.id,a.purchase_code,a.purchase_date,b.supplier_name,a.grand_total,b.tax_number,a.supplier_id,b.state_id");
		$this->db->select("a.tot_discount_to_all_amt");
		$this->db->select("a.round_off");
		
		
		$this->db->where("(a.purchase_date>='$from_date' and a.purchase_date<='$to_date')");
		
		$this->db->from("db_purchase as a");

		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		$this->db->from("db_suppliers as b");
		$this->db->where("b.`id`= a.`supplier_id`");
		
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_price_per_unit=0;
			$tot_discount_amt=0;
			$tot_tax_amt=0;
			$tot_round_off=0;
			$tot_grand_total=0;

			$tot_cgst_amt=0;
			$tot_sgst_amt=0;
			$tot_igst_amt=0;

			foreach ($q1->result() as $res1) {

				/*Find Tax Amount*/
				$q2 = $this->db->select("tax_amt,tax_id")
								->select("price_per_unit")
								->select("discount_amt")
								->where("purchase_id",$res1->id)
								->get("db_purchaseitems");

				foreach ($q2->result() as $res2) {
						
						$tax_amt = $res2->tax_amt;
						$discount_amt = $res2->discount_amt;
						$price_per_unit = $res2->price_per_unit;


						/*Find supplier State*/
						$supplier_state='';
						if(!empty($res1->state_id)){
							$supplier_state=$this->db->query("select state from db_states where id='".$res1->state_id."'")->row()->state;
						}

						/*Set GST type*/
						$sgst_amt =$cgst_amt=$igst_amt = 0;

						$total_before_tax = $res1->grand_total - $discount_amt - $tax_amt;

						$total_after_tax = $total_before_tax + $tax_amt;

						
						
						if(empty($supplier_state) || (strtoupper($supplier_state) == strtoupper(get_store_details($res1->store_id)->state))){
						    $sgst_amt = $cgst_amt = $tax_amt / 2;
						}else{
						    $sgst_amt = $cgst_amt = 0;
						    $igst_amt = $tax_amt;
						}


						echo "<tr>";
						echo "<td>".++$i."</td>";
						if(store_module() && is_admin()){
							echo "<td>".get_store_name($res1->store_id)."</td>";	
						}

						if($res1->store_id==get_current_store_id()){
						echo "<td><a data-toggle='tooltip' target='_blank' title='View Invoice' href='".base_url("purchase/invoice/$res1->id")."'>".$res1->purchase_code."</a></td>";
						}
						else{
						echo "<td>".$res1->purchase_code."</td>";	
						}

						echo "<td>".show_date($res1->purchase_date)."</td>";
						echo "<td>".$res1->supplier_name."</td>";
						echo "<td>".$res1->tax_number."</td>";
						echo "<td class='text-right'>".store_number_format($price_per_unit)."</td>";
						echo "<td class='text-right'>".store_number_format($discount_amt)."</td>";
						echo "<td class='text-right'>".get_tax_details($res2->tax_id)->tax_name."</td>";
						echo "<td class='text-right'>".store_number_format($cgst_amt)."</td>";
						echo "<td class='text-right'>".store_number_format($sgst_amt)."</td>";
						echo "<td class='text-right'>".store_number_format($igst_amt)."</td>";

							/*echo "<td class='text-right'>".store_number_format($res1->round_off)."</td>";
							echo "<td class='text-right'>".store_number_format($res1->grand_total)."</td>";*/
						echo "</tr>";
						$tot_price_per_unit+=$price_per_unit;
						$tot_discount_amt+=$discount_amt;
						$tot_tax_amt+=$tax_amt;
						$tot_round_off+=$res1->round_off;
						$tot_grand_total+=$res1->grand_total;

						$tot_cgst_amt+=$cgst_amt;
						$tot_sgst_amt+=$sgst_amt;
						$tot_igst_amt+=$igst_amt;
					}//foreach 2

			}//foreach 1

			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-right text-bold'>".store_number_format($tot_price_per_unit)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_discount_amt)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_cgst_amt)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_sgst_amt)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_igst_amt)."</td>";
					  /*echo "<td class='text-right text-bold'>".store_number_format($tot_round_off)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_grand_total)."</td>";*/
				  echo "</tr>";
		}
		else{
			$total_columns_count=13;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}//end


	public function show_customer_orders(){
		extract($_POST);

		
		$within_date = (!empty($within_date)) ? system_fromatted_date($within_date) : '';
	
		$this->db->select("*");
		$this->db->from("db_customers");
	    if(!empty($store_id)){
			$this->db->where("store_id",$store_id);
		}
		if($customer_id!=''){
			$this->db->where("id=$customer_id");
		}
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();

		//print_r($q1);exit;
		if($q1->num_rows()>0){

			$i=0;
			foreach ($q1->result() as $res1) {

				$this->db->select("sales_date,sales_code,id")
						->from("db_sales")
						->where("customer_id",$res1->id);
				if(!empty($within_date)){
					$this->db->where("sales_date<='$within_date'");
				}
				$this->db->order_by("sales_date",'asc');
						/*echo "<br> ".$this->db->get_compiled_select();
						continue;*/
						
						$q2 = $this->db->get();

						//echo "<br> ".$q2->num_rows();
						//continue;
				if($q2->num_rows()>0){
					
						//$res2 = $q2->row();

						foreach($q2->result() as $res2){
							$date_difference = date_difference($res2->sales_date,date("Y-m-d"));

							echo "<tr>";
							echo "<td>".++$i."</td>";
							if(store_module() && is_admin()){
								echo "<td>".get_store_name($res1->store_id)."</td>";	
							}
							echo "<td>".$res1->customer_name."</td>";
							echo "<td>".show_date($res2->sales_date)."</td>";
							
							if($store_id==get_current_store_id()){
							echo "<td><a title='View Invoice' href='".base_url("sales/invoice/$res2->id")."'>".$res2->sales_code."</a></td>";
							}
							else{
							echo "<td>".$res2->sales_code."</td>";	
							}
							echo "<td>".$date_difference."</td>";
							echo "</tr>";
						}
						
				}
				

			}

		}
		else{
			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}

	public function show_delivery_sheet(){
		extract($_POST);

		/*$from_date=date("Y-m-d",strtotime($from_date));
		$to_date=date("Y-m-d",strtotime($to_date));*/
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		$this->db->select("a.id,a.sales_code,a.sales_date,b.customer_name,a.grand_total,a.paid_amount,a.store_id,a.created_time");
	    
		if($customer_id!=''){
			
			$this->db->where("a.customer_id=$customer_id");
		}
		
		$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");
		
		$this->db->where("b.`id`= a.`customer_id`");
		$this->db->from("db_sales as a");
		$this->db->where("a.`sales_status`= 'Final'");

		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		$this->db->from("db_customers as b");
		
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_grand_total=0;
			$tot_paid_amount=0;
			$due_amount=0;
			$tot_due_amount=0;
			$tot_sales_qty=0;
			$tot_return_qty=0;
			foreach ($q1->result() as $res1) {

				$tot_grand_total+=$res1->grand_total;
				$tot_paid_amount+=$res1->paid_amount;
				

				//Find the Sales items of the item
				$q3 = $this->db->select("coalesce(sum(sales_qty),0) as sales_qty")
								->where("sales_id",$res1->id)
								->get("db_salesitems")->row();
				$sales_qty = $q3->sales_qty;

				$q4 = $this->db->select("coalesce(sum(grand_total),0) as grand_total")
								->select("coalesce(sum(paid_amount),0) as paid_amount")
								->where("sales_id",$res1->id)
								->get("db_salesreturn")->row();

				//Find the return of the item
				$q2 = $this->db->select("coalesce(sum(return_qty),0) as return_qty")
								->where("sales_id",$res1->id)
								->get("db_salesitemsreturn")->row();

				$return_qty = $q2->return_qty;

				$return_tot = $q4->grand_total;

				$invoices_tot = $res1->grand_total - $return_tot;

				$due_amount=($res1->grand_total-$res1->paid_amount);
				$due_amount-=($q4->paid_amount);
				$tot_due_amount+=$due_amount;


				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				
				echo "<td>".show_date($res1->sales_date)."</td>";
				echo "<td>".$res1->created_time."</td>";

				if($store_id==get_current_store_id()){
				echo "<td><a title='View Invoice' href='".base_url("sales/invoice/$res1->id")."'>".$res1->sales_code."</a></td>";
				}
				else{
				echo "<td>".$res1->sales_code."</td>";	
				}
				
				echo "<td>".$res1->customer_name."</td>";
				echo "<td class='text-left'>".format_qty($sales_qty)."</td>";
				echo "<td class='text-left'>".format_qty($return_qty)."</td>";
				echo "<td class='text-right'>".store_number_format($invoices_tot)."</td>";
				echo "<td class='text-right'>".store_number_format($due_amount)."</td>";
				
				echo "</tr>";

				$tot_return_qty+=$return_qty;
				$tot_sales_qty+=$sales_qty;
				

			}

			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-left text-bold'>".format_qty($tot_sales_qty)."</td>
					  <td class='text-left text-bold'>".format_qty($tot_return_qty)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_grand_total)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_due_amount)."</td>
					  
				  </tr>";
		}
		else{
			$total_columns_count=9;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}


	public function show_load_sheet(){
		extract($_POST);

		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		
		$this->db->select("a.id,a.sales_code,a.sales_date,b.customer_name,b.customer_code,a.grand_total,a.paid_amount,a.store_id");
		$this->db->select("sum(c.sales_qty) as sales_qty");
		$this->db->select("d.item_name,d.brand_id");
	    
	    
			$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");
		$this->db->order_by("a.`sales_date`,a.sales_code",'desc');
		$this->db->from("db_sales as a");
		$this->db->where("a.`id`= c.`sales_id`");
		$this->db->where("a.`sales_status`= 'Final'");
		$this->db->from("db_items as d");
		$this->db->where("d.`id`= c.`item_id`");
		$this->db->from("db_customers as b");
		$this->db->where("b.`id`= a.`customer_id`");
		$this->db->from("db_salesitems as c");
		$this->db->group_by("c.item_id");
		
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		
		
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			
			$tot_qty=0;
			foreach ($q1->result() as $res1) {

				$brand_name = (!empty($res1->brand_id)) ? get_brand_details($res1->brand_id)->brand_name : '';

				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
							
				echo "<td>".show_date($res1->sales_date)."</td>";
				echo "<td>".$brand_name."</td>";
				echo "<td>".$res1->item_name."</td>";
				echo "<td>".format_qty($res1->sales_qty)."</td>";
				echo "</tr>";

				$tot_qty+=$res1->sales_qty;

			}

			$total_columns_count=4;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
		

			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-left text-bold'>".format_qty($tot_qty)."</td>
				  </tr>";
		}
		else{
			$total_columns_count=5;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}
	public function show_sales_gst_report(){
		extract($_POST);
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);


		/*if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
				$this->db->where("a.warehouse_id",$warehouse_id);
		}*/

		if(!empty($customer_id)){
			$this->db->where("a.customer_id",$customer_id);
		}
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}

		$this->db->select("
							a.store_id,
							a.id,
							a.sales_code,
							a.sales_date,
							a.customer_id,
							a.round_off,
							a.coupon_amt,

							b.state_id,
							b.gstin,
							b.customer_name,

							c.item_id,
							c.sales_qty,
							c.price_per_unit,
							c.tax_type,
							c.tax_id,
							c.tax_amt,
							c.discount_type,
							c.discount_input,
							c.discount_amt,
							c.unit_total_cost,
							c.total_cost,

							d.item_name,
							d.hsn,

							t.tax_name,
							t.tax,

							s.state,
						");
		
		
		$this->db->from("db_sales as a");
		$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");
		//Customer - Join
		$this->db->join("db_customers as b","b.`id`= a.`customer_id`","left");
		//Sales Items - Join
		$this->db->join("db_salesitems as c","c.`sales_id`= a.id","left");
		//Item Details - Join
		$this->db->join("db_items as d","d.`id`= c.item_id","left");
		//Tax - Join
		$this->db->join("db_tax as t","t.`id`= c.tax_id","left");
		//Store - Join
		$this->db->join("db_store as s","s.`id`= a.store_id","left");

		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_price_per_unit=0;
			$tot_discount_amt=0;
			$tot_tax_amt=0;
			$tot_round_off=0;
			$tot_total_cost=0;
			$tot_sales_qty=0;
			$tot_taxable=0;

			$tot_cgst_amt = $tot_sgst_amt = $tot_igst_amt = 0;

			foreach ($q1->result() as $res1) {
				//Coupon amount
				$coupon_amt = $res1->coupon_amt;
				//Taxable
				$taxable = $res1->price_per_unit-$res1->tax_amt;

				//Customer State
				/*Find Customer State*/
				$customer_state='';
				if(!empty($res1->state_id)){
					$customer_state=$this->db->query("select state from db_states where id='".$res1->state_id."'")->row()->state;
				}

				//validate GST Type
				$gst_type = (strtoupper($customer_state)==strtoupper($res1->state)) ? "GST" : "IGST";

				//Set GST type
				//if($gst_type=='GST'){//Within state
				if(empty($customer_state) || (strtoupper($customer_state) == strtoupper(get_store_details($res1->store_id)->state))){
					$gst_tax_per = ($res1->tax/2);
				    $cgst_amt = ($res1->tax_amt / 2);
				    $sgst_amt = $cgst_amt;
				    $igst_amt =0;
				    $igst_tax_per = 0;
				}else{//IGST
					$igst_tax_per = $res1->tax;
				    $igst_amt = $res1->tax_amt;
				    $cgst_amt = 0;
				    $sgst_amt = 0;
				    $gst_tax_per=0;
				}


				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}

				if($res1->store_id==get_current_store_id()){
				echo "<td><a data-toggle='tooltip' target='_blank' title='View Invoice' href='".base_url("sales/invoice/$res1->id")."'>".$res1->sales_code."</a></td>";
				}
				else{
				echo "<td>".$res1->sales_code."</td>";	
				}

				echo "<td>".$res1->customer_name."</td>";
				echo "<td>".$res1->gstin."</td>";
				echo "<td>".show_date($res1->sales_date)."</td>";
				echo "<td>".$res1->item_name."</td>";
				echo "<td>".format_qty($res1->sales_qty)."</td>";
				echo "<td>".$res1->hsn."</td>";
				echo "<td class='text-right'>".store_number_format($res1->price_per_unit)."</td>";
				echo "<td class='text-right'>".store_number_format($res1->discount_amt+$coupon_amt)."</td>";
				echo "<td class='text-right'>".store_number_format($taxable)."</td>";
				echo "<td class='text-right'>".$res1->tax_name."</td>";
				echo "<td class='text-right'>".store_number_format($gst_tax_per)."</td>";
				echo "<td class='text-right'>".store_number_format($cgst_amt)."</td>";
				echo "<td class='text-right'>".store_number_format($gst_tax_per)."</td>";
				echo "<td class='text-right'>".store_number_format($sgst_amt)."</td>";
				echo "<td class='text-right'>".store_number_format($igst_tax_per)."</td>";
				echo "<td class='text-right'>".store_number_format($igst_amt)."</td>";

				echo "<td class='text-right'>".store_number_format($res1->round_off)."</td>";
				echo "<td class='text-right'>".store_number_format($res1->total_cost)."</td>";
				echo "</tr>";
				$tot_price_per_unit+=$res1->price_per_unit;
				$tot_discount_amt+=$res1->discount_amt+$coupon_amt;
				$tot_tax_amt+=$res1->tax_amt;
				$tot_round_off+=$res1->round_off;
				$tot_total_cost+=$res1->total_cost;
				$tot_sales_qty+=$res1->sales_qty;
				$tot_taxable+=$taxable;

				$tot_cgst_amt+=$cgst_amt;
				$tot_sgst_amt+=$sgst_amt;
				$tot_igst_amt+=$igst_amt;


			}

			$total_columns_count=6;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-right text-bold'>".format_qty($tot_sales_qty)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_price_per_unit)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_discount_amt)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_taxable)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_cgst_amt)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_sgst_amt)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_igst_amt)."</td>

					  <td class='text-right text-bold'>".store_number_format($tot_round_off)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_total_cost)."</td>
				  </tr>";
		}
		else{
			$total_columns_count=20;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}//end

	public function show_purchase_gst_report(){
		extract($_POST);
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);


		/*if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
				$this->db->where("a.warehouse_id",$warehouse_id);
		}*/

		if(!empty($supplier_id)){
			$this->db->where("a.supplier_id",$supplier_id);
		}
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}

		$this->db->select("
							a.store_id,
							a.id,
							a.purchase_code,
							a.purchase_date,
							a.supplier_id,
							a.round_off,

							b.state_id,
							b.gstin,
							b.supplier_name,

							c.item_id,
							c.purchase_qty,
							c.price_per_unit,
							c.tax_type,
							c.tax_id,
							c.tax_amt,
							c.discount_type,
							c.discount_input,
							c.discount_amt,
							c.unit_total_cost,
							c.total_cost,

							d.item_name,
							d.hsn,

							t.tax_name,
							t.tax,

							s.state,
						");
		
		
		$this->db->from("db_purchase as a");
		$this->db->where("(a.purchase_date>='$from_date' and a.purchase_date<='$to_date')");
		//supplier - Join
		$this->db->join("db_suppliers as b","b.`id`= a.`supplier_id`","left");
		//purchase Items - Join
		$this->db->join("db_purchaseitems as c","c.`purchase_id`= a.id","left");
		//Item Details - Join
		$this->db->join("db_items as d","d.`id`= c.item_id","left");
		//Tax - Join
		$this->db->join("db_tax as t","t.`id`= c.tax_id","left");
		//Store - Join
		$this->db->join("db_store as s","s.`id`= a.store_id","left");

		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_price_per_unit=0;
			$tot_discount_amt=0;
			$tot_tax_amt=0;
			$tot_round_off=0;
			$tot_total_cost=0;
			$tot_purchase_qty=0;
			$tot_taxable=0;

			$tot_cgst_amt = $tot_sgst_amt = $tot_igst_amt = 0;

			foreach ($q1->result() as $res1) {

				//Taxable
				$taxable = $res1->price_per_unit-$res1->tax_amt;

				//validate GST Type
				$supplier_state='';
				if(!empty($res1->state_id)){
					$supplier_state=$this->db->query("select state from db_states where id='".$res1->state_id."'")->row()->state;
				}

				//$gst_type = (strtoupper($supplier_state)==strtoupper($res1->state)) ? "GST" : "IGST";

				//Set GST type
				//if($gst_type=='GST'){//Within state

				if(empty($supplier_state) || (strtoupper($supplier_state) == strtoupper(get_store_details($res1->store_id)->state))){
					$gst_tax_per = ($res1->tax/2);
				    $cgst_amt = ($res1->tax_amt / 2);
				    $sgst_amt = $cgst_amt;
				    $igst_amt =0;
				    $igst_tax_per =0;
				}else{//IGST
					$igst_tax_per = $res1->tax;
				    $igst_amt = $res1->tax_amt;
				    $cgst_amt = 0;
				    $sgst_amt = 0;
				    $gst_tax_per = 0;
				}


				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}

				if($res1->store_id==get_current_store_id()){
				echo "<td><a data-toggle='tooltip' target='_blank' title='View Invoice' href='".base_url("purchase/invoice/$res1->id")."'>".$res1->purchase_code."</a></td>";
				}
				else{
				echo "<td>".$res1->purchase_code."</td>";	
				}

				echo "<td>".$res1->supplier_name."</td>";
				echo "<td>".$res1->gstin."</td>";
				echo "<td>".show_date($res1->purchase_date)."</td>";
				echo "<td>".$res1->item_name."</td>";
				echo "<td>".format_qty($res1->purchase_qty)."</td>";
				echo "<td>".$res1->hsn."</td>";
				echo "<td class='text-right'>".store_number_format($res1->price_per_unit)."</td>";
				echo "<td class='text-right'>".store_number_format($res1->discount_amt)."</td>";
				echo "<td class='text-right'>".store_number_format($taxable)."</td>";
				echo "<td class='text-right'>".$res1->tax_name."</td>";
				echo "<td class='text-right'>".store_number_format($gst_tax_per)."</td>";
				echo "<td class='text-right'>".store_number_format($cgst_amt)."</td>";
				echo "<td class='text-right'>".store_number_format($gst_tax_per)."</td>";
				echo "<td class='text-right'>".store_number_format($sgst_amt)."</td>";
				echo "<td class='text-right'>".store_number_format($igst_tax_per)."</td>";
				echo "<td class='text-right'>".store_number_format($igst_amt)."</td>";

				echo "<td class='text-right'>".store_number_format($res1->round_off)."</td>";
				echo "<td class='text-right'>".store_number_format($res1->total_cost)."</td>";
				echo "</tr>";
				$tot_price_per_unit+=$res1->price_per_unit;
				$tot_discount_amt+=$res1->discount_amt;
				$tot_tax_amt+=$res1->tax_amt;
				$tot_round_off+=$res1->round_off;
				$tot_total_cost+=$res1->total_cost;
				$tot_purchase_qty+=$res1->purchase_qty;
				$tot_taxable+=$taxable;

				$tot_cgst_amt+=$cgst_amt;
				$tot_sgst_amt+=$sgst_amt;
				$tot_igst_amt+=$igst_amt;


			}

			$total_columns_count=6;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-left text-bold'>".format_qty($tot_purchase_qty)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_price_per_unit)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_discount_amt)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_taxable)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_cgst_amt)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_sgst_amt)."</td>
					  <td class='text-right text-bold'></td>
					  <td class='text-right text-bold'>".store_number_format($tot_igst_amt)."</td>
					  
					  <td class='text-right text-bold'>".store_number_format($tot_round_off)."</td>
					  <td class='text-right text-bold'>".store_number_format($tot_total_cost)."</td>
				  </tr>";
		}
		else{
			$total_columns_count=20;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}//end


	public function show_return_items_report(){
		extract($_POST);
		

		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		
		$this->db->select("a.id,a.return_date,a.return_code,b.customer_name,a.store_id,a.return_status");
		$this->db->from("db_salesreturn a");
		$this->db->where("(a.return_date>='$from_date' and a.return_date<='$to_date')");
		if(!empty($warehouse_id)){
			$this->db->where("a.warehouse_id",$warehouse_id);
		}
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		$this->db->join("db_customers b","b.`id`= a.`customer_id`",'left');
		$this->db->order_by("a.`return_date`,a.return_code",'desc');
		//echo $this->db->get_compiled_select();exit();
		$q1 = $this->db->get();
		if($q1->num_rows()>0){
			$tot_total_cost=0;
			
			foreach ($q1->result() as $res1) {
				$sales_id = $res1->id;

				$this->db->select(" c.total_cost,
									c.return_qty,
									d.item_name,
								");
				//Join
				$this->db->from("db_salesitemsreturn c");
				$this->db->where("c.return_id",$sales_id);
				if($item_id!=''){
					$this->db->where("c.item_id=$item_id");
				}
				$this->db->join("db_items d","d.`id`= c.`item_id`","left");
				//echo $this->db->get_compiled_select();exit();
				$q2=$this->db->get();

					if($q2->num_rows()>0){
					$i=0;
					
					
					foreach ($q2->result() as $res2) {
							echo "<tr>";
							echo "<td>".++$i."</td>";
							if(store_module() && is_admin()){
								echo "<td>".get_store_name($res1->store_id)."</td>";	
							}
							if($store_id==get_current_store_id()){
							echo "<td><a title='View Invoice' href='".base_url("sales_return/invoice/$res1->id")."'>".$res1->return_code."</a></td>";
							}
							else{
							echo "<td>".$res1->return_code."</td>";	
							}

							
							echo "<td>".show_date($res1->return_date)."</td>";
							echo "<td>".$res1->return_status."</td>";
							echo "<td>".$res1->customer_name."</td>";
							echo "<td>".$res2->item_name."</td>";
							echo "<td>".format_qty($res2->return_qty)."</td>";
							echo "<td class='text-right'>".store_number_format($res2->total_cost)."</td>";
							echo "</tr>";
							
							$tot_total_cost+=$res2->total_cost;

					}// foreach $res2
					//Print Total
					$total_columns_count=6;
					if(store_module() && is_admin()){
						$total_columns_count ++;
					}
					if(warehouse_module() && warehouse_count()>0){
						$total_columns_count ++;
					}

					
				}//num_rows $q2
				else{
					echo "No Records Found";
				}


			}//foreach $res1

			echo "<tr>
							  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
							  <td class='text-right text-bold'>".store_number_format($tot_total_cost)."</td>
							  
						  </tr>";

		}//num_rows
		else{
			$total_columns_count=8;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			if(warehouse_module() && warehouse_count()>0){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
	}

	public function sales_and_payments_report(){
		extract($_POST);

		$from_date = (!empty($from_date)) ? system_fromatted_date($from_date) : '';
		$to_date = (!empty($to_date)) ? system_fromatted_date($to_date) : '';
		$store_id = (!empty($store_id)) ? $store_id : null;

		// Debug logging
		log_message('debug', 'Sales & Payments Report - Customer ID: ' . $customer_id . ', From: ' . $from_date . ', To: ' . $to_date . ', Store: ' . $store_id);
		
		// Add error handling for missing customer_id
		if(empty($customer_id)) {
			echo "<tr><td colspan='9' class='text-center text-warning'>Please select a customer first.</td></tr>";
			return;
		}

		// Load helper and get base currency for conversion
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'UGX';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : 'USh';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';

		// Get customer's preferred currency (from first transaction or default to base)
		$customer_currency = $base_currency; // Default to base currency
		if(!empty($customer_id)) {
			$customer_currency_query = $this->db->query("
				SELECT DISTINCT c.currency_code, c.symbol, c.currency_position 
				FROM db_sales s 
				JOIN db_currency c ON s.transaction_currency_id = c.id 
				WHERE s.customer_id = ? 
				ORDER BY s.sales_date DESC 
				LIMIT 1
			", array($customer_id));
			if($customer_currency_query->num_rows() > 0) {
				$customer_currency = $customer_currency_query->row();
			}
		}
		$customer_currency_code = $customer_currency ? $customer_currency->currency_code : $base_currency_code;
		$customer_currency_symbol = $customer_currency ? $customer_currency->symbol : $base_currency_symbol;
		$customer_currency_position = $customer_currency ? $customer_currency->currency_position : $base_currency_position;

		$i=0;
		$tot_qty=0;
		$tot_total_cost=0;
		$tot_payment=0;
		$running_balance=0; // Running balance in base currency
		$running_balance_customer=0; // Running balance in customer's original currency

		// Simple query to get sales and payments
		$sql = "
			SELECT 
				sales_date as date, 
				'Sale' as type, 
				sales_code as reference, 
				CONCAT('Sale - ', sales_code) as description, 
				grand_total as amount,
				COALESCE(transaction_currency_id, 1) as currency_id,
				COALESCE(c.currency_code, ?) as currency_code,
				COALESCE(c.symbol, ?) as currency_symbol,
				COALESCE(c.currency_position, ?) as currency_position,
				COALESCE(base_currency_total, grand_total) as base_amount,
				reference_no,
				created_time,
				s.id as sales_id
			FROM db_sales s
			LEFT JOIN db_currency c ON s.transaction_currency_id = c.id
			WHERE s.customer_id = ? 
			AND s.sales_date >= ? 
			AND s.sales_date <= ?
			" . ($store_id ? " AND s.store_id = ?" : "") . "
			
			UNION ALL
			
			SELECT 
				payment_date as date, 
				'Payment' as type, 
				payment_code as reference, 
				CONCAT('Payment - ', payment_code) as description, 
				payment as amount,
				COALESCE(payment_currency_id, 1) as currency_id,
				COALESCE(c.currency_code, ?) as currency_code,
				COALESCE(c.symbol, ?) as currency_symbol,
				COALESCE(c.currency_position, ?) as currency_position,
				COALESCE(base_currency_amount, payment) as base_amount,
				payment_note as reference_no,
				created_time,
				NULL as sales_id
			FROM db_salespayments p
			LEFT JOIN db_currency c ON p.payment_currency_id = c.id
			WHERE p.customer_id = ? 
			AND p.payment_date >= ? 
			AND p.payment_date <= ?
			" . ($store_id ? " AND p.store_id = ?" : "") . "
			
		ORDER BY date ASC, created_time ASC, FIELD(type, 'Purchase', 'Return', 'Payment')
		";
		
		// Prepare parameters
		$params = [
			$base_currency_code, $base_currency_symbol, $base_currency_position, // Sales COALESCE
			$customer_id, $from_date ?: '1900-01-01', $to_date ?: '2099-12-31' // Sales WHERE
		];
		
		if($store_id) {
			$params[] = $store_id; // Sales store_id
		}
		
		// Add payments parameters
		$params[] = $base_currency_code; // Payments COALESCE currency_code
		$params[] = $base_currency_symbol; // Payments COALESCE symbol
		$params[] = $base_currency_position; // Payments COALESCE position
		$params[] = $customer_id; // Payments WHERE customer_id
		$params[] = $from_date ?: '1900-01-01'; // Payments WHERE from_date
		$params[] = $to_date ?: '2099-12-31'; // Payments WHERE to_date
		
		if($store_id) {
			$params[] = $store_id; // Payments store_id
		}
		
		try {
			log_message('debug', 'Sales & Payments Query Parameters: ' . json_encode($params));
			$q1 = $this->db->query($sql, $params);
			log_message('debug', 'Sales & Payments Query executed successfully. Rows: ' . $q1->num_rows());
		} catch (Exception $e) {
			log_message('error', 'Sales & Payments Query Error: ' . $e->getMessage());
			echo "<tr><td colspan='9' class='text-center text-danger'>Database Error: " . $e->getMessage() . "</td></tr>";
			return;
		}

		if($q1->num_rows() > 0) {
			foreach ($q1->result() as $row) {
				// Skip zero payments
				if($row->type == 'Payment' && $row->amount == 0) {
					continue;
				}
				
				// Get item details for sales
				$item_name = '';
				$qty = 0;
				if($row->type == 'Sale') {
					// Get first item name and total qty for this sale using sales_id
					$this->db->select("b.item_name, SUM(a.sales_qty) as total_qty");
					$this->db->from("db_salesitems a");
					$this->db->join("db_items b", "b.id = a.item_id", "left");
					$this->db->where("a.sales_id", $row->sales_id);
					$this->db->group_by("a.sales_id");
					$item_result = $this->db->get();
					if($item_result->num_rows() > 0) {
						$item_data = $item_result->row();
						$item_name = $item_data->item_name;
						$qty = $item_data->total_qty;
					}
				}
				
				// Format currency based on position
				$format_amount = function($amount, $symbol, $position) {
					$formatted = number_format($amount, 2);
					return $position == 'before' ? $symbol . $formatted : $formatted . $symbol;
				};
				
				// Calculate running balance (both system and customer currency)
				if($row->type == 'Sale') {
					$running_balance += $row->base_amount;
					$running_balance_customer += $row->amount; // Original customer currency
					$tot_total_cost += $row->base_amount;
					$tot_qty += $qty;
				} else {
					$running_balance -= $row->base_amount;
					$running_balance_customer -= $row->amount; // Original customer currency
					$tot_payment += $row->base_amount;
				}
				
				echo "<tr>";
				echo "<td class='text-center'>" . ++$i . "</td>";
				echo "<td>" . show_date($row->date) . "</td>";
				echo "<td>" . $row->reference . "</td>";
				echo "<td>";
				if($row->type == 'Sale') {
					echo "<strong>Item:</strong> " . $item_name . "<br>";
					if($row->reference_no) {
						echo "<strong>Ref:</strong> " . $row->reference_no;
					}
				} else {
					echo "<strong>Payment Type:</strong> " . ($row->reference_no ?: 'Cash') . "<br>";
					echo "<strong>Note:</strong> " . ($row->description ?: 'Payment received');
				}
				echo "</td>";
				echo "<td class='text-center'>" . format_qty($qty) . "</td>";
				
				// Show both base currency and original currency
				if($row->type == 'Sale') {
					$base_amount = $format_amount($row->base_amount, $base_currency_symbol, $base_currency_position);
					$original_amount = $format_amount($row->amount, $row->currency_symbol, $row->currency_position);
					echo "<td class='text-right bill-amount'>";
					echo "<div><strong>" . $base_amount . "</strong></div>";
					if($row->base_amount != $row->amount) {
						echo "<div><small>(" . $original_amount . ")</small></div>";
					}
					echo "</td>";
				} else {
					echo "<td class='text-right'>0.00</td>";
				}
				
				if($row->type == 'Payment') {
					$base_amount = $format_amount($row->base_amount, $base_currency_symbol, $base_currency_position);
					$original_amount = $format_amount($row->amount, $row->currency_symbol, $row->currency_position);
					echo "<td class='text-right payment-amount'>";
					echo "<div><strong>" . $base_amount . "</strong></div>";
					if($row->base_amount != $row->amount) {
						echo "<div><small>(" . $original_amount . ")</small></div>";
					}
					echo "</td>";
				} else {
					echo "<td class='text-right'>0.00</td>";
				}
				
				echo "<td class='text-right'>";
				echo "<div><strong>" . $format_amount($running_balance, $base_currency_symbol, $base_currency_position) . "</strong></div>";
				if($running_balance_customer != $running_balance) {
					echo "<div><small>(" . $format_amount($running_balance_customer, $row->currency_symbol, $row->currency_position) . ")</small></div>";
				}
				echo "</td>";
				echo "<td class='text-center'>" . $row->currency_code . "</td>";
				echo "</tr>";
			}
		} else {
			echo "<tr><td colspan='9' class='text-center'>No Records Found</td></tr>";
		}

		// Summary row
		if($q1->num_rows() > 0) {
			$format_amount = function($amount, $symbol, $position) {
				$formatted = number_format($amount, 2);
				return $position == 'before' ? $symbol . $formatted : $formatted . $symbol;
			};
			
			// Calculate totals in base currency for consistency
			$tot_total_cost_base = 0;
			$tot_payment_base = 0;
			$running_balance_base = 0;
			
			// Recalculate totals in base currency
			foreach ($q1->result() as $row) {
				if($row->type == 'Sale') {
					$tot_total_cost_base += $row->base_amount;
					$running_balance_base += $row->base_amount;
				} else {
					$tot_payment_base += $row->base_amount;
					$running_balance_base -= $row->base_amount;
				}
			}
			
			echo "<tr style='background: #f8f9fa; font-weight: bold;'>";
			echo "<td colspan='4' class='text-right'>TOTAL</td>";
			echo "<td class='text-center'>" . format_qty($tot_qty) . "</td>";
			echo "<td class='text-right'>";
			echo "<div><strong>" . $format_amount($tot_total_cost_base, $base_currency_symbol, $base_currency_position) . "</strong></div>";
			echo "</td>";
			echo "<td class='text-right'>";
			echo "<div><strong>" . $format_amount($tot_payment_base, $base_currency_symbol, $base_currency_position) . "</strong></div>";
			echo "</td>";
			echo "<td class='text-right'>";
			echo "<div><strong>" . $format_amount($running_balance_base, $base_currency_symbol, $base_currency_position) . "</strong></div>";
			echo "</td>";
			echo "<td class='text-center'>" . $base_currency_code . "</td>";
			echo "</tr>";
		}
	}

	public function show_stock_transfer_report(){
		extract($_POST);

		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		$item_id = isset($item_id) ? $item_id : "";

		$this->db->where("a.warehouse_from",$from_warehouse);
		$this->db->where("a.warehouse_to",$to_warehouse);
		
		$this->db->select("a.id,a.transfer_date,a.created_by,a.store_id,e.category_name,f.brand_name");
		$this->db->select("c.transfer_qty,d.item_name");
		$this->db->select("w1.warehouse_name as from_warehouse");
		$this->db->select("w2.warehouse_name as to_warehouse");
	    
	    
		$this->db->from("db_stocktransfer as a");
		
		
		$this->db->where("(a.transfer_date>='$from_date' and a.transfer_date<='$to_date')");
		
		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}
		$this->db->order_by("a.`transfer_date`",'desc');

		$str = "" ; 


		if($item_id!=''){
			$str = " and c.item_id=$item_id"; 
		}
		$this->db->join("db_stocktransferitems as c","c.stocktransfer_id = a.id $str","left");

		
		$this->db->join("db_items as d","d.`id`= c.`item_id`","left");

		$str = "" ; 
		if($category_id!=''){
			$str = " and e.id=$category_id"; 
		}

		$this->db->join("db_category as e","e.`id`= d.`category_id` $str","left");
			
		$str ="";

		if($brand_id!=''){
			$str = " and f.id=$brand_id"; 
		}

		$this->db->join("db_brands as f","f.`id`= d.`brand_id` $str","left");

		$this->db->join("db_warehouse as w1","w1.`id`= c.`warehouse_from`","left");
		$this->db->join("db_warehouse as w2","w2.`id`= c.`warehouse_to`","left");


		
		//echo $this->db->get_compiled_select();exit();
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			
			$tot_transfer_qty=0;
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				
				echo "<td>".show_date($res1->transfer_date)."</td>";
				echo "<td>".$res1->from_warehouse."</td>";
				echo "<td>".$res1->to_warehouse."</td>";
				echo "<td>".$res1->item_name."</td>";
				echo "<td>".$res1->category_name."</td>";
				echo "<td>".$res1->brand_name."</td>";
				echo "<td>".format_qty($res1->transfer_qty)."</td>";
				
				echo "</tr>";
				$tot_transfer_qty+=$res1->transfer_qty;
				
			}

			$total_columns_count=7;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			

			echo "<tr>
					  <td class='text-right text-bold' colspan='$total_columns_count'><b>Total :</b></td>
					  <td class='text-left text-bold'>".format_qty($tot_transfer_qty)."</td>
				  </tr>";
		}
		else{
			$total_columns_count=9;
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}


	public function show_sales_summary_report(){
		extract($_POST);

		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
		
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);

		$item_id = isset($item_id) ? $item_id : "";
		$item_type = isset($item_type) ? $item_type : "";

		if(warehouse_module() && warehouse_count()>0 && !empty($warehouse_id)){
			$this->db->where("a.warehouse_id",$warehouse_id);
		}
		
		// Enhanced query with multi-currency support
		$this->db->select("a.id,a.store_id,e.category_name");
		$this->db->select("sum(c.sales_qty) as sales_qty,d.item_name");
		$this->db->select("COALESCE(SUM(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN c.total_cost / a.exchange_rate ELSE c.total_cost END), 0) as total_sales_base");
		$this->db->select("COALESCE(SUM(CASE WHEN a.transaction_currency_id IS NOT NULL AND a.transaction_currency_id != 1 AND a.exchange_rate IS NOT NULL THEN (c.sales_qty * c.price_per_unit) / a.exchange_rate ELSE (c.sales_qty * c.price_per_unit) END), 0) as total_revenue_base");
		$this->db->select("SUM(c.total_cost) as total_sales_original");
		$this->db->select("SUM(c.sales_qty * c.price_per_unit) as total_revenue_original");
		$this->db->select("a.transaction_currency_id, cur.currency_code, cur.symbol, cur.currency_position");
	    
		$this->db->from("db_sales as a");
		
		$this->db->where("a.`sales_status`= 'Final'");
		$this->db->where("(a.sales_date>='$from_date' and a.sales_date<='$to_date')");

		if(!empty($store_id)){
			$this->db->where("a.store_id",$store_id);
		}

		$this->db->group_by("c.`item_id`");

		$str = "" ; 
		if($item_id!=''){
			$str = " and c.item_id=$item_id"; 
		}
		$this->db->join("db_salesitems as c","c.sales_id = a.id $str","left");

		$this->db->join("db_items as d","d.`id`= c.`item_id`","left");

		if(!empty($item_type)){
			$this->db->where("service_bit", (($item_type=="Items") ? 0 : 1) );
		}

		$str = "" ; 
		if($category_id!=''){
			$str = " and e.id=$category_id"; 
		}

		$this->db->join("db_category as e","e.`id`= d.`category_id` $str","right");
		$this->db->join("db_currency cur", "cur.id = a.transaction_currency_id", "left");
		
		$q1=$this->db->get();
		if($q1->num_rows()>0){
			$i=0;
			$tot_sales_qty=0;
			$tot_sales_base=0;
			$tot_revenue_base=0;
			
			foreach ($q1->result() as $res1) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($res1->store_id)."</td>";	
				}
				
				echo "<td>".$res1->item_name."</td>";
				echo "<td>".$res1->category_name."</td>";
				echo "<td class='text-right'>".format_qty($res1->sales_qty)."</td>";
				// Format total sales with currency display
				$total_sales_display = $this->_format_currency_with_base($res1->total_sales_original, $res1->transaction_currency_id, $res1->total_sales_base, get_base_currency_id());
				echo "<td class='text-right'>".$total_sales_display."</td>";
				
				// Format total revenue with currency display
				$total_revenue_display = $this->_format_currency_with_base($res1->total_revenue_original, $res1->transaction_currency_id, $res1->total_revenue_base, get_base_currency_id());
				echo "<td class='text-right'>".$total_revenue_display."</td>";
				
				
				echo "</tr>";
				$tot_sales_qty+=$res1->sales_qty;
				$tot_sales_base+=$res1->total_sales_base;
				$tot_revenue_base+=$res1->total_revenue_base;
			}

			echo "<tr class='bg-primary'>
					  <td class='text-right text-bold'><b>Total :</b></td>";
			if(store_module() && is_admin()){
				echo "<td class='text-right text-bold'>-</td>"; // Store Name
			}
			echo "<td class='text-right text-bold'>-</td>"; // Item Name
			echo "<td class='text-right text-bold'>-</td>"; // Category
			echo "<td class='text-right text-bold'>".format_qty($tot_sales_qty)."</td>"; // Quantity
			echo "<td class='text-right text-bold'>".store_number_format($tot_sales_base)." ".$base_currency_symbol."</td>"; // Total Sales
			echo "<td class='text-right text-bold'>".store_number_format($tot_revenue_base)." ".$base_currency_symbol."</td>"; // Total Revenue
			echo "</tr>";
		}
		else{
			$total_columns_count=7; // All columns: #, Store Name (if admin), Item Name, Category, Quantity, Total Sales, Total Revenue
			if(store_module() && is_admin()){
				$total_columns_count ++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Records Found</td>";
			echo "</tr>";
		}
		
	    exit;
	}

	// Customer Statement Report
public function get_customer_statement()
{
    $customer_id = $this->input->post('customer_id');
    $from_date   = $this->input->post('from_date');
    $to_date     = $this->input->post('to_date');
    $store_id    = $this->input->post('store_id');

    if (empty($customer_id)) {
        return ['error' => true, 'message' => 'Customer ID is required'];
    }

    // Customer
    $customer = $this->db->where('id', $customer_id)->get('db_customers')->row();
    if (!$customer) {
        return ['error' => true, 'message' => 'Customer not found'];
    }

    /*
    |--------------------------------------------------------------------------
    | CURRENCY (DEFINE FIRST - FIXED)
    |--------------------------------------------------------------------------
    */
    $base_currency = get_base_currency($store_id);
    $base_currency_code     = $base_currency->currency_code ?? 'KES';
    $base_currency_symbol   = $base_currency->currency_symbol ?? 'Ksh';
    $base_currency_position = $base_currency->currency_position ?? 'before';

    /*
    |--------------------------------------------------------------------------
    | OPENING BALANCE (FULLY FIXED)
    |--------------------------------------------------------------------------
    */

    $opening_balance = (float)($customer->opening_balance ?? 0);

    // Sales before period
    $opening_sales = $this->db->select('COALESCE(SUM(grand_total),0) as total')
        ->from('db_sales')
        ->where('customer_id', $customer_id)
        ->where('sales_date <', $from_date)
        ->where($store_id ? ['store_id' => $store_id] : null)
        ->get()->row()->total;

    // Payments before period (FIXED with JOIN)
    $this->db->select('COALESCE(SUM(p.payment),0) as total');
    $this->db->from('db_salespayments p');
    $this->db->join('db_sales s', 'p.sales_id = s.id', 'left');

    $this->db->group_start();
    $this->db->where('p.customer_id', $customer_id);
    $this->db->or_where('s.customer_id', $customer_id);
    $this->db->group_end();

    $this->db->where('p.payment_date <', $from_date);
    if ($store_id) $this->db->where('p.store_id', $store_id);

    $opening_payments = $this->db->get()->row()->total;

    // Sales returns before period (IMPORTANT)
    $opening_returns = $this->db->select('COALESCE(SUM(grand_total),0) as total')
        ->from('db_salesreturn')
        ->where('customer_id', $customer_id)
        ->where('return_date <', $from_date)
        ->where($store_id ? ['store_id' => $store_id] : null)
        ->get()->row()->total;

    $opening_balance = $opening_balance
        + (float)$opening_sales
        - (float)$opening_payments
        - (float)$opening_returns;

    /*
    |--------------------------------------------------------------------------
    | TRANSACTIONS (UNION LEDGER)
    |--------------------------------------------------------------------------
    */

    $sql = "
        SELECT 
            sales_date as date,
            'Sale' as type,
            sales_code as reference,
            CONCAT('Sale - ', sales_code) as description,
            grand_total as debit,
            0 as credit,
            COALESCE(transaction_currency_id,1) as currency_id,
            COALESCE(c.currency_code, ?) as currency_code,
            COALESCE(c.symbol, ?) as currency_symbol,
            COALESCE(c.currency_position, ?) as currency_position
        FROM db_sales s
        LEFT JOIN db_currency c ON s.transaction_currency_id = c.id
        WHERE s.customer_id = ?
        AND s.sales_date BETWEEN ? AND ?
        " . ($store_id ? " AND s.store_id = ?" : "") . "

        UNION ALL

        SELECT 
            p.payment_date as date,
            'Payment' as type,
            p.payment_code as reference,
            CONCAT(
                'Payment - ', p.payment_code,
                CASE 
                    WHEN p.sales_id IS NOT NULL 
                    THEN CONCAT(' (Inv: ', s.sales_code, ')')
                    ELSE ' (Opening Bal Payment)'
                END
            ) as description,
            0 as debit,
            p.payment as credit,
            COALESCE(p.payment_currency_id,1) as currency_id,
            COALESCE(c.currency_code, ?) as currency_code,
            COALESCE(c.symbol, ?) as currency_symbol,
            COALESCE(c.currency_position, ?) as currency_position
        FROM db_salespayments p
        LEFT JOIN db_currency c ON p.payment_currency_id = c.id
        LEFT JOIN db_sales s ON p.sales_id = s.id
        WHERE 
        (
            p.customer_id = ?
            OR s.customer_id = ?
        )
        AND p.payment_date BETWEEN ? AND ?
        " . ($store_id ? " AND p.store_id = ?" : "") . "

        UNION ALL

        SELECT 
            return_date as date,
            'Return' as type,
            return_code as reference,
            CONCAT('Sales Return - ', return_code) as description,
            0 as debit,
            grand_total as credit,
            1 as currency_id,
            ? as currency_code,
            ? as currency_symbol,
            ? as currency_position
        FROM db_salesreturn r
        WHERE r.customer_id = ?
        AND r.return_date BETWEEN ? AND ?
        " . ($store_id ? " AND r.store_id = ?" : "") . "

        ORDER BY date ASC
    ";

    /*
    |--------------------------------------------------------------------------
    | PARAMS
    |--------------------------------------------------------------------------
    */

    $params = [];

    // Sales
    $params = array_merge($params, [
        $base_currency_code, $base_currency_symbol, $base_currency_position,
        $customer_id, $from_date, $to_date
    ]);
    if ($store_id) $params[] = $store_id;

    // Payments
    $params = array_merge($params, [
        $base_currency_code, $base_currency_symbol, $base_currency_position,
        $customer_id, $customer_id, $from_date, $to_date
    ]);
    if ($store_id) $params[] = $store_id;

    // Returns
    $params = array_merge($params, [
        $base_currency_code, $base_currency_symbol, $base_currency_position,
        $customer_id, $from_date, $to_date
    ]);
    if ($store_id) $params[] = $store_id;

    $all_transactions = $this->db->query($sql, $params)->result();

    /*
    |--------------------------------------------------------------------------
    | RUNNING BALANCE
    |--------------------------------------------------------------------------
    */

    $transactions = [];

    // Opening row
    $transactions[] = [
        'date' => date('M d, Y', strtotime($from_date)),
        'type' => 'Opening Balance',
        'reference' => '-',
        'description' => 'Opening Balance',
        'debit' => 0,
        'credit' => 0,
        'balance' => $opening_balance,
        'currency_id' => 1,
        'currency_code' => $base_currency_code,
        'currency_symbol' => $base_currency_symbol,
        'currency_position' => $base_currency_position
    ];

    $running_balance = $opening_balance;

    foreach ($all_transactions as $t) {
        $running_balance += ((float)$t->debit - (float)$t->credit);

        $transactions[] = [
            'date'        => date('M d, Y', strtotime($t->date)),
            'type'        => $t->type,
            'reference'   => $t->reference,
            'description' => $t->description,
            'debit'       => $t->debit,
            'credit'      => $t->credit,
            'balance'     => $running_balance,
            'currency_id' => $t->currency_id,
            'currency_code' => $t->currency_code,
            'currency_symbol' => $t->currency_symbol,
            'currency_position' => $t->currency_position
        ];
    }

    /*
    |--------------------------------------------------------------------------
    | TOTALS
    |--------------------------------------------------------------------------
    */

    $total_sales = $this->db->select('COALESCE(SUM(grand_total),0) as total')
        ->from('db_sales')
        ->where('customer_id', $customer_id)
        ->where('sales_date >=', $from_date)
        ->where('sales_date <=', $to_date)
        ->get()->row()->total;

    // Payments FIXED
    $this->db->select('COALESCE(SUM(p.payment),0) as total');
    $this->db->from('db_salespayments p');
    $this->db->join('db_sales s', 'p.sales_id = s.id', 'left');

    $this->db->group_start();
    $this->db->where('p.customer_id', $customer_id);
    $this->db->or_where('s.customer_id', $customer_id);
    $this->db->group_end();

    $this->db->where('p.payment_date >=', $from_date);
    $this->db->where('p.payment_date <=', $to_date);

    $total_payments = $this->db->get()->row()->total;

    $total_returns = $this->db->select('COALESCE(SUM(grand_total),0) as total')
        ->from('db_salesreturn')
        ->where('customer_id', $customer_id)
        ->where('return_date >=', $from_date)
        ->where('return_date <=', $to_date)
        ->get()->row()->total;

    $closing_balance = $opening_balance + $total_sales - $total_payments - $total_returns;

    return [
        'error' => false,
        'customer' => $customer,
        'transactions' => $transactions,
        'summary' => [
            'opening_balance' => $opening_balance,
            'total_sales' => $total_sales,
            'total_payments' => $total_payments,
            'closing_balance' => $closing_balance
        ]
    ];
}

// Supplier Statement Report
public function get_supplier_statement()
{
    $supplier_id = $this->input->post('supplier_id');
    $from_date   = $this->input->post('from_date');
    $to_date     = $this->input->post('to_date');
    $store_id    = $this->input->post('store_id');

    if (empty($supplier_id)) {
        return ['error' => true, 'message' => 'Supplier ID is required'];
    }

    // Supplier
    $supplier = $this->db->where('id', $supplier_id)->get('db_suppliers')->row();
    if (!$supplier) {
        return ['error' => true, 'message' => 'Supplier not found'];
    }

    /*
    |--------------------------------------------------------------------------
    | OPENING BALANCE
    |--------------------------------------------------------------------------
    */

    $opening_balance = (float)($supplier->opening_balance ?? 0);

    // Purchases before period
    $opening_purchases = $this->db->select('COALESCE(SUM(grand_total),0) as total')
        ->from('db_purchase')
        ->where('supplier_id', $supplier_id)
        ->where('purchase_date <', $from_date)
        ->where($store_id ? ['store_id' => $store_id] : null)
        ->get()->row()->total;

    // Payments before period (FIXED)
    $this->db->select('COALESCE(SUM(p.payment),0) as total');
    $this->db->from('db_purchasepayments p');
    $this->db->join('db_purchase pu', 'p.purchase_id = pu.id', 'left');

    $this->db->group_start();
    $this->db->where('p.supplier_id', $supplier_id);
    $this->db->or_where('pu.supplier_id', $supplier_id);
    $this->db->group_end();

    $this->db->where('p.payment_date <', $from_date);
    if ($store_id) $this->db->where('p.store_id', $store_id);

    $opening_payments = $this->db->get()->row()->total;

    // Returns before period
    $opening_returns = $this->db->select('COALESCE(SUM(grand_total),0) as total')
        ->from('db_purchasereturn')
        ->where('supplier_id', $supplier_id)
        ->where('return_date <', $from_date)
        ->where($store_id ? ['store_id' => $store_id] : null)
        ->get()->row()->total;

    $opening_balance = $opening_balance
        + (float)$opening_purchases
        - (float)$opening_payments
        - (float)$opening_returns;

    /*
    |--------------------------------------------------------------------------
    | CURRENCY
    |--------------------------------------------------------------------------
    */
    $base_currency = get_base_currency($store_id);
    $base_currency_code     = $base_currency->currency_code ?? 'KES';
    $base_currency_symbol   = $base_currency->currency_symbol ?? 'Ksh';
    $base_currency_position = $base_currency->currency_position ?? 'before';

    /*
    |--------------------------------------------------------------------------
    | TRANSACTIONS (UNION LEDGER)
    |--------------------------------------------------------------------------
    */

    $sql = "
        SELECT 
            purchase_date as date,
            'Purchase' as type,
            purchase_code as reference,
            CONCAT('Purchase - ', purchase_code) as description,
            grand_total as debit,
            0 as credit,
            COALESCE(transaction_currency_id,1) as currency_id,
            COALESCE(c.currency_code, ?) as currency_code,
            COALESCE(c.symbol, ?) as currency_symbol,
            COALESCE(c.currency_position, ?) as currency_position
        FROM db_purchase p
        LEFT JOIN db_currency c ON p.transaction_currency_id = c.id
        WHERE p.supplier_id = ?
        AND p.purchase_date BETWEEN ? AND ?
        " . ($store_id ? " AND p.store_id = ?" : "") . "

        UNION ALL

        SELECT 
            p.payment_date as date,
            'Payment' as type,
            p.payment_code as reference,
            CONCAT(
                'Payment - ', p.payment_code,
                CASE 
                    WHEN p.purchase_id IS NOT NULL 
                    THEN CONCAT(' (Inv: ', pu.purchase_code, ')')
                    ELSE ' (Opening Bal Payment)'
                END
            ) as description,
            0 as debit,
            p.payment as credit,
            COALESCE(p.payment_currency_id,1) as currency_id,
            COALESCE(c.currency_code, ?) as currency_code,
            COALESCE(c.symbol, ?) as currency_symbol,
            COALESCE(c.currency_position, ?) as currency_position
        FROM db_purchasepayments p
        LEFT JOIN db_currency c ON p.payment_currency_id = c.id
        LEFT JOIN db_purchase pu ON p.purchase_id = pu.id
        WHERE 
        (
            p.supplier_id = ?
            OR pu.supplier_id = ?
        )
        AND p.payment_date BETWEEN ? AND ?
        " . ($store_id ? " AND p.store_id = ?" : "") . "

        UNION ALL

        SELECT 
            return_date as date,
            'Return' as type,
            return_code as reference,
            CONCAT('Purchase Return - ', return_code) as description,
            0 as debit,
            grand_total as credit,
            1 as currency_id,
            ? as currency_code,
            ? as currency_symbol,
            ? as currency_position
        FROM db_purchasereturn r
        WHERE r.supplier_id = ?
        AND r.return_date BETWEEN ? AND ?
        " . ($store_id ? " AND r.store_id = ?" : "") . "

        ORDER BY date ASC
    ";

    /*
    |--------------------------------------------------------------------------
    | PARAMS
    |--------------------------------------------------------------------------
    */

    $params = [];

    // Purchases
    $params = array_merge($params, [
        $base_currency_code, $base_currency_symbol, $base_currency_position,
        $supplier_id, $from_date, $to_date
    ]);
    if ($store_id) $params[] = $store_id;

    // Payments
    $params = array_merge($params, [
        $base_currency_code, $base_currency_symbol, $base_currency_position,
        $supplier_id, $supplier_id, $from_date, $to_date
    ]);
    if ($store_id) $params[] = $store_id;

    // Returns
    $params = array_merge($params, [
        $base_currency_code, $base_currency_symbol, $base_currency_position,
        $supplier_id, $from_date, $to_date
    ]);
    if ($store_id) $params[] = $store_id;

    $all_transactions = $this->db->query($sql, $params)->result();

    /*
    |--------------------------------------------------------------------------
    | RUNNING BALANCE
    |--------------------------------------------------------------------------
    */

    $transactions = [];

    // ✅ Opening Balance Row
    $transactions[] = [
        'date' => date('M d, Y', strtotime($from_date)),
        'type' => 'Opening Balance',
        'reference' => '-',
        'description' => 'Opening Balance (Before ' . date('M d, Y', strtotime($from_date)) . ')',
        'debit' => 0,
        'credit' => 0,
        'balance' => $opening_balance,
        'currency_id' => 1,
        'currency_code' => $base_currency_code,
        'currency_symbol' => $base_currency_symbol,
        'currency_position' => $base_currency_position
    ];

    $running_balance = $opening_balance;

    foreach ($all_transactions as $t) {
        $running_balance += ((float)$t->debit - (float)$t->credit);

        $transactions[] = [
            'date'        => date('M d, Y', strtotime($t->date)),
            'type'        => $t->type,
            'reference'   => $t->reference,
            'description' => $t->description,
            'debit'       => $t->debit,
            'credit'      => $t->credit,
            'balance'     => $running_balance,
            'currency_id' => $t->currency_id,
            'currency_code' => $t->currency_code,
            'currency_symbol' => $t->currency_symbol,
            'currency_position' => $t->currency_position
        ];
    }

    /*
    |--------------------------------------------------------------------------
    | TOTALS
    |--------------------------------------------------------------------------
    */

    $total_purchases = $this->db->select('COALESCE(SUM(grand_total),0) as total')
        ->from('db_purchase')
        ->where('supplier_id', $supplier_id)
        ->where('purchase_date >=', $from_date)
        ->where('purchase_date <=', $to_date)
        ->get()->row()->total;

    // Payments (FIXED)
    $this->db->select('COALESCE(SUM(p.payment),0) as total');
    $this->db->from('db_purchasepayments p');
    $this->db->join('db_purchase pu', 'p.purchase_id = pu.id', 'left');

    $this->db->group_start();
    $this->db->where('p.supplier_id', $supplier_id);
    $this->db->or_where('pu.supplier_id', $supplier_id);
    $this->db->group_end();

    $this->db->where('p.payment_date >=', $from_date);
    $this->db->where('p.payment_date <=', $to_date);

    $total_payments = $this->db->get()->row()->total;

    $total_returns = $this->db->select('COALESCE(SUM(grand_total),0) as total')
        ->from('db_purchasereturn')
        ->where('supplier_id', $supplier_id)
        ->where('return_date >=', $from_date)
        ->where('return_date <=', $to_date)
        ->get()->row()->total;

    $closing_balance = $opening_balance + $total_purchases - $total_payments - $total_returns;

    return [
        'error' => false,
        'supplier' => $supplier,
        'transactions' => $transactions,
        'summary' => [
            'opening_balance' => $opening_balance,
            'total_purchases' => $total_purchases,
            'total_payments'  => $total_payments,
            'closing_balance' => $closing_balance
        ]
    ];
}
	// Stock Aging Report
	public function get_stock_aging_report() {
		extract($_POST);
		
		// Load helper
		$this->load->helper('multi_currency_helper');
		
		try {
			// Get base currency info
			$base_currency = get_base_currency($store_id);
			$base_currency_symbol = $base_currency ? $base_currency->symbol : 'USh';
			$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
			
			if(empty($store_id)) {
				$store_id = get_current_store_id();
			}

			if(!empty($store_id)){
				$this->db->where("a.store_id",$store_id);
			}
			if(!is_admin()){
				$this->db->where("a.store_id",get_current_store_id());
			}
			
			$this->db->select("a.sales_price,a.item_code,a.price,a.purchase_price,a.item_name,a.tax_type,a.store_id,a.id as item_id,a.item_group,
				d.category_name,
				c.brand_name,
				");
			$this->db->from("db_items as a");
			$this->db->join("db_brands as c","c.id=a.brand_id","left");
			$this->db->join("db_category as d","d.id=a.category_id","left");
			$this->db->where("a.service_bit=0");

			if(!empty($brand_id)){
				$this->db->where("a.brand_id",$brand_id);
			}
			if(!empty($category_id)){
				$this->db->where("a.category_id",$category_id);
			}

			$q1=$this->db->get();
			$str='';

			if($q1->num_rows()>0){
				$i=0;
				foreach ($q1->result() as $res1) {
					if($res1->item_group=='Variants'){continue;}

					$available_qty_wh = $this->get_available_qty($warehouse_id,$res1->store_id,$res1->item_id);
					
					if($available_qty_wh <= 0) continue; // Skip items with no stock

					// Calculate days in stock (simplified - using item creation date)
					$days_in_stock = $this->calculate_days_in_stock($res1->item_id, $from_date, $to_date);
					$age_category = $this->get_age_category($days_in_stock);
					
					$stock_value = $available_qty_wh * $res1->sales_price;
					
					$str .= "<tr>";
					$str .= "<td>".++$i."</td>";
					if(store_module() && is_admin()){
						$str .= "<td>".$this->get_store_name($res1->store_id)."</td>";	
					}
					$str .= "<td>".$res1->item_code."</td>";
					$str .= "<td>".$res1->item_name."</td>";
					$str .= "<td>".$res1->brand_name."</td>";
					$str .= "<td>".$res1->category_name."</td>";
					$str .= "<td class='text-center'>".$this->format_qty($available_qty_wh)."</td>";
					$str .= "<td class='text-center'>".$days_in_stock."</td>";
					$str .= "<td class='text-center'><span class='label label-".$this->get_age_label_class($age_category)."'>".$age_category."</span></td>";
					$str .= "<td class='text-right'>".$this->format_currency($stock_value, $base_currency_symbol, $base_currency_position)."</td>";
					$str .= "</tr>";
				}
			}
			
			return $str;
		} catch (Exception $e) {
			log_message('error', 'Stock Aging Report Error: ' . $e->getMessage());
			return "<tr><td colspan='10' class='text-center text-danger'>Error loading stock aging report</td></tr>";
		}
	}

	// Most Moving Stock Report
	public function get_most_moving_report() {
		extract($_POST);
		
		// Load helper
		$this->load->helper('multi_currency_helper');
		
		try {
			// Get base currency info
			$base_currency = get_base_currency($store_id);
			$base_currency_symbol = $base_currency ? $base_currency->symbol : 'USh';
			$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
			
			if(empty($store_id)) {
				$store_id = get_current_store_id();
			}

			// Date filters
			$date_where = "";
			if(!empty($from_date) && !empty($to_date)) {
				$from_date = system_fromatted_date($from_date);
				$to_date = system_fromatted_date($to_date);
				$date_where = "AND s.sales_date BETWEEN '$from_date' AND '$to_date'";
			}

			$str = '';
			$i = 0;

			// Query to get most moving items
			$query = "SELECT 
				a.item_code, a.item_name, a.sales_price, a.purchase_price,
				c.brand_name, d.category_name, a.store_id,
				COALESCE(SUM(si.sales_qty), 0) as quantity_sold,
				COALESCE(SUM(si.sales_qty * a.sales_price), 0) as sales_value,
				COALESCE(SUM(si.sales_qty), 0) / GREATEST(DATEDIFF(CURDATE(), MIN(s.sales_date)), 1) as movement_rate
			FROM db_items a
			LEFT JOIN db_salesitems si ON a.id = si.item_id
			LEFT JOIN db_sales s ON si.sales_id = s.id AND s.sales_status = 'Final'
			LEFT JOIN db_brands c ON c.id = a.brand_id
			LEFT JOIN db_category d ON d.id = a.category_id
			WHERE a.service_bit = 0 AND a.store_id = '$store_id' $date_where
			GROUP BY a.id, a.item_code, a.item_name, a.sales_price, a.purchase_price, c.brand_name, d.category_name, a.store_id
			HAVING quantity_sold > 0
			ORDER BY quantity_sold DESC
			LIMIT 50";

			$result = $this->db->query($query);
			
			if($result->num_rows() > 0) {
				foreach($result->result() as $row) {
					$available_qty = $this->get_available_qty($warehouse_id, $row->store_id, $row->item_id);
					$days_to_sell_out = $available_qty > 0 ? round($available_qty / max($row->movement_rate, 0.01)) : 0;
					
					$str .= "<tr>";
					$str .= "<td>".++$i."</td>";
					if(store_module() && is_admin()){
						$str .= "<td>".$this->get_store_name($row->store_id)."</td>";	
					}
					$str .= "<td>".$row->item_code."</td>";
					$str .= "<td>".$row->item_name."</td>";
					$str .= "<td>".$row->brand_name."</td>";
					$str .= "<td>".$row->category_name."</td>";
					$str .= "<td class='text-center'>".$this->format_qty($row->quantity_sold)."</td>";
					$str .= "<td class='text-right'>".$this->format_currency($row->sales_value, $base_currency_symbol, $base_currency_position)."</td>";
					$str .= "<td class='text-center'>".number_format($row->movement_rate, 2)."</td>";
					$str .= "<td class='text-center'>".$days_to_sell_out."</td>";
					$str .= "</tr>";
				}
			}
			
			return $str;
		} catch (Exception $e) {
			log_message('error', 'Most Moving Report Error: ' . $e->getMessage());
			return "<tr><td colspan='10' class='text-center text-danger'>Error loading most moving report</td></tr>";
		}
	}

	// Less Moving Stock Report
	public function get_less_moving_report() {
		extract($_POST);
		
		// Load helper
		$this->load->helper('multi_currency_helper');
		
		try {
			// Get base currency info
			$base_currency = get_base_currency($store_id);
			$base_currency_symbol = $base_currency ? $base_currency->symbol : 'USh';
			$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
			
			if(empty($store_id)) {
				$store_id = get_current_store_id();
			}

			$str = '';
			$i = 0;

			// Query to get less moving items
			$query = "SELECT 
				a.item_code, a.item_name, a.sales_price, a.purchase_price,
				c.brand_name, d.category_name, a.store_id,
				COALESCE(MAX(s.sales_date), '1900-01-01') as last_sale_date,
				DATEDIFF(CURDATE(), COALESCE(MAX(s.sales_date), '1900-01-01')) as days_since_last_sale
			FROM db_items a
			LEFT JOIN db_salesitems si ON a.id = si.item_id
			LEFT JOIN db_sales s ON si.sales_id = s.id AND s.sales_status = 'Final'
			LEFT JOIN db_brands c ON c.id = a.brand_id
			LEFT JOIN db_category d ON d.id = a.category_id
			WHERE a.service_bit = 0 AND a.store_id = '$store_id'
			GROUP BY a.id, a.item_code, a.item_name, a.sales_price, a.purchase_price, c.brand_name, d.category_name, a.store_id
			HAVING days_since_last_sale > 30 OR last_sale_date = '1900-01-01'
			ORDER BY days_since_last_sale DESC
			LIMIT 50";

			$result = $this->db->query($query);
			
			if($result->num_rows() > 0) {
				foreach($result->result() as $row) {
					$available_qty = $this->get_available_qty($warehouse_id, $row->store_id, $row->item_id);
					$stock_value = $available_qty * $row->sales_price;
					$last_sale_display = $row->last_sale_date == '1900-01-01' ? 'Never' : date('Y-m-d', strtotime($row->last_sale_date));
					
					$str .= "<tr>";
					$str .= "<td>".++$i."</td>";
					if(store_module() && is_admin()){
						$str .= "<td>".$this->get_store_name($row->store_id)."</td>";	
					}
					$str .= "<td>".$row->item_code."</td>";
					$str .= "<td>".$row->item_name."</td>";
					$str .= "<td>".$row->brand_name."</td>";
					$str .= "<td>".$row->category_name."</td>";
					$str .= "<td class='text-center'>".$this->format_qty($available_qty)."</td>";
					$str .= "<td class='text-center'>".$last_sale_display."</td>";
					$str .= "<td class='text-center'>".$row->days_since_last_sale."</td>";
					$str .= "<td class='text-right'>".$this->format_currency($stock_value, $base_currency_symbol, $base_currency_position)."</td>";
					$str .= "</tr>";
				}
			}
			
			return $str;
		} catch (Exception $e) {
			log_message('error', 'Less Moving Report Error: ' . $e->getMessage());
			return "<tr><td colspan='10' class='text-center text-danger'>Error loading less moving report</td></tr>";
		}
	}

	// Helper methods for stock aging
	private function calculate_days_in_stock($item_id, $from_date, $to_date) {
		// Simplified calculation - in real implementation, you'd track actual stock movements
		$query = "SELECT DATEDIFF(CURDATE(), MIN(s.sales_date)) as days
				  FROM db_salesitems si 
				  JOIN db_sales s ON si.sales_id = s.id 
				  WHERE si.item_id = '$item_id' AND s.sales_status = 'Final'";
		$result = $this->db->query($query);
		return $result->num_rows() > 0 ? max($result->row()->days, 0) : 0;
	}

	private function get_age_category($days) {
		if($days <= 30) return 'Fresh';
		if($days <= 60) return '30-60 Days';
		if($days <= 90) return '60-90 Days';
		return '90+ Days';
	}

	private function get_age_label_class($category) {
		switch($category) {
			case 'Fresh': return 'success';
			case '30-60 Days': return 'warning';
			case '60-90 Days': return 'info';
			default: return 'danger';
		}
	}

	// Cash Flow Statement Report
	public function get_cash_flow_statement() {
		try {
			$from_date = $this->input->post('from_date');
			$to_date = $this->input->post('to_date');
			$store_id = $this->input->post('store_id');
		
		// Convert dates
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);
		
		// Load helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_code = $base_currency ? $base_currency->currency_code : 'UGX';
		$base_currency_symbol = $base_currency ? $base_currency->symbol : 'USh';
		$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
		
		// Format currency function
		$format_amount = function($amount, $symbol, $position) {
			$formatted = number_format($amount, 2);
			return $position == 'before' ? $symbol . $formatted : $formatted . $symbol;
		};
		
		$cash_flow = array();
		
		// OPERATING ACTIVITIES
		$operating = array();
		
		// Sales Revenue
		$this->db->select('COALESCE(SUM(grand_total), 0) as total_sales');
		$this->db->from('db_sales');
		$this->db->where('sales_date >=', $from_date);
		$this->db->where('sales_date <=', $to_date);
		if($store_id) $this->db->where('store_id', $store_id);
		$sales_revenue = $this->db->get()->row()->total_sales;
		
		// Cash Sales: case-insensitive payment_type; period by payment_date or sales_date; store from sale if payment.store_id null
		$this->db->select('COALESCE(SUM(sp.payment), 0) as cash_sales');
		$this->db->from('db_salespayments sp');
		$this->db->join('db_sales s', 's.id = sp.sales_id', 'inner');
		$this->db->where('(COALESCE(sp.payment_date, s.sales_date) >= ' . $this->db->escape($from_date) . ' AND COALESCE(sp.payment_date, s.sales_date) <= ' . $this->db->escape($to_date) . ')', null, false);
		$this->db->where('LOWER(TRIM(sp.payment_type))', 'cash');
		if ($store_id && (int)$store_id > 0) {
			$sid = (int) $store_id;
			$this->db->where('(COALESCE(sp.store_id, s.store_id) = ' . $sid . ')', null, false);
		}
		$cash_sales = $this->db->get()->row()->cash_sales;
		
		// Credit Sales
		$credit_sales = $sales_revenue - $cash_sales;
		
		// Purchase Payments
		$this->db->select('COALESCE(SUM(payment), 0) as purchase_payments');
		$this->db->from('db_purchasepayments');
		$this->db->where('payment_date >=', $from_date);
		$this->db->where('payment_date <=', $to_date);
		if($store_id) $this->db->where('store_id', $store_id);
		$purchase_payments = $this->db->get()->row()->purchase_payments;
		
		// Expense Payments
		$this->db->select('COALESCE(SUM(expense_amt), 0) as expense_payments');
		$this->db->from('db_expense');
		$this->db->where('expense_date >=', $from_date);
		$this->db->where('expense_date <=', $to_date);
		if($store_id) $this->db->where('store_id', $store_id);
		$expense_payments = $this->db->get()->row()->expense_payments;
		
		// Tax Payments
		$this->db->select('COALESCE(SUM(si.tax_amt), 0) as tax_payments');
		$this->db->from('db_salesitems si');
		$this->db->join('db_sales s', 's.id = si.sales_id', 'inner');
		$this->db->where('s.sales_date >=', $from_date);
		$this->db->where('s.sales_date <=', $to_date);
		$this->db->where('s.sales_status', 'Final');
		if($store_id) $this->db->where('s.store_id', $store_id);
		$tax_payments = $this->db->get()->row()->tax_payments;
		
		$cash_sales = floatval($cash_sales);
		$purchase_payments = floatval($purchase_payments);
		$expense_payments = floatval($expense_payments);
		$tax_payments = floatval($tax_payments);
		$operating = array(
			'Cash Sales' => $cash_sales,
			'Credit Sales' => floatval($sales_revenue) - $cash_sales,
			'Total Sales Revenue' => floatval($sales_revenue),
			'Purchase Payments' => -$purchase_payments,
			'Expense Payments' => -$expense_payments,
			'Tax Payments' => -$tax_payments,
			'Net Operating Cash Flow' => $cash_sales - $purchase_payments - $expense_payments - $tax_payments
		);
		
		// INVESTING ACTIVITIES
		$investing = array();
		
		// Asset Purchases (if you have asset management)
		$asset_purchases = 0;
		// Note: Asset management not implemented yet, so set to 0
		
		$investing = array(
			'Asset Purchases' => -$asset_purchases,
			'Net Investing Cash Flow' => -$asset_purchases
		);
		
		// FINANCING ACTIVITIES
		$financing = array();
		
		// Loan Receipts
		$loan_receipts = 0;
		$loan_payments = 0;
		// Check if db_loans table exists
		if($this->db->table_exists('db_loans')) {
			$this->db->select('COALESCE(SUM(amount), 0) as loan_receipts');
			$this->db->from('db_loans');
			$this->db->where('date >=', $from_date);
			$this->db->where('date <=', $to_date);
			$this->db->where('type', 'Receipt');
			if($store_id) $this->db->where('store_id', $store_id);
			$loan_receipts = $this->db->get()->row()->loan_receipts;
			
			// Loan Payments
			$this->db->select('COALESCE(SUM(amount), 0) as loan_payments');
			$this->db->from('db_loans');
			$this->db->where('date >=', $from_date);
			$this->db->where('date <=', $to_date);
			$this->db->where('type', 'Payment');
			if($store_id) $this->db->where('store_id', $store_id);
			$loan_payments = $this->db->get()->row()->loan_payments;
		}
		
		$financing = array(
			'Loan Receipts' => $loan_receipts,
			'Loan Payments' => -$loan_payments,
			'Net Financing Cash Flow' => $loan_receipts - $loan_payments
		);
		
		// Calculate Net Cash Flow
		$net_operating = $operating['Net Operating Cash Flow'];
		$net_investing = $investing['Net Investing Cash Flow'];
		$net_financing = $financing['Net Financing Cash Flow'];
		$net_cash_flow = $net_operating + $net_investing + $net_financing;
		
		// Get Opening Cash Balance from Cash Account
		$this->load->helper('cash_account_helper');
		$cash_account_id = get_cash_account_id($store_id);
		$opening_balance = 0; // Set to 0 for now since balance tracking isn't implemented
		
		// Log for debugging
		log_message('info', 'Cash Flow Statement - Store ID: ' . $store_id . ', Cash Account ID: ' . $cash_account_id . ', Opening Balance: ' . $opening_balance);
		
		// Calculate Closing Cash Balance
		$closing_balance = $opening_balance + $net_cash_flow;
		
		$cash_flow = array(
			'operating' => $operating,
			'investing' => $investing,
			'financing' => $financing,
			'summary' => array(
				'Net Cash Flow' => $net_cash_flow,
				'Opening Balance' => $opening_balance,
				'Closing Balance' => $closing_balance
			),
			'base_currency' => array(
				'code' => $base_currency_code,
				'symbol' => $base_currency_symbol,
				'position' => $base_currency_position
			)
		);
		
		return $cash_flow;
		} catch (Exception $e) {
			log_message('error', 'Cash Flow Statement Model Error: ' . $e->getMessage());
			return array(
				'error' => true,
				'message' => 'Error generating cash flow statement: ' . $e->getMessage(),
				'operating' => array(),
				'investing' => array(),
				'financing' => array(),
				'summary' => array(),
				'base_currency' => array('code' => 'UGX', 'symbol' => 'USh', 'position' => 'before')
			);
		}
	}

	// Low Stock Alert Report
	public function get_low_stock_alert_report() {
		try {
			extract($_POST);
			
			// Load helper
			$this->load->helper('multi_currency_helper');
			
			log_message('debug', 'Low Stock Alert Report - Starting method');
			log_message('debug', 'Low Stock Alert Report - POST data: ' . json_encode($_POST));
			
			// Get base currency info
			$base_currency = get_base_currency($store_id);
			$base_currency_code = $base_currency ? $base_currency->currency_code : 'UGX';
			$base_currency_symbol = $base_currency ? $base_currency->symbol : 'USh';
			$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
			
			// Set default store_id if empty
			if(empty($store_id)) {
				$store_id = get_current_store_id();
			}
			
			log_message('debug', 'Low Stock Alert Report - Store ID: ' . $store_id . ', Warehouse ID: ' . $warehouse_id);

			// Build query for items with low stock - match dashboard logic
			// Check both minimum_stock_level AND alert_qty (for backward compatibility)
			$this->db->select("a.id as item_id, a.item_code, a.item_name, a.sales_price, a.purchase_price, a.store_id");
			$this->db->select("a.alert_qty, a.minimum_stock_level, a.reorder_level");
			$this->db->select("d.category_name, c.brand_name");
			$this->db->from("db_items as a");
			$this->db->join("db_brands as c", "c.id = a.brand_id", "left");
			$this->db->join("db_category as d", "d.id = a.category_id", "left");
			$this->db->where("a.service_bit", 0);
			$this->db->where("a.status", 1);
			$this->db->where("(a.item_group IS NULL OR a.item_group != 'Variants')", null, false);
			
			// Apply filters
			if(!empty($store_id)) {
				$this->db->where("a.store_id", $store_id);
			}
			if(!is_admin()) {
				$this->db->where("a.store_id", get_current_store_id());
			}
			if(!empty($brand_id)) {
				$this->db->where("a.brand_id", $brand_id);
			}
			if(!empty($category_id)) {
				$this->db->where("a.category_id", $category_id);
			}
			// Only items that have at least one alert configured (same as dashboard)
			$this->db->where("(COALESCE(a.minimum_stock_level, 0) > 0 OR COALESCE(a.alert_qty, 0) > 0 OR COALESCE(a.reorder_level, 0) > 0)");
			$query = $this->db->get();
			log_message('debug', 'Low Stock Alert Report - Query executed. Rows: ' . $query->num_rows());
			log_message('debug', 'Low Stock Alert Report - Query: ' . $this->db->last_query());
			
			if($query->num_rows() > 0) {
				$i = 0;
				$str = '';
				$out_of_stock_count = 0;
				$critical_stock_count = 0;
				$low_stock_count = 0;
				$total_risk_value = 0;
				
				foreach($query->result() as $row) {
					// Threshold: minimum_stock_level, else alert_qty, else reorder_level (0 = none)
					$minimum_stock_level = 0;
					if(!empty($row->minimum_stock_level) && $row->minimum_stock_level > 0) {
						$minimum_stock_level = $row->minimum_stock_level;
					} elseif(!empty($row->alert_qty) && $row->alert_qty > 0) {
						$minimum_stock_level = $row->alert_qty;
					} elseif(!empty($row->reorder_level) && $row->reorder_level > 0) {
						$minimum_stock_level = $row->reorder_level;
					}
					
					// Current stock = total across ALL warehouses for store (match dashboard)
					$current_stock = 0;
					$this->db->select('COALESCE(SUM(available_qty), 0) as stock');
					$this->db->from('db_warehouseitems');
					$this->db->where('item_id', $row->item_id);
					$this->db->where('store_id', $store_id);
					$stock_q = $this->db->get();
					if($stock_q->num_rows() > 0) {
						$current_stock = (float)$stock_q->row()->stock;
					}
					if($current_stock == 0) {
						$this->db->select('COALESCE(stock, 0) as stock');
						$this->db->from('db_items');
						$this->db->where('id', $row->item_id);
						$this->db->where('store_id', $store_id);
						$fq = $this->db->get();
						if($fq->num_rows() > 0) {
							$current_stock = (float)$fq->row()->stock;
						}
					}
					
					// Show only items at or below alert level (negative, out of stock, critical, low). Skip OK.
					$is_at_alert = ($current_stock < 0) || ($minimum_stock_level > 0 && $current_stock <= $minimum_stock_level);
					if (!$is_at_alert) {
						continue;
					}
					
					// Calculate stock value
					$stock_value = $current_stock * $row->sales_price;
					$total_risk_value += $stock_value;
					
					// Calculate days to run out (simplified calculation)
					$days_to_run_out = 'N/A';
					if($current_stock > 0) {
						// This is a simplified calculation - in real scenario you'd need sales velocity
						$days_to_run_out = round($current_stock / max(1, $minimum_stock_level / 30)); // Assume 30 days for minimum stock
					}
					
					// Determine stock status (include negative as critical) - match dashboard
					$stock_status = '';
					$row_class = '';
					if($current_stock < 0) {
						$stock_status = '<span class="label label-danger"><i class="fa fa-exclamation-triangle"></i> Negative</span>';
						$row_class = 'danger';
						$critical_stock_count++;
					} elseif($current_stock == 0) {
						$stock_status = '<span class="label label-danger"><i class="fa fa-times"></i> Out of Stock</span>';
						$row_class = 'danger';
						$out_of_stock_count++;
					} elseif($minimum_stock_level > 0 && $current_stock < ($minimum_stock_level * 0.5)) {
						$stock_status = '<span class="label label-danger"><i class="fa fa-exclamation-triangle"></i> Critical</span>';
						$row_class = 'danger';
						$critical_stock_count++;
					} elseif($minimum_stock_level > 0 && $current_stock <= $minimum_stock_level) {
						$stock_status = '<span class="label label-warning"><i class="fa fa-warning"></i> Low</span>';
						$row_class = 'warning';
						$low_stock_count++;
					} else {
						continue;
					}
					
					// Calculate reorder quantity (suggest 2x minimum stock level when set)
					$suggested_reorder = $minimum_stock_level > 0 ? ($minimum_stock_level * 2) : 0;
					$reorder_needed = max(0, $suggested_reorder - $current_stock);
					
					$str .= "<tr class='$row_class'>";
					$str .= "<td>" . ++$i . "</td>";
					
					if(store_module() && is_admin()) {
						$str .= "<td>" . $this->get_store_name($row->store_id) . "</td>";
					}
					
					$str .= "<td><code>" . $row->item_code . "</code></td>";
					$str .= "<td><strong>" . $row->item_name . "</strong><br><small class='text-muted'>Reorder Qty: " . $this->format_qty($reorder_needed) . "</small></td>";
					$str .= "<td>" . ($row->brand_name ?: 'N/A') . "</td>";
					$str .= "<td>" . ($row->category_name ?: 'N/A') . "</td>";
					$str .= "<td class='text-center'><strong class='text-" . $row_class . "'>" . $this->format_qty($current_stock) . "</strong></td>";
					$str .= "<td class='text-center'>" . $this->format_qty($minimum_stock_level) . "</td>";
					$str .= "<td class='text-center'>" . $stock_status . "</td>";
					$str .= "<td class='text-right'><strong>" . $this->format_currency($stock_value, $base_currency_symbol, $base_currency_position) . "</strong></td>";
					$str .= "<td class='text-center'>" . ($days_to_run_out == 'N/A' ? '<span class="text-muted">N/A</span>' : '<span class="badge badge-info">' . $days_to_run_out . ' days</span>') . "</td>";
					
					// Add action buttons
					$str .= "<td class='text-center no-print'>";
					$str .= "<div class='btn-group btn-group-xs'>";
					$str .= "<a href='".base_url()."stock_adjustment/add' class='btn btn-primary btn-xs' title='Stock Adjustment'>";
					$str .= "<i class='fa fa-edit'></i>";
					$str .= "</a>";
					$str .= "<a href='".base_url()."purchase/add' class='btn btn-success btn-xs' title='Add Purchase'>";
					$str .= "<i class='fa fa-plus'></i>";
					$str .= "</a>";
					$str .= "</div>";
					$str .= "</td>";
					$str .= "</tr>";
				}
				
				// Add summary statistics to the response
				$str .= "<script>";
				$str .= "updateStockAlertSummary(" . $out_of_stock_count . ", " . $critical_stock_count . ", " . $low_stock_count . ", '" . $this->format_currency($total_risk_value, $base_currency_symbol, $base_currency_position) . "');";
				$str .= "</script>";
				
				if($i == 0) {
					$total_columns = 10;
					if(store_module() && is_admin()) {
						$total_columns++;
					}
					$str = "<tr><td colspan='$total_columns' class='text-center text-success'><i class='fa fa-check-circle'></i> No low stock items found! All items are above minimum stock levels.</td></tr>";
				}
				
				return $str;
			} else {
				$total_columns = 10;
				if(store_module() && is_admin()) {
					$total_columns++;
				}
				return "<tr><td colspan='$total_columns' class='text-center text-info'><i class='fa fa-info-circle'></i> No items found with minimum stock levels set.</td></tr>";
			}
			
		} catch (Exception $e) {
			log_message('error', 'Low Stock Alert Report Error: ' . $e->getMessage());
			log_message('error', 'Low Stock Alert Report Stack Trace: ' . $e->getTraceAsString());
			$total_columns = 10;
			if(store_module() && is_admin()) {
				$total_columns++;
			}
			return "<tr><td colspan='$total_columns' class='text-center text-danger'>Error loading low stock alert report: " . $e->getMessage() . "</td></tr>";
		}
	}

	public function show_gross_profit_per_sale_report(){
		try {
			// Load multi-currency helper
			$this->load->helper('multi_currency_helper');
			
			// Get POST data safely
			$from_date = $this->input->post('from_date');
			$to_date = $this->input->post('to_date');
			$store_id = $this->input->post('store_id');
			$customer_id = $this->input->post('customer_id');
			$warehouse_id = $this->input->post('warehouse_id');
			$currency_id = $this->input->post('currency_id');

			// Set defaults
			if(empty($store_id)){
				$store_id = get_current_store_id();
			}
			if(empty($from_date)){
				$from_date = date('Y-m-01'); // First day of current month
			}
			if(empty($to_date)){
				$to_date = date('Y-m-d'); // Today
			}
			if(empty($currency_id)){
				$currency_id = get_base_currency_id(); // Use base currency by default
			}

			// Get base currency info
			$base_currency = get_base_currency($store_id);
			$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
			$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';

			// Convert dates
			$from_date = system_fromatted_date($from_date);
			$to_date = system_fromatted_date($to_date);

			// Get sales data with currency information
			$this->db->select("s.id, s.sales_code, s.sales_date, s.customer_id, c.customer_name, s.grand_total, s.store_id, s.transaction_currency_id, s.exchange_rate, s.base_currency_total");
			$this->db->select("cur.currency_code, cur.symbol, cur.currency_position");
			$this->db->from("db_sales s");
			$this->db->join("db_customers c", "c.id = s.customer_id", "left");
			$this->db->join("db_currency cur", "cur.id = s.transaction_currency_id", "left");
			$this->db->where("s.sales_status", "Final");
			$this->db->where("s.sales_date >=", $from_date);
			$this->db->where("s.sales_date <=", $to_date);
			$this->db->where("s.store_id", $store_id);
			
			if(!empty($customer_id)){
				$this->db->where("s.customer_id", $customer_id);
			}
			
			if(!empty($warehouse_id)){
				$this->db->where("s.warehouse_id", $warehouse_id);
			}
			
			$this->db->order_by("s.sales_date", "DESC");
			$query = $this->db->get();
			
			if($query->num_rows() > 0){
				$i = 0;
				$total_sales = 0;
				$total_cost = 0;
				$total_profit = 0;
				
				foreach($query->result() as $row){
					// Calculate cost and profit for this sale
					$sale_cost = 0;
					$sale_profit = 0;
					
					// Get sales items for this sale with currency info
					$this->db->select("si.item_id, si.sales_qty, si.unit_total_cost, si.total_cost, si.item_currency_id, si.item_exchange_rate, si.base_currency_price, si.unit_type, si.sales_qty_main, si.sales_qty_alternate, si.purchase_price as si_purchase_price, i.item_name, i.purchase_price, i.service_bit, i.conversion_factor, i.unit_id, i.alternate_unit_id");
					$this->db->from("db_salesitems si");
					$this->db->join("db_items i", "i.id = si.item_id", "left");
					$this->db->where("si.sales_id", $row->id);
					$items_query = $this->db->get();
					
					if($items_query->num_rows() > 0){
						foreach($items_query->result() as $item){
							// Calculate cost (only for non-service items)
							$item_cost = 0;
							if(
    (!empty($item->si_purchase_price) && floatval($item->si_purchase_price) > 0)
    ||
    (!empty($item->purchase_price) && floatval($item->purchase_price) > 0)
){
								// Get conversion factor
								$conversion_factor = !empty($item->conversion_factor) ? floatval($item->conversion_factor) : 0;
								
								// Determine sales_qty in main units - CRITICAL for multi-unit items
								// Always recalculate from unit_type if available (most reliable)
								$sales_qty_main = 0;
								
								// Method 1: Calculate from unit_type (most reliable - explicit unit used)
								if(!empty($item->unit_type)){
									if($item->unit_type == 'alternate'){
										// Sale was in alternate units - convert to main units
										if($conversion_factor > 0 && $conversion_factor != 1){
											$sales_qty_main = floatval($item->sales_qty) / $conversion_factor;
										} else {
											// No conversion factor, assume 1:1
											$sales_qty_main = floatval($item->sales_qty);
										}
									} else if($item->unit_type == 'main'){
										// Sale was in main units - use as is
										$sales_qty_main = floatval($item->sales_qty);
									}
								}
								// Method 2: Use stored sales_qty_main if unit_type not available
								else if(isset($item->sales_qty_main) && $item->sales_qty_main !== null && $item->sales_qty_main !== ''){
									$sales_qty_main_val = floatval($item->sales_qty_main);
									if($sales_qty_main_val > 0){
										$sales_qty_main = $sales_qty_main_val;
									}
								}
								// Method 3: Use sales_qty_alternate to detect unit type
								else if(!empty($item->sales_qty_alternate) && floatval($item->sales_qty_alternate) > 0){
									// If sales_qty equals sales_qty_alternate, it's in alternate units
									if(abs(floatval($item->sales_qty) - floatval($item->sales_qty_alternate)) < 0.01){
										if($conversion_factor > 0 && $conversion_factor != 1){
											$sales_qty_main = floatval($item->sales_qty) / $conversion_factor;
										} else {
											$sales_qty_main = floatval($item->sales_qty);
										}
									} else {
										// sales_qty is in main units
										$sales_qty_main = floatval($item->sales_qty);
									}
								}
								// Method 4: Fallback - assume main unit if no other info
								else {
									$sales_qty_main = floatval($item->sales_qty);
								}
								
								// Safety check - ensure we have a valid quantity
								if($sales_qty_main <= 0){
									$sales_qty_main = floatval($item->sales_qty);
								}
								
								// Now calculate cost - purchase prices are ALWAYS per main unit
								// Use actual cost calculation with proper unit handling
								$purchase_price_per_main = 0;
								
								// Priority 1: salesitems purchase price
if(
    !empty($item->si_purchase_price)
    && floatval($item->si_purchase_price) > 0
){
    $purchase_price_per_main =
        floatval($item->si_purchase_price);
}

// Priority 2: items table purchase price
else if(
    !empty($item->purchase_price)
    && floatval($item->purchase_price) > 0
){
    $purchase_price_per_main =
        floatval($item->purchase_price);
}

// Priority 3: base currency price
else if(
    !empty($item->base_currency_price)
    && floatval($item->base_currency_price) > 0
){
    $purchase_price_per_main =
        floatval($item->base_currency_price);
}
								
								// Calculate total cost: purchase_price_per_main (per main unit) Ã— sales_qty_main (in main units)
								if($purchase_price_per_main > 0 && $sales_qty_main > 0){
									$item_cost = $purchase_price_per_main * $sales_qty_main;
								} else {
									$item_cost = 0;
								}
								
								// Final validation - cost should be reasonable
								if($item_cost <= 0 || $item_cost > 100000){
									$item_cost = 0;
								}
							}
							// Services have zero cost
							
							$sale_cost += $item_cost;
						}
					}
					
					// Cost is calculated in base currency (purchase prices are in base currency)
					// Sales amount is in transaction currency
					// We need to convert both to the same currency for comparison
					
					$base_currency_id = get_base_currency_id();
					
					// Get sales amount in base currency
					$sales_amount_base = $row->grand_total;
					if (!empty($row->base_currency_total) && $row->base_currency_total > 0) {
						// Use stored base_currency_total if available (most accurate)
						$sales_amount_base = $row->base_currency_total;
					} elseif (!empty($row->transaction_currency_id) && $row->transaction_currency_id != $base_currency_id && !empty($row->exchange_rate) && $row->exchange_rate > 0) {
						// Convert from transaction currency to base currency
						$sales_amount_base = convert_currency($row->grand_total, $row->transaction_currency_id, $base_currency_id);
					}
					
					// Cost is already in base currency
					$cost_amount_base = $sale_cost;
					
					// If target currency is not base currency, convert both to target currency
					if($currency_id != $base_currency_id){
						// Convert sales from base currency to target currency
						$sales_exchange_rate = get_exchange_rate($base_currency_id, $currency_id, $store_id, $row->sales_date);
						if($sales_exchange_rate !== false && $sales_exchange_rate > 0){
							$sales_amount_base = $sales_amount_base * $sales_exchange_rate;
							// Convert cost from base currency to target currency
							$cost_amount_base = $cost_amount_base * $sales_exchange_rate;
						}
					}
					// If target currency is base currency, amounts are already in base currency
					
					// Sanity check for cost amount - should not exceed sales amount by too much
					if($cost_amount_base > $sales_amount_base * 10) {
						// If cost is more than 10x sales amount, something is wrong
						$cost_amount_base = $sales_amount_base * 0.8; // Use 80% of sales as cost
					}
					
					$sale_profit = $sales_amount_base - $cost_amount_base;
					$profit_percentage = $sales_amount_base > 0 ? ($sale_profit / $sales_amount_base) * 100 : 0;
					
					// Calculate cost in original transaction currency for display
					$cost_original_currency = $sale_cost; // Cost is in base currency
					if($row->transaction_currency_id != $base_currency_id && !empty($row->exchange_rate) && $row->exchange_rate > 0){
						// Convert cost from base currency to transaction currency
						// exchange_rate is from transaction to base, so to go from base to transaction, multiply
						$cost_original_currency = $sale_cost * $row->exchange_rate;
					}
					
					// Format amounts with original currency and target currency equivalent
					$sales_display = $this->_format_currency_with_base($row->grand_total, $row->transaction_currency_id, $sales_amount_base, $currency_id);
					
					// For cost, we need to determine the original currency of the cost
					// Cost is calculated in base currency, so we need to convert it to transaction currency for display
					$cost_original_currency_id = get_base_currency_id(); // Cost is in base currency
					$cost_display = $this->_format_currency_with_base($cost_original_currency, $cost_original_currency_id, $cost_amount_base, $currency_id);
					
					// Calculate profit in transaction currency for display
					$profit_original_currency = $row->grand_total - $cost_original_currency;
					$profit_display = $this->_format_currency_with_base($profit_original_currency, $row->transaction_currency_id, $sale_profit, $currency_id);
					
					echo "<tr>";
					echo "<td>".++$i."</td>";
					echo "<td>".show_date($row->sales_date)."</td>";
					echo "<td><a href='".base_url("sales/invoice/".$row->id)."' target='_blank'>".$row->sales_code."</a></td>";
					echo "<td>".($row->customer_name ?: 'Walk-in Customer')."</td>";
					echo "<td class='text-right'>".$sales_display."</td>";
					echo "<td class='text-right'>".$cost_display."</td>";
					echo "<td class='text-right'>".$profit_display."</td>";
					echo "<td class='text-right'>".number_format($profit_percentage, 2)."%</td>";
					echo "</tr>";
					
					$total_sales += $sales_amount_base;
					$total_cost += $cost_amount_base;
					$total_profit += $sale_profit;
				}
				
				// Display totals
				$total_profit_percentage = $total_sales > 0 ? ($total_profit / $total_sales) * 100 : 0;
				echo "<tr class='bg-gray text-bold'>";
				echo "<td colspan='4' class='text-right'><b>Total:</b></td>";
				echo "<td class='text-right text-bold'>".format_currency_amount($total_sales, $currency_id)."</td>";
				echo "<td class='text-right text-bold'>".format_currency_amount($total_cost, $currency_id)."</td>";
				echo "<td class='text-right text-bold'>".format_currency_amount($total_profit, $currency_id)."</td>";
				echo "<td class='text-right text-bold'>".number_format($total_profit_percentage, 2)."%</td>";
				echo "</tr>";
			}
			else{
				echo "<tr><td colspan='8' class='text-center text-danger'>No Records Found</td></tr>";
			}
			
		} catch (Exception $e) {
			echo "<tr><td colspan='8' class='text-center text-danger'>Error: " . $e->getMessage() . "</td></tr>";
		}
	}

	private function _format_currency_with_base($original_amount, $original_currency_id, $base_amount, $target_currency_id) {
		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		
		// If same currency, just format normally
		if($original_currency_id == $target_currency_id) {
			return format_currency_amount($base_amount, $target_currency_id);
		}
		
		// Get original currency info
		$this->db->select('currency_name, currency_symbol, symbol, decimal_places, currency_position');
		$this->db->from('db_currency');
		$this->db->where('id', $original_currency_id);
		$this->db->where('status', 1);
		$original_currency = $this->db->get()->row();
		
		// Get target currency info
		$this->db->select('currency_name, currency_symbol, symbol, decimal_places, currency_position');
		$this->db->from('db_currency');
		$this->db->where('id', $target_currency_id);
		$this->db->where('status', 1);
		$target_currency = $this->db->get()->row();
		
		if(!$original_currency || !$target_currency) {
			return format_currency_amount($base_amount, $target_currency_id);
		}
		
		// Format original amount
		$original_decimal_places = isset($original_currency->decimal_places) ? $original_currency->decimal_places : 2;
		$original_symbol = !empty($original_currency->symbol) ? $original_currency->symbol : (!empty($original_currency->currency_symbol) ? $original_currency->currency_symbol : '');
		$original_position = isset($original_currency->currency_position) ? $original_currency->currency_position : 'before';
		
		$is_negative = $original_amount < 0;
		$absolute_amount = abs($original_amount);
		
		// Remove unnecessary decimal places
		$formatted_original = number_format($absolute_amount, $original_decimal_places);
		if($original_decimal_places > 0) {
			$formatted_original = rtrim(rtrim($formatted_original, '0'), '.');
		}
		
		if($original_position == 'before') {
			$original_display = ($is_negative ? '-' : '') . $original_symbol . ' ' . $formatted_original;
		} else {
			$original_display = ($is_negative ? '-' : '') . $formatted_original . ' ' . $original_symbol;
		}
		
		
		// Format base amount
		$base_decimal_places = isset($target_currency->decimal_places) ? $target_currency->decimal_places : 2;
		$base_symbol = !empty($target_currency->symbol) ? $target_currency->symbol : (!empty($target_currency->currency_symbol) ? $target_currency->currency_symbol : '');
		$base_position = isset($target_currency->currency_position) ? $target_currency->currency_position : 'before';
		
		$base_is_negative = $base_amount < 0;
		$base_absolute_amount = abs($base_amount);
		
		// Remove unnecessary decimal places
		$formatted_base = number_format($base_absolute_amount, $base_decimal_places);
		if($base_decimal_places > 0) {
			$formatted_base = rtrim(rtrim($formatted_base, '0'), '.');
		}
		
		if($base_position == 'before') {
			$base_display = ($base_is_negative ? '-' : '') . $base_symbol . ' ' . $formatted_base;
		} else {
			$base_display = ($base_is_negative ? '-' : '') . $formatted_base . ' ' . $base_symbol;
		}
		
		
		// Return combined display
		return $original_display . ' ( ' . $base_display . ' )';
	}

	private function _get_item_actual_cost($item_id, $quantity, $sales_date, $store_id) {
		// Get the actual cost from purchase records using FIFO method
		$this->db->select("pi.price_per_unit, pi.purchase_qty, pi.item_currency_id, pi.item_exchange_rate, pi.base_currency_price, p.purchase_date, p.transaction_currency_id, p.exchange_rate");
		$this->db->from("db_purchaseitems pi");
		$this->db->join("db_purchase p", "p.id = pi.purchase_id", "left");
		$this->db->where("pi.item_id", $item_id);
		$this->db->where("pi.store_id", $store_id);
		$this->db->where("p.purchase_status", "Received");
		$this->db->where("p.purchase_date <=", $sales_date);
		$this->db->order_by("p.purchase_date", "ASC");
		$this->db->order_by("pi.id", "ASC");
		
		$query = $this->db->get();
		
		if($query->num_rows() > 0){
			$remaining_qty = $quantity;
			$total_cost = 0;
			
			foreach($query->result() as $purchase_item){
				if($remaining_qty <= 0) break;
				
				$available_qty = $purchase_item->purchase_qty;
				$used_qty = min($remaining_qty, $available_qty);
				
				$item_cost = $purchase_item->price_per_unit * $used_qty;
				
				// Convert to base currency if needed
				if($purchase_item->item_currency_id && $purchase_item->item_currency_id != get_base_currency_id()){
					$exchange_rate = get_exchange_rate($purchase_item->item_currency_id, get_base_currency_id(), $store_id, $purchase_item->purchase_date);
					if($exchange_rate !== false && $exchange_rate > 0){
						$item_cost = $item_cost * $exchange_rate;
					}
				}
				
				// If base_currency_price is available, use it for more accurate conversion
				if(!empty($purchase_item->base_currency_price) && $purchase_item->base_currency_price > 0 && $used_qty > 0){
					$item_cost = $purchase_item->base_currency_price * $used_qty;
				}
				
				// Sanity check - cost should not be unreasonably high
				if($item_cost > 0 && $item_cost < 1000000) { // Reasonable upper limit
					$total_cost += $item_cost;
				}
				
				$remaining_qty -= $used_qty;
			}
			
			return $total_cost;
		}
		
		// If no purchase records found, return 0
		return 0;
	}

	/**
	 * Show Payment Method Breakdown Report (Standalone)
	 */
	public function show_payment_method_breakdown_report(){
		try {
			extract($_POST);
			
			// Debug logging
			log_message('debug', 'Payment Method Breakdown Report - Model method called');
			log_message('debug', 'POST data: ' . print_r($_POST, true));

			// Load multi-currency helper safely
			try {
				$this->load->helper('multi_currency_helper');
				$base_currency = get_base_currency($store_id);
				$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
				$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
				log_message('debug', 'Currency loaded: ' . $base_currency_code . ' (' . $base_currency_symbol . ')');
			} catch (Exception $e) {
				log_message('error', 'Currency helper error: ' . $e->getMessage());
				$base_currency_code = 'USD';
				$base_currency_symbol = '$';
			}
			
			// Handle date formatting safely
			try {
				$from_date = system_fromatted_date($from_date);
				$to_date = system_fromatted_date($to_date);
				log_message('debug', 'From date: ' . $from_date . ', To date: ' . $to_date);
			} catch (Exception $e) {
				log_message('error', 'Date formatting error: ' . $e->getMessage());
				$from_date = date('Y-m-d', strtotime($from_date));
				$to_date = date('Y-m-d', strtotime($to_date));
				log_message('debug', 'Fallback dates - From: ' . $from_date . ', To: ' . $to_date);
			}

			// Test if payment table exists and has data
			$test_query = "SELECT COUNT(*) as count FROM db_salespayments LIMIT 1";
			$test_result = $this->db->query($test_query);
			if($test_result) {
				$count = $test_result->row()->count;
				log_message('debug', 'Total payments in database: ' . $count);
			} else {
				log_message('error', 'Cannot access db_salespayments table');
				echo '<tr><td colspan="7" class="text-center text-danger">Database error: Cannot access payment data</td></tr>';
				exit;
			}

		// Build where conditions for payment query
		$where_conditions = ["sp.status = 1"];
		
		if($from_date && $to_date) {
			$where_conditions[] = "(sp.payment_date >= '$from_date' AND sp.payment_date <= '$to_date')";
		}
		
		if(!empty($store_id)) {
			$where_conditions[] = "sp.store_id = $store_id";
		}
		
		if(!empty($customer_id)) {
			$where_conditions[] = "sp.customer_id = $customer_id";
		}
		
		if(!empty($created_by)) {
			$where_conditions[] = "upper(sp.created_by) = upper('$created_by')";
		}
		
		// Add warehouse filter if applicable
		if(warehouse_module() && warehouse_count() > 0 && !empty($warehouse_id)) {
			$where_conditions[] = "s.warehouse_id = $warehouse_id";
		}
		
		// Add service/product filtering to payment breakdown - MUTUALLY EXCLUSIVE
		if($item_type_filter != 'all') {
			if($item_type_filter == 'services') {
				// Payments for sales that have services (including mixed)
				$where_conditions[] = "s.id IN (
					SELECT s.id FROM db_sales s 
					WHERE EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = s.id AND COALESCE(i.service_bit, 0) = 1)
				)";
			} elseif($item_type_filter == 'products') {
				// Payments for sales that have ONLY products (no services)
				$where_conditions[] = "s.id IN (
					SELECT s.id FROM db_sales s 
					WHERE EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = s.id AND COALESCE(i.service_bit, 0) != 1)
					AND NOT EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = s.id AND COALESCE(i.service_bit, 0) = 1)
				)";
			}
		}
		
		$where_clause = implode(' AND ', $where_conditions);
		
		// Query to get payment method breakdown - simplified to avoid field issues
		$payment_query = "
			SELECT 
				sp.payment_type,
				COALESCE(SUM(sp.payment), 0) as total_amount,
				COUNT(DISTINCT sp.sales_id) as transaction_count,
				COUNT(sp.id) as payment_count
			FROM db_salespayments sp
			LEFT JOIN db_sales s ON s.id = sp.sales_id
			WHERE $where_clause
			AND sp.payment_type IS NOT NULL 
			AND sp.payment_type != ''
			GROUP BY sp.payment_type
			ORDER BY total_amount DESC
		";
		
		log_message('debug', 'Payment query: ' . $payment_query);
		
		$payment_result = $this->db->query($payment_query);
		
		if(!$payment_result) {
			log_message('error', 'Query failed: ' . $this->db->error()['message']);
			echo '<tr><td colspan="7" class="text-center text-danger">Database query failed: ' . htmlspecialchars($this->db->error()['message']) . '</td></tr>';
			exit;
		}
		
		log_message('debug', 'Query executed, num_rows: ' . $payment_result->num_rows());
		
		if($payment_result->num_rows() > 0) {
			$i = 0;
			$grand_total_payments = 0;
			
			// First pass: calculate total for accurate percentages
			foreach($payment_result->result() as $payment) {
				$grand_total_payments += $payment->total_amount;
			}
			
			// Second pass: display data with correct percentages
			foreach($payment_result->result() as $payment) {
				echo "<tr>";
				echo "<td>".++$i."</td>";
				if(store_module() && is_admin()){
					echo "<td>".get_store_name($store_id)."</td>";	
				}
				echo "<td class='payment-method-name'>".htmlspecialchars($payment->payment_type)."</td>";
				echo "<td class='text-right amount-cell'>".store_number_format($payment->total_amount)." ".$base_currency_symbol."</td>";
				echo "<td class='text-center'>".$payment->transaction_count."</td>";
				echo "<td class='text-center'>".$payment->payment_count."</td>";
				echo "<td class='text-right percentage-cell'>".($grand_total_payments > 0 ? number_format(($payment->total_amount / $grand_total_payments) * 100, 2) : "0.00")."%</td>";
				echo "</tr>";
			}
			
			// Grand total row
			$total_columns_count = 6;
			if(store_module() && is_admin()){
				$total_columns_count++;
			}
			
			echo "<tr class='total-row'>";
			echo "<td colspan='2' class='text-left'><b>TOTAL PAYMENTS (".$base_currency_code."):</b></td>";
			echo "<td class='text-right amount-cell'><b>".store_number_format($grand_total_payments)." ".$base_currency_symbol."</b></td>";
			echo "<td class='text-center'>-</td>";
			echo "<td class='text-center'>-</td>";
			echo "<td class='text-right percentage-cell'><b>100.00%</b></td>";
			echo "</tr>";
		}
		else{
			log_message('debug', 'No payment records found');
			$total_columns_count = 6;
			if(store_module() && is_admin()){
				$total_columns_count++;
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='$total_columns_count'>No Payment Records Found</td>";
			echo "</tr>";
		}
		
			log_message('debug', 'Payment Method Breakdown Report - Model method completed');
			exit;
		} catch (Exception $e) {
			log_message('error', 'Payment Method Breakdown Report Error: ' . $e->getMessage());
			echo '<tr><td colspan="7" class="text-center text-danger">Error: ' . htmlspecialchars($e->getMessage()) . '</td></tr>';
			exit;
		}
	}

	/**
	 * Show Payment Method Breakdown for Sales Report
	 */
	private function _show_payment_method_breakdown($from_date, $to_date, $store_id, $customer_id, $created_by, $warehouse_id, $base_currency_symbol, $base_currency_code, $total_columns_count, $item_type_filter = 'all') {
		// Build where conditions for payment query
		$where_conditions = ["sp.status = 1"];
		
		if($from_date && $to_date) {
			$where_conditions[] = "(sp.payment_date >= '$from_date' AND sp.payment_date <= '$to_date')";
		}
		
		if(!empty($store_id)) {
			$where_conditions[] = "sp.store_id = $store_id";
		}
		
		if(!empty($customer_id)) {
			$where_conditions[] = "sp.customer_id = $customer_id";
		}
		
		if(!empty($created_by)) {
			$where_conditions[] = "upper(sp.created_by) = upper('$created_by')";
		}
		
		// Add warehouse filter if applicable
		if(warehouse_module() && warehouse_count() > 0 && !empty($warehouse_id)) {
			$where_conditions[] = "s.warehouse_id = $warehouse_id";
		}
		
		// Add service/product filtering to payment breakdown - MUTUALLY EXCLUSIVE
		if($item_type_filter != 'all') {
			if($item_type_filter == 'services') {
				// Payments for sales that have services (including mixed)
				$where_conditions[] = "s.id IN (
					SELECT s.id FROM db_sales s 
					WHERE EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = s.id AND COALESCE(i.service_bit, 0) = 1)
				)";
			} elseif($item_type_filter == 'products') {
				// Payments for sales that have ONLY products (no services)
				$where_conditions[] = "s.id IN (
					SELECT s.id FROM db_sales s 
					WHERE EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = s.id AND COALESCE(i.service_bit, 0) != 1)
					AND NOT EXISTS (SELECT 1 FROM db_salesitems si INNER JOIN db_items i ON i.id = si.item_id WHERE si.sales_id = s.id AND COALESCE(i.service_bit, 0) = 1)
				)";
			}
		}
		
		$where_clause = implode(' AND ', $where_conditions);
		
		// Query to get payment method breakdown
		$payment_query = "
			SELECT 
				sp.payment_type,
				COALESCE(SUM(sp.payment), 0) as total_amount,
				COUNT(DISTINCT sp.sales_id) as transaction_count,
				COUNT(sp.id) as payment_count
			FROM db_salespayments sp
			LEFT JOIN db_sales s ON s.id = sp.sales_id
			WHERE $where_clause
			AND sp.payment_type IS NOT NULL 
			AND sp.payment_type != ''
			GROUP BY sp.payment_type
			ORDER BY total_amount DESC
		";
		
		$payment_result = $this->db->query($payment_query);
		
		// Debug logging
		log_message('debug', 'Payment Method Breakdown Query: ' . $payment_query);
		log_message('debug', 'Payment Method Breakdown Results: ' . $payment_result->num_rows() . ' rows');
		
		if($payment_result->num_rows() > 0) {
			// Add separator row
			echo "<tr><td colspan='" . ($total_columns_count + 4) . "' style='border-top: 2px solid #333; padding: 15px 0;'></td></tr>";
			echo "<tr><td colspan='" . ($total_columns_count + 4) . "' class='text-center text-bold' style='background-color: #f8f9fa; padding: 12px; font-size: 16px;'><b>PAYMENT METHOD BREAKDOWN</b></td></tr>";
			
			$grand_total_payments = 0;
			
			foreach($payment_result->result() as $payment) {
				$grand_total_payments += $payment->total_amount;
				
				echo "<tr style='background-color: #f8f9fa;'>";
				echo "<td colspan='" . ($total_columns_count + 4) . "' class='text-left' style='padding: 8px 15px; font-size: 13px;'>";
				echo "<b>Total " . htmlspecialchars($payment->payment_type) . ":</b> " . store_number_format($payment->total_amount) . " " . $base_currency_symbol;
				echo " <span style='color: #666; font-size: 11px;'>(" . $payment->transaction_count . " transactions)</span>";
				echo "</td>";
				echo "</tr>";
			}
			
			// Grand total of all payments
			echo "<tr style='background-color: #e8f4fd; border-top: 2px solid #007bff;'>";
			echo "<td colspan='" . ($total_columns_count + 4) . "' class='text-center' style='padding: 12px; font-size: 15px; font-weight: bold;'>";
			echo "<b>TOTAL PAYMENTS (" . $base_currency_code . "): " . store_number_format($grand_total_payments) . " " . $base_currency_symbol . "</b>";
			echo "</td>";
			echo "</tr>";
		} else {
			// No payment data found
			log_message('debug', 'No payment method data found for the given criteria');
			echo "<tr><td colspan='" . ($total_columns_count + 4) . "' style='border-top: 2px solid #333; padding: 10px 0;'></td></tr>";
			echo "<tr><td colspan='" . ($total_columns_count + 4) . "' class='text-center text-info' style='background-color: #f8f9fa; padding: 8px; font-size: 14px;'><b>PAYMENT METHOD BREAKDOWN</b></td></tr>";
			echo "<tr><td colspan='" . ($total_columns_count + 4) . "' class='text-center text-muted' style='padding: 8px;'>No payment method data found for the selected period</td></tr>";
		}
	}

	/**
	 * Daily Reconciliation Report
	 * Shows purchased, sold, and remaining stock in main unit (kgs)
	 */
	public function show_daily_reconciliation_report(){
		extract($_POST);
		
		// Load multi-currency helper
		$this->load->helper('multi_currency_helper');
		$base_currency = get_base_currency($store_id);
		$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
		
		// Format dates
		$from_date = system_fromatted_date($from_date);
		$to_date = system_fromatted_date($to_date);
		
		// Build where conditions
		$where_conditions = array();
		$params = array();
		
		if(!empty($store_id)){
			$where_conditions[] = "p.store_id = ?";
			$params[] = $store_id;
		}
		
		if(warehouse_module() && warehouse_count() > 0 && !empty($warehouse_id)){
			$where_conditions[] = "p.warehouse_id = ?";
			$params[] = $warehouse_id;
		}
		
		if(!empty($item_id)){
			$where_conditions[] = "i.id = ?";
			$params[] = $item_id;
		}
		
		$where_clause = !empty($where_conditions) ? " AND " . implode(" AND ", $where_conditions) : "";
		
		// Get items with multi-unit support
		// Query to get all items that have purchases or sales in the date range
		$items_query = "
			SELECT DISTINCT 
				i.id,
				i.item_code,
				i.item_name,
				i.main_unit_id,
				i.alternate_unit_id,
				i.conversion_factor,
				mu.unit_name as main_unit_name,
				au.unit_name as alternate_unit_name
			FROM db_items i
			LEFT JOIN db_units mu ON i.main_unit_id = mu.id
			LEFT JOIN db_units au ON i.alternate_unit_id = au.id
			WHERE i.status = 1
			AND i.service_bit = 0
			" . (!empty($item_id) ? " AND i.id = " . (int)$item_id : "") . "
			AND (
				EXISTS (
					SELECT 1 FROM db_purchaseitems pi
					JOIN db_purchase p ON pi.purchase_id = p.id
					WHERE pi.item_id = i.id
					AND p.purchase_date >= ?
					AND p.purchase_date <= ?
					AND p.purchase_status = 'Received'
					AND p.status = 1
					AND pi.status = 1
					" . (!empty($store_id) ? " AND p.store_id = " . (int)$store_id : "") . "
				)
				OR EXISTS (
					SELECT 1 FROM db_salesitems si
					JOIN db_sales s ON si.sales_id = s.id
					WHERE si.item_id = i.id
					AND s.sales_date >= ?
					AND s.sales_date <= ?
					AND s.sales_status = 'Final'
					AND s.status = 1
					AND si.status = 1
					" . (!empty($store_id) ? " AND s.store_id = " . (int)$store_id : "") . "
				)
			)
			ORDER BY i.item_name
		";
		
		$query_params = array($from_date, $to_date, $from_date, $to_date);
		$items_result = $this->db->query($items_query, $query_params);
		
		if($items_result->num_rows() == 0){
			$colspan_no_data = 5; // #, Item Code, Item Name, Total Purchased, Total Sold, Remaining Stock
			if(store_module() && is_admin()){
				$colspan_no_data++; // Add Store column
			}
			if(warehouse_module() && warehouse_count() > 0){
				$colspan_no_data++; // Add Warehouse column
			}
			echo "<tr>";
			echo "<td class='text-center text-danger' colspan='" . $colspan_no_data . "'>No Records Found</td>";
			echo "</tr>";
			exit;
		}
		
		$i = 0;
		$total_purchased_main = 0;
		$total_purchased_alt = 0;
		$total_sold_main = 0;
		$total_sold_alt = 0;
		$total_stock_main = 0;
		$total_stock_alt = 0;
		
		foreach($items_result->result() as $item){
			$i++;
			
			// Get total purchased in main unit for the date range
			$purchase_query = "
				SELECT COALESCE(SUM(COALESCE(pi.purchase_qty_main, pi.purchase_qty)), 0) as total_purchased
				FROM db_purchaseitems pi
				JOIN db_purchase p ON pi.purchase_id = p.id
				WHERE pi.item_id = ?
				AND p.purchase_date >= ?
				AND p.purchase_date <= ?
				AND p.purchase_status = 'Received'
				AND p.status = 1
				AND pi.status = 1
				" . (!empty($store_id) ? " AND p.store_id = " . (int)$store_id : "") . "
				" . (warehouse_module() && warehouse_count() > 0 && !empty($warehouse_id) ? " AND p.warehouse_id = " . (int)$warehouse_id : "") . "
			";
			
			$purchase_params = array($item->id, $from_date, $to_date);
			$purchase_result = $this->db->query($purchase_query, $purchase_params);
			$total_purchased_qty = $purchase_result->row()->total_purchased;
			
			// Get total sold in main unit for the date range
			// Use improved logic similar to custom_helper for accurate conversion
			$sales_query = "
				SELECT COALESCE(SUM(
					CASE 
						-- Priority 1: If unit_type is explicitly 'alternate', ALWAYS convert from sales_qty
						WHEN si.unit_type = 'alternate' AND i.conversion_factor > 0 AND si.sales_qty > 0 THEN ROUND(si.sales_qty / i.conversion_factor, 4)
						-- Priority 2: If unit_type is 'main', use sales_qty directly
						WHEN si.unit_type = 'main' THEN si.sales_qty
						-- Priority 3: Use sales_qty_main if it's properly set (not NULL and > 0)
						WHEN si.sales_qty_main IS NOT NULL AND si.sales_qty_main > 0 AND si.unit_type IS NULL THEN si.sales_qty_main
						-- Priority 4: If unit_type is NULL but item has multi-unit, check if sales_qty looks like alternate unit
						WHEN si.unit_type IS NULL AND i.conversion_factor > 0 AND i.conversion_factor != 1.0 AND si.sales_qty > 0 
							 AND (si.sales_qty_main IS NULL OR si.sales_qty_main = 0) 
							 AND (si.sales_qty < i.conversion_factor OR si.sales_qty > i.conversion_factor * 10) 
							 THEN ROUND(si.sales_qty / i.conversion_factor, 4)
						-- Priority 5: Fallback to sales_qty_main if set (even if 0)
						WHEN si.sales_qty_main IS NOT NULL THEN si.sales_qty_main
						-- Priority 6: Default to sales_qty (assume it's in main units)
						ELSE si.sales_qty
					END
				), 0) as total_sold
				FROM db_salesitems si
				JOIN db_sales s ON si.sales_id = s.id
				LEFT JOIN db_items i ON si.item_id = i.id
				WHERE si.item_id = ?
				AND s.sales_date >= ?
				AND s.sales_date <= ?
				AND s.sales_status = 'Final'
				AND s.status = 1
				AND si.status = 1
				" . (!empty($store_id) ? " AND s.store_id = " . (int)$store_id : "") . "
				" . (warehouse_module() && warehouse_count() > 0 && !empty($warehouse_id) ? " AND s.warehouse_id = " . (int)$warehouse_id : "") . "
			";
			
			$sales_params = array($item->id, $from_date, $to_date);
			$sales_result = $this->db->query($sales_query, $sales_params);
			$total_sold_qty = $sales_result->row()->total_sold;
			
			// Get current stock (remaining) in main unit at end of day
			$this->load->helper('custom_helper');
			$warehouse_id_for_stock = (warehouse_module() && warehouse_count() > 0 && !empty($warehouse_id)) ? $warehouse_id : get_store_warehouse_id();
			$store_id_for_stock = !empty($store_id) ? $store_id : get_current_store_id();
			$current_stock = get_total_qty_of_warehouse_item($item->id, $warehouse_id_for_stock, $store_id_for_stock);
			$remaining_stock = $current_stock;
			
			// Get unit names
			$main_unit_name = $item->main_unit_name ? strtolower($item->main_unit_name) : 'unit';
			$alternate_unit_name = $item->alternate_unit_name ? strtolower($item->alternate_unit_name) : '';
			$conversion_factor = !empty($item->conversion_factor) ? floatval($item->conversion_factor) : 0;
			
			// Calculate alternate unit quantities
			$purchased_alt = ($conversion_factor > 0 && $total_purchased_qty > 0) ? $total_purchased_qty * $conversion_factor : 0;
			$sold_alt = ($conversion_factor > 0 && $total_sold_qty > 0) ? $total_sold_qty * $conversion_factor : 0;
			$stock_alt = ($conversion_factor > 0 && $remaining_stock > 0) ? $remaining_stock * $conversion_factor : 0;
			
			// Format purchased display
			$purchased_display = number_format($total_purchased_qty, 2) . " " . $main_unit_name;
			if($conversion_factor > 0 && $alternate_unit_name && $purchased_alt > 0){
				$purchased_display .= "<br><small class='text-muted'>(" . number_format($purchased_alt, 2) . " " . $alternate_unit_name . ")</small>";
			}
			
			// Format sold display
			$sold_display = number_format($total_sold_qty, 2) . " " . $main_unit_name;
			if($conversion_factor > 0 && $alternate_unit_name && $sold_alt > 0){
				$sold_display .= "<br><small class='text-muted'>(" . number_format($sold_alt, 2) . " " . $alternate_unit_name . ")</small>";
			}
			
			// Format remaining stock display
			$stock_display = number_format($remaining_stock, 2) . " " . $main_unit_name;
			if($conversion_factor > 0 && $alternate_unit_name && $stock_alt > 0){
				$stock_display .= "<br><small class='text-muted'>(" . number_format($stock_alt, 2) . " " . $alternate_unit_name . ")</small>";
			}
			
			echo "<tr>";
			echo "<td class='text-center'>" . $i . "</td>";
			if(store_module() && is_admin()){
				echo "<td class='text-left'>" . get_store_name($store_id) . "</td>";
			}
			if(warehouse_module() && warehouse_count() > 0){
				echo "<td class='text-left'>" . get_warehouse_name($warehouse_id) . "</td>";
			}
			echo "<td class='text-left'>" . htmlspecialchars($item->item_code) . "</td>";
			echo "<td class='text-left'>" . htmlspecialchars($item->item_name) . "</td>";
			echo "<td class='text-right' style='vertical-align:middle;'>" . $purchased_display . "</td>";
			echo "<td class='text-right' style='vertical-align:middle;'>" . $sold_display . "</td>";
			echo "<td class='text-right' style='vertical-align:middle;'>" . $stock_display . "</td>";
			echo "</tr>";
			
			// Accumulate totals
			$total_purchased_main += $total_purchased_qty;
			$total_purchased_alt += $purchased_alt;
			$total_sold_main += $total_sold_qty;
			$total_sold_alt += $sold_alt;
			$total_stock_main += $remaining_stock;
			$total_stock_alt += $stock_alt;
		}
		
		// Display totals with both units
		// Calculate colspan: # (1) + Store (if admin) + Warehouse (if enabled) + Item Code (1) + Item Name (1)
		$colspan = 3; // Base: #, Item Code, Item Name
		if(store_module() && is_admin()){
			$colspan++; // Add Store column
		}
		if(warehouse_module() && warehouse_count() > 0){
			$colspan++; // Add Warehouse column
		}
		
		// Get default unit names from last item or use defaults
		$default_main_unit = isset($item) && $item->main_unit_name ? strtolower($item->main_unit_name) : 'unit';
		$default_alt_unit = isset($item) && $item->alternate_unit_name ? strtolower($item->alternate_unit_name) : '';
		
		// Format total purchased
		$total_purchased_display = number_format($total_purchased_main, 2) . " " . $default_main_unit;
		if($total_purchased_alt > 0 && $default_alt_unit){
			$total_purchased_display .= "<br><small class='text-muted'>(" . number_format($total_purchased_alt, 2) . " " . $default_alt_unit . ")</small>";
		}
		
		// Format total sold
		$total_sold_display = number_format($total_sold_main, 2) . " " . $default_main_unit;
		if($total_sold_alt > 0 && $default_alt_unit){
			$total_sold_display .= "<br><small class='text-muted'>(" . number_format($total_sold_alt, 2) . " " . $default_alt_unit . ")</small>";
		}
		
		// Format total stock
		$total_stock_display = number_format($total_stock_main, 2) . " " . $default_main_unit;
		if($total_stock_alt > 0 && $default_alt_unit){
			$total_stock_display .= "<br><small class='text-muted'>(" . number_format($total_stock_alt, 2) . " " . $default_alt_unit . ")</small>";
		}
		
		echo "<tr class='bg-gray total-row' style='font-weight:bold; background-color:#e8e8e8; border-top: 2px solid #333;'>";
		echo "<td class='total-label' colspan='" . $colspan . "' style='font-weight:bold; text-align:right !important; padding-right:15px !important; vertical-align:middle !important; width:auto;'><span style='display:inline-block; text-align:right; width:100%;'>Total:</span></td>";
		echo "<td class='text-right total-value' style='vertical-align:middle !important; font-weight:bold; text-align:right !important; padding-right:15px !important;'>" . $total_purchased_display . "</td>";
		echo "<td class='text-right total-value' style='vertical-align:middle !important; font-weight:bold; text-align:right !important; padding-right:15px !important;'>" . $total_sold_display . "</td>";
		echo "<td class='text-right total-value' style='vertical-align:middle !important; font-weight:bold; text-align:right !important; padding-right:15px !important;'>" . $total_stock_display . "</td>";
		echo "</tr>";
		
		exit;
	}

	/**
	 * Get comprehensive Profit & Loss Statement in base currency
	 * Includes: Sales, Purchases, Expenses, Gross Profit, Net Profit, and Cash Balance
	 */
	public function get_profit_loss_statement_base_currency() {
		try {
			// Load required helpers first
			$this->load->helper('multi_currency_helper');
			$this->load->helper('cash_account_helper');
			
			$store_id = $this->input->post('store_id');
			$from_date = $this->input->post('from_date');
			$to_date = $this->input->post('to_date');
			$warehouse_id = $this->input->post('warehouse_id');
			$show_items_sold = $this->input->post('show_items_sold');
			$show_expenses = $this->input->post('show_expenses');
			
			// Set defaults
			if(empty($store_id)){
				$store_id = get_current_store_id();
			}
			if(empty($from_date)){
				$from_date = date('Y-m-01'); // First day of current month
			}
			if(empty($to_date)){
				$to_date = date('Y-m-d'); // Today
			}
			
			// Get base currency
			$base_currency = get_base_currency($store_id);
			$base_currency_id = $base_currency ? $base_currency->id : 1; // Default to 1 if not found
			$base_currency_code = $base_currency ? $base_currency->currency_code : 'USD';
			$base_currency_symbol = $base_currency ? $base_currency->symbol : '$';
			$base_currency_position = $base_currency ? $base_currency->currency_position : 'before';
			
			// Convert dates
			$from_date = system_fromatted_date($from_date);
			$to_date = system_fromatted_date($to_date);
			
			// Get P&L data (in base currency - don't pass currency_id)
			// Save original POST data
			$original_post = $_POST;
			
			// Set POST data for get_comprehensive_pl_report (without currency_id to ensure base currency)
			$_POST['store_id'] = $store_id;
			$_POST['from_date'] = $from_date;
			$_POST['to_date'] = $to_date;
			$_POST['warehouse_id'] = $warehouse_id;
			unset($_POST['currency_id']); // Remove currency_id to ensure base currency
			
			$pl_data = $this->get_comprehensive_pl_report();
			
			// Get Cash Flow data (in base currency)
			$_POST['store_id'] = $store_id;
			$_POST['from_date'] = $from_date;
			$_POST['to_date'] = $to_date;
			
			$cash_flow_data = $this->get_cash_flow_statement();
			
			// Restore original POST data
			$_POST = $original_post;
			
			// Calculate opening cash balance (before from_date)
			$opening_cash_balance = 0;
			// Helper already loaded at the beginning of the function
			$cash_account_id = get_cash_account_id($store_id);
			
			// Calculate opening cash from ALL sales payments and purchase payments before from_date (all payment types - Cash, M-Pesa, Card, etc.)
			// Convert all to base currency - use the base_currency_id we already have
			
			// Opening cash from sales - ALL payment types (convert to base currency; prefer base_currency_amount if available)
			$this->db->select('COALESCE(SUM(CASE 
				WHEN sp.base_currency_amount IS NOT NULL AND sp.base_currency_amount > 0 THEN sp.base_currency_amount 
				WHEN s.transaction_currency_id IS NOT NULL AND s.transaction_currency_id != ' . $base_currency_id . ' AND s.exchange_rate IS NOT NULL AND s.exchange_rate > 0 
				THEN sp.payment / s.exchange_rate 
				ELSE sp.payment 
			END), 0) as total');
			$this->db->from('db_salespayments sp');
			$this->db->join('db_sales s', 's.id = sp.sales_id', 'left');
			$this->db->where('(COALESCE(sp.payment_date, s.sales_date) < ' . $this->db->escape($from_date) . ')', null, false);
			if($store_id && (int)$store_id > 0) {
				$sid = (int) $store_id;
				$this->db->where('(COALESCE(sp.store_id, s.store_id) = ' . $sid . ')', null, false);
			}
			$_row = $this->db->get()->row();
			$opening_cash_in = ($_row && isset($_row->total)) ? floatval($_row->total) : 0;
			
			// Opening cash from purchase payments (convert to base currency; prefer base_currency_amount if available)
			$this->db->select('COALESCE(SUM(CASE 
				WHEN pp.base_currency_amount IS NOT NULL AND pp.base_currency_amount > 0 THEN pp.base_currency_amount 
				WHEN p.transaction_currency_id IS NOT NULL AND p.transaction_currency_id != ' . $base_currency_id . ' AND p.exchange_rate IS NOT NULL AND p.exchange_rate > 0 
				THEN pp.payment / p.exchange_rate 
				ELSE pp.payment 
			END), 0) as total');
			$this->db->from('db_purchasepayments pp');
			$this->db->join('db_purchase p', 'p.id = pp.purchase_id', 'left');
			$this->db->where('pp.payment_date <', $from_date);
			if($store_id) $this->db->where('pp.store_id', $store_id);
			$_row = $this->db->get()->row();
			$opening_cash_out = ($_row && isset($_row->total)) ? floatval($_row->total) : 0;
			
			// Opening expenses (convert to base currency)
			$this->db->select('COALESCE(SUM(CASE 
				WHEN e.base_currency_amount IS NOT NULL AND e.base_currency_amount > 0 
				THEN e.base_currency_amount 
				WHEN e.expense_currency_id IS NOT NULL AND e.expense_currency_id != ' . $base_currency_id . ' AND e.exchange_rate IS NOT NULL AND e.exchange_rate > 0 
				THEN e.expense_amt / e.exchange_rate 
				ELSE e.expense_amt 
			END), 0) as total');
			$this->db->from('db_expense e');
			$this->db->where('e.expense_date <', $from_date);
			if($store_id) $this->db->where('e.store_id', $store_id);
			$_row = $this->db->get()->row();
			$opening_expenses = ($_row && isset($_row->total)) ? floatval($_row->total) : 0;
			
			$opening_cash_balance = floatval($opening_cash_in) - floatval($opening_cash_out) - floatval($opening_expenses);
			
			// Net cash flow for the period: ALL sales payments (all types) - purchase payments - expenses (in base currency)
			$this->db->select('COALESCE(SUM(CASE 
				WHEN sp.base_currency_amount IS NOT NULL AND sp.base_currency_amount > 0 THEN sp.base_currency_amount 
				WHEN s.transaction_currency_id IS NOT NULL AND s.transaction_currency_id != ' . $base_currency_id . ' AND s.exchange_rate IS NOT NULL AND s.exchange_rate > 0 
				THEN sp.payment / s.exchange_rate 
				ELSE sp.payment 
			END), 0) as total');
			$this->db->from('db_salespayments sp');
			$this->db->join('db_sales s', 's.id = sp.sales_id', 'left');
			$this->db->where('(COALESCE(sp.payment_date, s.sales_date) >= ' . $this->db->escape($from_date) . ' AND COALESCE(sp.payment_date, s.sales_date) <= ' . $this->db->escape($to_date) . ')', null, false);
			if($store_id && (int)$store_id > 0) {
				$sid = (int) $store_id;
				$this->db->where('(COALESCE(sp.store_id, s.store_id) = ' . $sid . ')', null, false);
			}
			$_row = $this->db->get()->row();
			$period_cash_in = ($_row && isset($_row->total)) ? floatval($_row->total) : 0;
			
			$this->db->select('COALESCE(SUM(CASE 
				WHEN pp.base_currency_amount IS NOT NULL AND pp.base_currency_amount > 0 THEN pp.base_currency_amount 
				WHEN p.transaction_currency_id IS NOT NULL AND p.transaction_currency_id != ' . $base_currency_id . ' AND p.exchange_rate IS NOT NULL AND p.exchange_rate > 0 
				THEN pp.payment / p.exchange_rate 
				ELSE pp.payment 
			END), 0) as total');
			$this->db->from('db_purchasepayments pp');
			$this->db->join('db_purchase p', 'p.id = pp.purchase_id', 'left');
			$this->db->where('pp.payment_date >=', $from_date);
			$this->db->where('pp.payment_date <=', $to_date);
			if($store_id) $this->db->where('pp.store_id', $store_id);
			$_row = $this->db->get()->row();
			$period_cash_out_purchase = ($_row && isset($_row->total)) ? floatval($_row->total) : 0;
			
			$period_expenses = floatval($pl_data['expenses']['total']);
			$net_cash_flow = $period_cash_in - $period_cash_out_purchase - $period_expenses;
			
			// Calculate closing cash balance
			$closing_cash_balance = $opening_cash_balance + $net_cash_flow;
			
			// Build comprehensive report data
			$report = array(
				'period' => array(
					'from_date' => $from_date,
					'to_date' => $to_date,
					'store_id' => $store_id,
					'warehouse_id' => $warehouse_id
				),
			'revenue' => array(
				'sales' => floatval($pl_data['sales']['total']),
				'sales_return' => floatval($pl_data['sales_return']['total']),
				'net_sales' => floatval($pl_data['sales']['total']) - floatval($pl_data['sales_return']['total'])
			),
			'cost_of_goods_sold' => array(
				'cogs' => floatval($pl_data['cogs']['total']),
				'cogs_return' => floatval($pl_data['cogs_return']['total']),
				'net_cogs' => floatval($pl_data['cogs']['total']) - floatval($pl_data['cogs_return']['total'])
			),
				'purchase' => array(
					'purchases' => floatval(isset($pl_data['purchase']['total']) ? $pl_data['purchase']['total'] : 0),
					'purchase_return' => floatval(isset($pl_data['purchase_return']['total']) ? $pl_data['purchase_return']['total'] : 0),
					'net_purchases' => floatval(isset($pl_data['purchase']['total']) ? $pl_data['purchase']['total'] : 0) - floatval(isset($pl_data['purchase_return']['total']) ? $pl_data['purchase_return']['total'] : 0)
				),
				'gross_profit' => floatval($pl_data['gross_profit']),
				'operating_expenses' => array(
					'expenses' => floatval($pl_data['expenses']['total']),
					'sales_tax' => floatval($pl_data['sales_tax']['total']),
					'total_operating_expenses' => floatval($pl_data['expenses']['total']) + floatval($pl_data['sales_tax']['total'])
				),
				'net_profit' => floatval($pl_data['net_profit']),
				'cash' => array(
					'opening_balance' => $opening_cash_balance,
					'net_cash_flow' => $net_cash_flow,
					'closing_balance' => $closing_cash_balance
				),
				'currency' => array(
					'code' => $base_currency_code,
					'symbol' => $base_currency_symbol,
					'position' => $base_currency_position
				),
				'details' => array(
					'sales_count' => isset($pl_data['sales']['count']) ? $pl_data['sales']['count'] : 0,
					'purchase_count' => isset($pl_data['purchase']['count']) ? $pl_data['purchase']['count'] : 0,
					'expense_count' => isset($pl_data['expenses']['count']) ? $pl_data['expenses']['count'] : 0
				),
				'show_items_sold' => !empty($show_items_sold),
				'show_expenses' => !empty($show_expenses),
				'items_sold' => array(),
				'expenses_list' => array()
			);
			
			// Get detailed items sold if requested
			if(!empty($show_items_sold)){
				$sales_ids = $this->_get_db_sales_ids($store_id, $from_date, $to_date);
				if($sales_ids != 'null'){
					// Fetch all sales items with full details (like gross_profit_per_sale does)
					$this->db->select("si.item_id, si.sales_qty, si.unit_total_cost, si.total_cost, si.item_currency_id, si.item_exchange_rate, si.base_currency_price, si.unit_type, si.sales_qty_main, si.sales_qty_alternate, si.purchase_price as si_purchase_price, i.item_name, i.purchase_price, i.service_bit, i.conversion_factor, i.unit_id, i.alternate_unit_id, s.id as sales_id, s.grand_total, s.base_currency_total, s.transaction_currency_id, s.exchange_rate");
					$this->db->from("db_salesitems si");
					$this->db->join("db_items i", "i.id = si.item_id", "left");
					$this->db->join("db_sales s", "s.id = si.sales_id", "left");
					$this->db->where("si.sales_id IN ($sales_ids)");
					$this->db->where("s.sales_status", "Final");
					$this->db->where("i.service_bit", 0); // Only products, not services
					if(!empty($warehouse_id)){
						$this->db->where("s.warehouse_id", $warehouse_id);
					}
					$items_query = $this->db->get();
					
					// Process items in PHP (same logic as gross_profit_per_sale)
					$items_summary = array();
					
					if($items_query->num_rows() > 0){
						foreach($items_query->result() as $item){
							$item_id = $item->item_id;
							$item_name = $item->item_name;
							
							// Initialize item summary if not exists
							if(!isset($items_summary[$item_id])){
								$items_summary[$item_id] = array(
									'item_name' => $item_name,
									'total_qty' => 0,
									'total_qty_alternate' => 0, // Track alternate unit quantity
									'total_sales' => 0,
									'total_cost' => 0,
									'has_alternate_sales' => false, // Track if any sales were in alternate units
									'has_main_sales' => false, // Track if any sales were in main units
									'conversion_factor' => 0, // Store conversion factor for this item
									'sales_count' => 0
								);
							}
							
							// Calculate sales_qty in main units (same 4-method priority as gross_profit_per_sale)
							$conversion_factor = !empty($item->conversion_factor) ? floatval($item->conversion_factor) : 0;
							$items_summary[$item_id]['conversion_factor'] = $conversion_factor; // Store for later use
							$sales_qty_main = 0;
							$sales_qty_alternate = 0;
							$is_alternate_unit = false;
							
							// Method 1: Calculate from unit_type (most reliable)
							if(!empty($item->unit_type)){
								if($item->unit_type == 'alternate'){
									$is_alternate_unit = true;
									$sales_qty_alternate = floatval($item->sales_qty);
									if($conversion_factor > 0 && $conversion_factor != 1){
										$sales_qty_main = $sales_qty_alternate / $conversion_factor;
									} else {
										$sales_qty_main = $sales_qty_alternate;
									}
								} else if($item->unit_type == 'main'){
									$is_alternate_unit = false;
									$sales_qty_main = floatval($item->sales_qty);
									if($conversion_factor > 0 && $conversion_factor != 1){
										$sales_qty_alternate = $sales_qty_main * $conversion_factor;
									} else {
										$sales_qty_alternate = $sales_qty_main;
									}
								}
							}
							// Method 2: Use stored sales_qty_main
							else if(isset($item->sales_qty_main) && $item->sales_qty_main !== null && $item->sales_qty_main !== ''){
								$sales_qty_main_val = floatval($item->sales_qty_main);
								if($sales_qty_main_val > 0){
									$sales_qty_main = $sales_qty_main_val;
									$is_alternate_unit = false;
									if($conversion_factor > 0 && $conversion_factor != 1){
										$sales_qty_alternate = $sales_qty_main * $conversion_factor;
									} else {
										$sales_qty_alternate = $sales_qty_main;
									}
								}
							}
							// Method 3: Use sales_qty_alternate to detect unit type
							else if(!empty($item->sales_qty_alternate) && floatval($item->sales_qty_alternate) > 0){
								if(abs(floatval($item->sales_qty) - floatval($item->sales_qty_alternate)) < 0.01){
									$is_alternate_unit = true;
									$sales_qty_alternate = floatval($item->sales_qty);
									if($conversion_factor > 0 && $conversion_factor != 1){
										$sales_qty_main = $sales_qty_alternate / $conversion_factor;
									} else {
										$sales_qty_main = $sales_qty_alternate;
									}
								} else {
									$is_alternate_unit = false;
									$sales_qty_main = floatval($item->sales_qty);
									if($conversion_factor > 0 && $conversion_factor != 1){
										$sales_qty_alternate = $sales_qty_main * $conversion_factor;
									} else {
										$sales_qty_alternate = $sales_qty_main;
									}
								}
							}
							// Method 4: Fallback - assume main unit
							else {
								$is_alternate_unit = false;
								$sales_qty_main = floatval($item->sales_qty);
								if($conversion_factor > 0 && $conversion_factor != 1){
									$sales_qty_alternate = $sales_qty_main * $conversion_factor;
								} else {
									$sales_qty_alternate = $sales_qty_main;
								}
							}
							
							// Safety check
							if($sales_qty_main <= 0){
								$sales_qty_main = floatval($item->sales_qty);
								$is_alternate_unit = false;
							}
							
							// Track which unit type was used
							if($is_alternate_unit){
								$items_summary[$item_id]['has_alternate_sales'] = true;
							} else {
								$items_summary[$item_id]['has_main_sales'] = true;
							}
							
							// Calculate cost (same 3-priority logic as gross_profit_per_sale)
							$purchase_price_per_main = 0;
							
							// Priority 1: Use base_currency_price from salesitems
							if(!empty($item->base_currency_price) && floatval($item->base_currency_price) > 0 && floatval($item->base_currency_price) < 100000){
								$purchase_price_per_main = floatval($item->base_currency_price);
							}
							// Priority 2: Use purchase_price from salesitems
							else if(!empty($item->si_purchase_price) && floatval($item->si_purchase_price) > 0 && floatval($item->si_purchase_price) < 100000){
								$purchase_price_per_main = floatval($item->si_purchase_price);
							}
							// Priority 3: Use purchase_price from items table
							else if(!empty($item->purchase_price) && floatval($item->purchase_price) > 0){
								$purchase_price_per_main = floatval($item->purchase_price);
							}
							
							// Calculate item cost: purchase_price_per_main Ã— sales_qty_main
							$item_cost = 0;
							if($purchase_price_per_main > 0 && $sales_qty_main > 0){
								$item_cost = $purchase_price_per_main * $sales_qty_main;
							}
							
							// Final validation
							if($item_cost <= 0 || $item_cost > 100000){
								$item_cost = 0;
							}
							
							// Convert sales amount to base currency
							$item_sales_base = 0;
							if(!empty($item->base_currency_total) && $item->base_currency_total > 0 && $item->grand_total > 0){
								// Use proportional conversion
								$item_sales_base = floatval($item->total_cost) * ($item->base_currency_total / $item->grand_total);
							} else if(!empty($item->exchange_rate) && $item->exchange_rate > 0 && $item->transaction_currency_id != $base_currency_id){
								$item_sales_base = floatval($item->total_cost) / $item->exchange_rate;
							} else {
								$item_sales_base = floatval($item->total_cost);
							}
							
							// Accumulate totals
							$items_summary[$item_id]['total_qty'] += $sales_qty_main;
							$items_summary[$item_id]['total_qty_alternate'] += $sales_qty_alternate;
							$items_summary[$item_id]['total_sales'] += $item_sales_base;
							$items_summary[$item_id]['total_cost'] += $item_cost;
							$items_summary[$item_id]['sales_count'] += 1;
						}
						
						// Convert to array format and calculate avg_price
						$items_result = array();
						foreach($items_summary as $item_id => $summary){
							// Determine which unit to use for price display
							// If item was sold only in alternate units, show price per alternate unit
							// If item was sold only in main units, show price per main unit
							// If item was sold in both, show price per main unit (default)
							$use_alternate_for_price = false;
							if($summary['has_alternate_sales'] && !$summary['has_main_sales']){
								// Only alternate units were used
								$use_alternate_for_price = true;
							}
							
							// Calculate average unit price
							$avg_price = 0;
							if($use_alternate_for_price && $summary['total_qty_alternate'] > 0){
								// Calculate price per alternate unit
								$avg_price = $summary['total_sales'] / $summary['total_qty_alternate'];
							} else if($summary['total_qty'] > 0){
								// Calculate price per main unit
								$avg_price = $summary['total_sales'] / $summary['total_qty'];
							}
							
							$items_result[] = array(
								'item_name' => $summary['item_name'],
								'total_qty' => round($summary['total_qty'], 2),
								'avg_price' => round($avg_price, 2),
								'total_sales' => round($summary['total_sales'], 2),
								'total_cost' => round($summary['total_cost'], 2)
							);
						}
						
						// Sort by total_sales descending
						usort($items_result, function($a, $b) {
							return $b['total_sales'] - $a['total_sales'];
						});
						
						$report['items_sold'] = $items_result;
					}
				}
			}
			
			// Get detailed expense list if requested
			if(!empty($show_expenses)){
				$expense_ids = $this->_get_db_expense_ids($store_id, $from_date, $to_date);
				if($expense_ids != 'null'){
					$base_currency_id_escaped = (int)$base_currency_id; // Ensure it's an integer
					// Use FALSE to disable auto-escaping for CASE statement
					$this->db->select("e.expense_date, e.note as expense_note, 
						CASE 
							WHEN e.base_currency_amount IS NOT NULL AND e.base_currency_amount > 0 
							THEN e.base_currency_amount 
							WHEN e.expense_currency_id IS NOT NULL AND e.expense_currency_id != " . $base_currency_id_escaped . " AND e.exchange_rate IS NOT NULL AND e.exchange_rate > 0 
							THEN e.expense_amt / e.exchange_rate 
							ELSE e.expense_amt 
						END as expense_amt,
						ec.category_name", FALSE);
					$this->db->from("db_expense e");
					$this->db->join("db_expense_category ec", "ec.id = e.category_id", "left");
					$this->db->where("e.id IN ($expense_ids)");
					$this->db->order_by("e.expense_date", "DESC");
					$expenses_query = $this->db->get();
					if($expenses_query->num_rows() > 0){
						$report['expenses_list'] = $expenses_query->result_array();
					}
				}
			}
			
			return $report;
			
		} catch (Exception $e) {
			log_message('error', 'Profit & Loss Statement Error: ' . $e->getMessage());
			return array(
				'error' => true,
				'message' => 'Error generating profit & loss statement: ' . $e->getMessage()
			);
		}
	}

}