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

class Purchase_model extends CI_Model {
	//Datatable start
	var $table = 'db_purchase as a';
	var $column_order = array( 
								'a.id',
								'a.purchase_date',
								'a.purchase_code',
								'a.purchase_status',
								'a.reference_no',
								'b.supplier_name',
								'a.grand_total',
								'a.paid_amount',
								'a.payment_status',
								'a.created_by',
								'a.return_bit',
								'a.store_id',
								'a.transaction_currency_id',
								'a.exchange_rate',
								'a.base_currency_total'
								); //set column field database for datatable orderable
	var $column_search = array( 
								'a.id',
								'a.purchase_date',
								'a.purchase_code',
								'a.purchase_status',
								'a.reference_no',
								'b.supplier_name',
								'a.grand_total',
								'a.paid_amount',
								'a.payment_status',
								'a.created_by',
								'a.return_bit',
								'a.store_id'
								); //set column field database for datatable searchable 
	var $order = array('a.id' => 'desc'); // default order 

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

	private function _get_datatables_query()
	{
		$this->db->select($this->column_order);
		$this->db->from($this->table);
		$this->db->join('db_suppliers as b','b.id=a.supplier_id','left');
		
		/*If warehouse selected*/
		$warehouse_id = $this->input->post('warehouse_id');
		if(!empty($warehouse_id)){
			$this->db->join('db_warehouse as w','w.id='.$warehouse_id,'left');
			$this->db->where('a.warehouse_id',$warehouse_id);
		}

		if(!is_admin()){
	      	if($this->session->userdata('role_id')!='2'){
	      		if(!permissions('show_all_users_purchase_invoices')){
	      			$this->db->where("upper(a.created_by)",strtoupper($this->session->userdata('inv_username')));
	      		}
	      	}
	      }
		
		//if not admin
	    /*if(!is_admin()){*/
	      $this->db->where("a.store_id",get_current_store_id());
	    /*}*/
		$i = 0;
	
		foreach ($this->column_search as $item) // loop column 
		{
			if($_POST['search']['value']) // if datatable send POST for search
			{
				
				

				if($i===0) // first loop
				{
					$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.

					$this->db->like($item, $_POST['search']['value']);

				}
				else
				{
					$this->db->or_like($item, $_POST['search']['value']);
				}

				


				if(count($this->column_search) - 1 == $i) //last loop
					$this->db->group_end(); //close bracket
			}
			$i++;
		}
		
		if(isset($_POST['order'])) // here order processing
		{
			$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
		} 
		else if(isset($this->order))
		{
			$order = $this->order;
			$this->db->order_by(key($order), $order[key($order)]);
		}
	}

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

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

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

	public function xss_html_filter($input){
		return $this->security->xss_clean(html_escape($input));
	}

	//Save Cutomers
	public function verify_save_and_update(){
		//Filtering XSS and html escape from user inputs 
		extract($this->xss_html_filter(array_merge($this->data,$_POST,$_GET)));
		//echo "<pre>";print_r($this->xss_html_filter(array_merge($this->data,$_POST,$_GET)));exit();
		
		//varify max sales usage of the package subscription
		validate_package_offers('max_invoices','db_purchase');
		//END

		$this->db->trans_begin();
		$pur_date=system_fromatted_date($pur_date);

		// Helper function to clean and parse numeric values
		function clean_numeric_value($value) {
			if(empty($value) || $value == '' || $value == 0) return null;
			// Remove any formatting (commas, currency symbols, etc.)
			$cleaned = preg_replace('/[^0-9.\-]/', '', $value);
			$num = floatval($cleaned);
			return ($num == 0) ? null : $num;
		}

		// Clean and validate all numeric values
		$tot_subtotal_amt = clean_numeric_value($tot_subtotal_amt);
		$tot_total_amt = clean_numeric_value($tot_total_amt);
		$tot_discount_to_all_amt = clean_numeric_value($tot_discount_to_all_amt);
		$tot_round_off_amt = clean_numeric_value($tot_round_off_amt);
		$other_charges_input = clean_numeric_value($other_charges_input);
		$other_charges_amt = clean_numeric_value($other_charges_amt);
		$discount_to_all_input = clean_numeric_value($discount_to_all_input);

		if($other_charges_tax_id=='' || $other_charges_tax_id==0){$other_charges_tax_id=null;}

	    $prev_item_ids = array();
	    
	    // Get currency information for the supplier (like sales uses customer currency)
	    $transaction_currency_id = null;
	    $exchange_rate = 1.0;
	    $base_currency_total = $tot_total_amt;
	    
	    if (!empty($supplier_id)) {
	        $supplier_currency = get_supplier_trading_currency($supplier_id);
	        $base_currency = get_base_currency();
	        
	        if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
	            $transaction_currency_id = $supplier_currency->id;
	            $exchange_rate = get_exchange_rate($base_currency->id, $supplier_currency->id);
	            $base_currency_total = $tot_total_amt / $exchange_rate;
	        }
	    }
	    
	    if($command=='save'){//Create purchase code unique if first time entry
		    
			$this->db->query("ALTER TABLE db_purchase AUTO_INCREMENT = 1");
			
		    $purchase_entry = array(
		    				'purchase_code' 			=> get_init_code('purchase'), 
		    				'count_id' 					=> get_count_id('db_purchase'), 
		    				'reference_no' 				=> $reference_no, 
		    				'purchase_date' 			=> $pur_date,
		    				'purchase_status' 			=> $purchase_status,
		    				'supplier_id' 				=> $supplier_id,
		    				/*Other Charges*/
		    				'other_charges_input' 		=> $other_charges_input,
		    				'other_charges_tax_id' 		=> $other_charges_tax_id,
		    				'other_charges_amt' 		=> $other_charges_amt,
		    				/*Discount*/
		    				'discount_to_all_input' 	=> $discount_to_all_input,
		    				'discount_to_all_type' 		=> $discount_to_all_type,
		    				'tot_discount_to_all_amt' 	=> $tot_discount_to_all_amt,
		    				/*Subtotal & Total */
		    				'subtotal' 					=> ($tot_subtotal_amt !== null) ? $tot_subtotal_amt : 0,
		    				'round_off' 				=> ($tot_round_off_amt !== null) ? $tot_round_off_amt : 0,
		    				'grand_total' 				=> ($tot_total_amt !== null && $tot_total_amt > 0) ? $tot_total_amt : (($tot_subtotal_amt !== null) ? $tot_subtotal_amt : 0),
		    				'purchase_note' 			=> $purchase_note,
		    				/*Currency Info*/
		    				'transaction_currency_id' 	=> $transaction_currency_id,
		    				'exchange_rate' 			=> $exchange_rate,
		    				'base_currency_total' 		=> $base_currency_total,
		    				/*System Info*/
		    				'created_date' 				=> $CUR_DATE,
		    				'created_time' 				=> $CUR_TIME,
		    				'created_by' 				=> $CUR_USERNAME,
		    				'system_ip' 				=> $SYSTEM_IP,
		    				'system_name' 				=> $SYSTEM_NAME,
		    				'status' 					=> 1,
		    			);
		    $purchase_entry['store_id']=(store_module() && is_admin()) ? $store_id : get_current_store_id();  	
		    $purchase_entry['warehouse_id']=(warehouse_module() && warehouse_count()>1) ? $warehouse_id : get_store_warehouse_id();  	
			$q1 = $this->db->insert('db_purchase', $purchase_entry);
			$purchase_id = $this->db->insert_id();
		}
		else if($command=='update'){	
			// Recalculate currency for update (supplier or amounts may have changed)
			$update_transaction_currency_id = null;
			$update_exchange_rate = 1.0;
			$update_base_currency_total = $tot_total_amt;
			
			if (!empty($supplier_id)) {
				$supplier_currency = get_supplier_trading_currency($supplier_id);
				$base_currency = get_base_currency();
				
				if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
					$update_transaction_currency_id = $supplier_currency->id;
					$update_exchange_rate = get_exchange_rate($base_currency->id, $supplier_currency->id);
					$update_base_currency_total = $tot_total_amt / $update_exchange_rate;
				}
			}
			
			$purchase_entry = array(
		    				'reference_no' 				=> $reference_no, 
		    				'purchase_date' 			=> $pur_date,
		    				'purchase_status' 			=> $purchase_status,
		    				'supplier_id' 				=> $supplier_id,
		    				/*'warehouse_id' 				=> $warehouse_id,*/
		    				/*Other Charges*/
		    				'other_charges_input' 		=> $other_charges_input,
		    				'other_charges_tax_id' 		=> $other_charges_tax_id,
		    				'other_charges_amt' 		=> $other_charges_amt,
		    				/*Discount*/
		    				'discount_to_all_input' 	=> $discount_to_all_input,
		    				'discount_to_all_type' 		=> $discount_to_all_type,
		    				'tot_discount_to_all_amt' 	=> $tot_discount_to_all_amt,
		    				/*Subtotal & Total */
		    				'subtotal' 					=> ($tot_subtotal_amt !== null) ? $tot_subtotal_amt : 0,
		    				'round_off' 				=> ($tot_round_off_amt !== null) ? $tot_round_off_amt : 0,
		    				'grand_total' 				=> ($tot_total_amt !== null && $tot_total_amt > 0) ? $tot_total_amt : (($tot_subtotal_amt !== null) ? $tot_subtotal_amt : 0),
		    				'purchase_note' 			=> $purchase_note,
		    				/*Currency Info - Updated on save*/
		    				'transaction_currency_id' 	=> $update_transaction_currency_id,
		    				'exchange_rate' 			=> $update_exchange_rate,
		    				'base_currency_total' 		=> $update_base_currency_total,
		    			);
			$purchase_entry['store_id']=(store_module() && is_admin()) ? $store_id : get_current_store_id();  
			$purchase_entry['warehouse_id']=(warehouse_module() && warehouse_count()>1) ? $warehouse_id : get_store_warehouse_id();  		
			$q1 = $this->db->where('id',$purchase_id)->update('db_purchase', $purchase_entry);

			##############################################START
			//FIND THE PREVIOUSE ITEM LIST ID'S
			$prev_item_ids = $this->db->select("item_id")->from("db_purchaseitems")->where("purchase_id",$purchase_id)->get()->result_array();
			##############################################END

			$q11=$this->db->query("delete from db_purchaseitems where purchase_id='$purchase_id'");
			if(!$q11){
				return "failed";
			}
		}
		//end

		

		//Import post data from form
		for($i=1;$i<=$rowcount;$i++){
		
			if(isset($_REQUEST['tr_item_id_'.$i]) && !empty($_REQUEST['tr_item_id_'.$i])){

				$item_id 			=$this->xss_html_filter(trim($_REQUEST['tr_item_id_'.$i]));
				$purchase_qty		=$this->xss_html_filter(trim($_REQUEST['td_data_'.$i.'_3']));
				$price_per_unit 	=$this->xss_html_filter(trim($_REQUEST['td_data_'.$i.'_4']));
				$tax_id 			=$this->xss_html_filter(trim($_REQUEST['tr_tax_id_'.$i]));
				$tax_amt 			=$this->xss_html_filter(trim($_REQUEST['td_data_'.$i.'_5']));
				$tax_type			=$this->xss_html_filter(trim($_REQUEST['tr_tax_type_'.$i]));
				
				$unit_total_cost	=$this->xss_html_filter(trim($_REQUEST['td_data_'.$i.'_10']));
				$total_cost			=$this->xss_html_filter(trim($_REQUEST['td_data_'.$i.'_9']));
				
				$discount_type 		=$this->xss_html_filter(trim($_REQUEST['item_discount_type_'.$i]));
				$discount_input 	=$this->xss_html_filter(trim($_REQUEST['item_discount_input_'.$i]));
				$discount_amt	    =$this->xss_html_filter(trim($_REQUEST['td_data_'.$i.'_8']));//Amount
				$description		=$this->xss_html_filter(trim($_REQUEST['description_'.$i]));
				
				// Clean and parse numeric values - remove formatting (commas, currency symbols, etc.)
				// Helper function to clean numeric values
				if (!function_exists('clean_numeric_value_purchase_item')) {
					function clean_numeric_value_purchase_item($value) {
						if(empty($value) || $value == '' || $value == 0) return null;
						// Remove any formatting (commas, currency symbols, etc.)
						$cleaned = preg_replace('/[^0-9.\-]/', '', $value);
						$num = floatval($cleaned);
						return ($num == 0) ? null : $num;
					}
				}
				
				// Clean all numeric values before using them
				$unit_total_cost = clean_numeric_value_purchase_item($unit_total_cost);
				$total_cost = clean_numeric_value_purchase_item($total_cost);
				$tax_amt = clean_numeric_value_purchase_item($tax_amt);
				$discount_amt = clean_numeric_value_purchase_item($discount_amt);
				$price_per_unit = clean_numeric_value_purchase_item($price_per_unit);
				
				// Multi-unit support
				$unit_type = isset($_REQUEST['unit_type_'.$i]) ? $this->xss_html_filter(trim($_REQUEST['unit_type_'.$i])) : 'main';
				$purchase_qty_main = null;
				$purchase_qty_alternate = null;
				
				// Get item conversion factor if multi-unit is enabled
				$item_info = $this->db->select('main_unit_id, alternate_unit_id, conversion_factor')->from('db_items')->where('id', $item_id)->get()->row();
				if ($item_info && $item_info->main_unit_id && $item_info->alternate_unit_id && $item_info->conversion_factor > 0) {
					if ($unit_type == 'main') {
						$purchase_qty_main = $purchase_qty;
						$purchase_qty_alternate = $purchase_qty * $item_info->conversion_factor;
					} else {
						$purchase_qty_alternate = $purchase_qty;
						$purchase_qty_main = $purchase_qty / $item_info->conversion_factor;
					}
				} else {
					// No multi-unit, use main unit
					$unit_type = 'main';
					$purchase_qty_main = $purchase_qty;
				}

				// Batch tracking details
				$batch_number = isset($_REQUEST['batch_number_'.$i]) ? $this->xss_html_filter(trim($_REQUEST['batch_number_'.$i])) : '';
				$manufacturing_date = isset($_REQUEST['manufacturing_date_'.$i]) ? $this->xss_html_filter(trim($_REQUEST['manufacturing_date_'.$i])) : '';
				$expiry_date = isset($_REQUEST['expiry_date_'.$i]) ? $this->xss_html_filter(trim($_REQUEST['expiry_date_'.$i])) : '';
				$batch_notes = isset($_REQUEST['batch_notes_'.$i]) ? $this->xss_html_filter(trim($_REQUEST['batch_notes_'.$i])) : '';

				// SERVER-SIDE VALIDATION: Check if batch details are required
				if($purchase_qty > 0){
					// Check if item has batch tracking enabled
					$item_info = $this->db->select('batch_tracking_enabled, item_name')->from('db_items')->where('id', $item_id)->get()->row();
					
					if($item_info && $item_info->batch_tracking_enabled == 1){
						// Batch tracking is enabled - batch details are REQUIRED
						if(empty($batch_number)){
							// Batch number is missing - BLOCK SAVE
							$this->db->trans_rollback();
							$item_name = !empty($item_info->item_name) ? $item_info->item_name : 'Item ID ' . $item_id;
							return "error:Batch details are required for '{$item_name}'. This item has batch tracking enabled. Please add batch number and details before saving.";
						}
					}
				}

				
				// Ensure values are not null or invalid before saving
				if($total_cost === null || $total_cost == 0 || $total_cost == ''){
					// Calculate total_cost if not provided or invalid
					$unit_tax_val = ($unit_tax !== null) ? $unit_tax : 0;
					$price_val = ($price_per_unit !== null) ? $price_per_unit : 0;
					$discount_val = ($discount_amt !== null) ? $discount_amt : 0;
					$qty_val = ($purchase_qty > 0) ? $purchase_qty : 1;
					
					if($tax_type=='Exclusive'){
						$calculated_total = ($price_val * $qty_val) - $discount_val + ($tax_amt !== null ? $tax_amt : 0);
					} else {
						$calculated_total = ($price_val * $qty_val) - $discount_val;
					}
					$total_cost = ($calculated_total > 0) ? $calculated_total : null;
				}
				
				if($unit_total_cost === null || $unit_total_cost == 0 || $unit_total_cost == ''){
					// Calculate unit_total_cost if not provided
					if($total_cost !== null && $purchase_qty > 0){
						$unit_total_cost = $total_cost / $purchase_qty;
					} else {
						$unit_total_cost = null;
					}
				}
				
				$purchaseitems_entry = array(
		    				'purchase_id' 		=> $purchase_id,
		    				'purchase_status'	=> $purchase_status,
		    				'item_id' 			=> $item_id,
		    				'purchase_qty' 		=> $purchase_qty,
		    				'price_per_unit' 	=> ($price_per_unit !== null) ? $price_per_unit : 0,
		    				'tax_id' 			=> $tax_id,
		    				'tax_amt' 			=> ($tax_amt !== null) ? $tax_amt : null,
		    				'tax_type' 			=> $tax_type,
		    				'discount_input' 	=> $discount_input,
		    				'discount_amt' 		=> ($discount_amt !== null) ? $discount_amt : null,
		    				'unit_total_cost' 	=> ($unit_total_cost !== null && $unit_total_cost > 0) ? $unit_total_cost : null,
		    				'total_cost' 		=> ($total_cost !== null && $total_cost > 0) ? $total_cost : null,
		    				'discount_type' 	=> $discount_type,
		    				'description' 		=> $description, 
		    				'status'			=> 1,
		    				
		    				// Batch tracking fields
		    				'batch_number' 		=> $batch_number,
		    				'manufacturing_date' => $manufacturing_date,
		    				'expiry_date' 		=> $expiry_date,
		    				
		    				// Multi-unit fields
		    				'unit_type' 			=> $unit_type,
		    				'purchase_qty_main' 	=> $purchase_qty_main,
		    				'purchase_qty_alternate' => $purchase_qty_alternate,
		    			);
				$purchaseitems_entry['store_id']=(store_module() && is_admin()) ? $store_id : get_current_store_id();  	
				
				$q2 = $this->db->insert('db_purchaseitems', $purchaseitems_entry);
				
				// Create batch record in db_item_batches if batch tracking is enabled
				// Use purchase_qty_main for multi-unit items (stock is always tracked in main unit)
				$batch_qty = !empty($purchase_qty_main) ? $purchase_qty_main : $purchase_qty;
				
				if(!empty($batch_number) && $batch_qty > 0){
					// Check if item has batch tracking enabled
					$item_info = $this->db->select('batch_tracking_enabled')->from('db_items')->where('id', $item_id)->get()->row();
					
					if($item_info && $item_info->batch_tracking_enabled == 1){
						// Check if batch already exists in db_item_batches
						$existing_batch = $this->db->select('id, remaining_quantity, quantity')
							->from('db_item_batches')
							->where('item_id', $item_id)
							->where('batch_number', $batch_number)
							->where('status', 1)
							->get()
							->row();
						
						if($existing_batch){
							// Batch exists - update remaining quantity by adding new purchase quantity
							$new_remaining = $existing_batch->remaining_quantity + $batch_qty;
							$new_quantity = $existing_batch->quantity + $batch_qty;
							$this->db->where('id', $existing_batch->id)
								->update('db_item_batches', array(
									'remaining_quantity' => $new_remaining,
									'quantity' => $new_quantity,
									'purchase_price' => ($price_per_unit !== null) ? $price_per_unit : 0
								));
							log_message('debug', "Purchase: Updated existing batch {$batch_number} for item {$item_id} - Added {$batch_qty}, New remaining: {$new_remaining}");
						} else {
							// Batch doesn't exist - create new batch record
							$warehouse_id_for_batch = (warehouse_module() && warehouse_count()>1) ? $warehouse_id : get_store_warehouse_id();
							$store_id_for_batch = (store_module() && is_admin()) ? $store_id : get_current_store_id();
							
							$batch_data = array(
								'item_id' => $item_id,
								'store_id' => $store_id_for_batch,
								'warehouse_id' => $warehouse_id_for_batch,
								'batch_number' => $batch_number,
								'manufacturing_date' => !empty($manufacturing_date) ? $manufacturing_date : null,
								'expiry_date' => !empty($expiry_date) ? $expiry_date : null,
								'quantity' => $batch_qty,
								'remaining_quantity' => $batch_qty,
								'purchase_price' => ($price_per_unit !== null) ? $price_per_unit : 0,
								'created_date' => date('Y-m-d'),
								'created_time' => date('H:i:s'),
								'created_by' => get_current_user_id(),
								'status' => 1
							);
							
							$this->db->insert('db_item_batches', $batch_data);
							log_message('debug', "Purchase: Created new batch {$batch_number} for item {$item_id} with quantity {$batch_qty}");
						}
					}
				}
				
				//UPDATE itemS QUANTITY IN itemS TABLE
				$this->load->model('pos_model');				
				$q6=$this->pos_model->update_items_quantity($item_id);
				if(!$q6){
					return "failed";
				}

				
			}
		
		}//for end

		if($amount=='' || $amount==0){$amount=null;}
		if($amount>0 && !empty($payment_type)){

			if($amount>$tot_total_amt){
				echo "Payble amount should not be exceeds Invoice Amount!!";exit;
			}

			/**
			 * @update
			 * Verifieng previous and current payment total with invoice amount
			*/
			if($command=='update'){
				$tot_payment = $this->db->select('coalesce(sum(payment),0) as payment')->where('purchase_id',$purchase_id)->get('db_purchasepayments')->row()->payment;
				if(($tot_payment+$amount)>$tot_total_amt){
					echo "Payble amount should not be exceeds Invoice Amount!!\nPlease check previous payments as well.";exit;
				}
			}


			$payment_code=get_init_code('purchase_payment');
			$purchasepayments_entry = array(
					'payment_code' 		=> $payment_code,
		    		'count_id'	  		=> get_count_id('db_purchasepayments'),
					'purchase_id' 		=> $purchase_id, 
					'payment_date'		=> $pur_date,//Current Payment with Purchase entry
					'payment_type' 		=> $payment_type,
					'payment' 			=> $amount,
					'payment_note' 		=> $payment_note,
					'created_date' 		=> $CUR_DATE,
    				'created_time' 		=> $CUR_TIME,
    				'created_by' 		=> $CUR_USERNAME,
    				'system_ip' 		=> $SYSTEM_IP,
    				'system_name' 		=> $SYSTEM_NAME,
    				'status' 			=> 1,
    				'account_id' 		=> (empty($account_id)) ? null : $account_id,
    				'supplier_id' 		=> $supplier_id,
				);
			$purchasepayments_entry['store_id']=(store_module() && is_admin()) ? $store_id : get_current_store_id();  	
			$q3 = $this->db->insert('db_purchasepayments', $purchasepayments_entry);

			//Set the payment to specified account
			if(!empty($account_id)){
				//ACCOUNT INSERT
				$insert_bit = insert_account_transaction(array(
															'transaction_type'  	=> 'PURCHASE PAYMENT',
															'reference_table_id'  	=> $this->db->insert_id(),
															'debit_account_id'  	=> $account_id,
															'credit_account_id'  	=> null,
															'debit_amt'  			=> $amount,
															'credit_amt'  			=> 0,
															'process'  				=> 'SAVE',
															'note'  				=> $payment_note,
															'transaction_date'  	=> $CUR_DATE,
															'payment_code'  		=> $payment_code,
															'customer_id'  			=> null,
															'supplier_id'  			=> $supplier_id,
													));
				if(!$insert_bit){
					return "failed";
				}
			}
			//end
			
		}
		
		$q10=$this->update_purchase_payment_status($purchase_id);
		if($q10!=1){
			return "failed";
		}

		##############################################START
		//FIND THE PREVIOUSE ITEM LIST ID'S
		$curr_item_ids = $this->db->select("item_id")->from("db_purchaseitems")->where("purchase_id",$purchase_id)->get()->result_array();
		$two_array = array_merge($prev_item_ids,$curr_item_ids);

		/*Update items in all warehouses of the item*/
		$q7=update_warehouse_items($two_array);
		if(!$q7){
			return "failed";
		}
		##############################################END
		
		$this->db->trans_commit();
		$this->session->set_flashdata('success', 'Success!! Record Saved Successfully!');
		return "success<<<###>>>$purchase_id";
		
	}//verify_save_and_update() function end

	public function delete_payment($payment_id){
        $this->db->trans_begin();
        
        // Get purchase_id before deleting payment
		$purchase_id = $this->db->query("select purchase_id from db_purchasepayments where id=$payment_id")->row()->purchase_id;
        
        // Get account information before deleting
		$reset_accounts = $this->db->select("debit_account_id,credit_account_id")
									->where("ref_purchasepayments_id", $payment_id)
									->group_by("debit_account_id,credit_account_id")
									->get("ac_transactions");

		// Delete account transactions first
		$q3 = $this->db->query("delete from ac_transactions where ref_purchasepayments_id='$payment_id'");
		
		// Delete payment record
		$q1=$this->db->query("delete from db_purchasepayments where id='$payment_id'");
		$q2=$this->update_purchase_payment_status($purchase_id);

		// Update account balances
        if($reset_accounts->num_rows()>0){
        	foreach ($reset_accounts->result() as $res1) {
        		if($res1->debit_account_id && !update_account_balance($res1->debit_account_id)){
					$this->db->trans_rollback();
					return 'failed';
				}

				if($res1->credit_account_id && !update_account_balance($res1->credit_account_id)){
					$this->db->trans_rollback();
					return 'failed';
				}
        	}
        }

		if($q1!=1 || $q2!=1)
		{
			$this->db->trans_rollback();
		    return "failed";
		}
		else{
			$this->db->trans_commit();
		        return "success";
		}
	}

	public function update_purchase_payment_status_by_purchase_id($purchase_id){
		$q8=$this->db->query("select COALESCE(SUM(payment),0) as payment from db_purchasepayments where purchase_id='$purchase_id'");
		$sum_of_payments=$q8->row()->payment;
		

		$q9=$this->db->query("select coalesce(grand_total,0) as total from db_purchase where id='$purchase_id'");
		$payble_total=$q9->row()->total;
		
		//$pending_amt=$payble_total-$sum_of_payments;

		$payment_status='';
		if($payble_total==$sum_of_payments){
			$payment_status="Paid";
		}
		else if($sum_of_payments!=0 && ($sum_of_payments<$payble_total)){
			$payment_status="Partial";
		}
		else if($sum_of_payments==0){
			$payment_status="Unpaid";
		}


		$q7=$this->db->query("update db_purchase set 
							payment_status='$payment_status',
							paid_amount=$sum_of_payments 
							where id='$purchase_id'");
		$supplier_id =$this->db->query("select supplier_id from db_purchase where id=$purchase_id")->row()->supplier_id;

		$purchase_due =$this->db->query("select COALESCE(SUM(grand_total),0)-COALESCE(SUM(paid_amount),0) as purchase_due from db_purchase where supplier_id=$supplier_id and purchase_status='Received'")->row()->purchase_due;
		
		$q12 = $this->db->query("update db_suppliers set purchase_due=$purchase_due where id=$supplier_id");
		if(!$q7 || !$q12)
		{
			return false;
		}
		else{
			return true;
		}
	}

	function update_purchase_payment_status($purchase_id=null){
	//UPDATE PRODUCTS QUANTITY IN PRODUCTS TABLE
		if(empty($purchase_id)){ //If purchase ID not exist you need setup all the suppliers purchase due
			$q11=$this->db->query("select id from db_suppliers");
			if($q11->num_rows()>0){
				foreach ($q11->result() as $res) {
					$q12=$this->db->query("select id from db_purchase where supplier_id=".$res->id);
					if($q12->num_rows()>0){
						foreach ($q12->result() as $res12) {
							if(!$this->update_purchase_payment_status_by_purchase_id($res12->id)){
								return false;
							}
						}
					}
					else{
						$q13=$this->db->query("update db_suppliers set purchase_due=0 where id=".$res->id);
						if(!$q13){
							return false;
						}
					}
				}
			}
			return true;
		}
		else{
					if(!$this->update_purchase_payment_status_by_purchase_id($purchase_id)){
						return false;
					}
					return true;
		}
	}

	function fun_temp_update_suppliers_purchase_due(){
		
		
		$q11=$this->db->query("select id from db_suppliers");
		if($q11->num_rows()>0){
			foreach ($q11->result() as $res) {

				$q12=$this->db->query("select id from db_purchase where supplier_id=".$res->id);
				if($q12->num_rows()>0){
					foreach ($q12->result() as $res12) {
						if(!$this->purchase_model->update_purchase_payment_status($res12->id)){
							return false;
						}
					}
				}
				else{
					$q13=$this->db->query("update db_suppliers set purchase_due=0 where id=".$res->id);
					if(!$q13){
						return false;
					}
				}
			}
		}
		return true;
	}



	public function delete_purchase($ids){
      	$this->db->trans_begin();

      	//ACCOUNT RESET
		$reset_accounts = $this->db->select("debit_account_id,credit_account_id")
									->where("ref_purchasepayments_id in ($ids)")
									->group_by("debit_account_id,credit_account_id")
									->get("ac_transactions");
		//ACCOUNT RESET END

      	##############################################START
		//FIND THE PREVIOUS ITEM LIST ID'S - Get unique item IDs
		$prev_item_ids_result = $this->db->select("item_id")
										  ->from("db_purchaseitems")
										  ->where("purchase_id in ($ids)")
										  ->distinct()
										  ->get()
										  ->result_array();
		$prev_item_ids = array_map(function($row) { return $row['item_id']; }, $prev_item_ids_result);
		##############################################END

		// Get unique supplier IDs from deleted purchases - for optimized payment status update
		$supplier_ids_result = $this->db->select("supplier_id")
										->from("db_purchase")
										->where("id in ($ids)")
										->distinct()
										->get()
										->result_array();
		$supplier_ids = array_map(function($row) { return $row['supplier_id']; }, $supplier_ids_result);

		// Check if any items from this purchase have been sold
		$sold_items_check = $this->db->query("
			SELECT DISTINCT pi.item_id, pi.batch_number, pi.manufacturing_date, pi.expiry_date, i.item_name
			FROM db_purchaseitems pi 
			JOIN db_items i ON i.id = pi.item_id
			WHERE pi.purchase_id IN ($ids) 
			AND pi.batch_number IS NOT NULL 
			AND pi.batch_number != ''
			AND EXISTS (
				SELECT 1 FROM db_salesitems si 
				WHERE si.item_id = pi.item_id 
				AND si.batch_number = pi.batch_number
				AND si.status = 1
			)
		");

		if($sold_items_check->num_rows() > 0){
			$i = 1;
			echo "Sorry! Cannot delete purchase with batch details that have been sold:<br>";
			foreach($sold_items_check->result() as $res){
				echo $i++ . ". " . $res->item_name . " (Batch: " . $res->batch_number . ")<br>";
			}
			echo "<br>Please delete the sales records first before deleting this purchase.";
			exit();
		}

		$q8=$this->db->query("SELECT COUNT(*) AS tot_invoices,a.purchase_id,b.purchase_code FROM db_purchasereturn AS a INNER JOIN db_purchase AS b ON b.id=a.purchase_id WHERE purchase_id IN($ids) GROUP BY purchase_id");

		if($q8->num_rows()>0){
			$i=1;
			echo "Sorry! Records Not Deleted! Return Invoices Found Against Purchases:";
			foreach($q8->result() as $res){
				echo "<br>".$i++.".Return Invoice Against Purchase Id:".$res->purchase_code;
			}
			echo "<br>To Delete Purchase! You need to Delete Purchase Return Invoices!";
			exit();
		}
		
		#----------------------------------
		$this->db->where("id in ($ids)");
		//if not admin
		if(!is_admin()){
			$this->db->where("store_id",get_current_store_id());
		}

		$q3=$this->db->delete("db_purchase");
		#----------------------------------
		#----------------------------------
		$this->db->where("purchase_id in ($ids)");
		//if not admin
		if(!is_admin()){
			$this->db->where("store_id",get_current_store_id());
		}

		$q5=$this->db->delete("db_purchasepayments");
		#----------------------------------
		
		// Get batch details from purchase items BEFORE deleting them
		$this->db->where("purchase_id in ($ids)");
		if(!is_admin()){
			$this->db->where("store_id",get_current_store_id());
		}
		$purchase_batch_items = $this->db->select("item_id, batch_number")
			->from("db_purchaseitems")
			->where("batch_number IS NOT NULL")
			->where("batch_number != ''")
			->get()
			->result();
		
		$this->db->where("purchase_id in ($ids)");
		//if not admin
		if(!is_admin()){
			$this->db->where("store_id",get_current_store_id());
		}
		$q7=$this->db->delete("db_purchaseitems");
		#----------------------------------

		// Clean up batch entries in db_item_batches that were created from these purchase batches
		// Only delete if the batch hasn't been sold AND doesn't exist in other purchases
		if(!empty($purchase_batch_items)){
			foreach ($purchase_batch_items as $batch_item) {
				// Check if this batch has been sold
				$sold_check = $this->db->select('id')
					->from('db_salesitems')
					->where('item_id', $batch_item->item_id)
					->where('batch_number', $batch_item->batch_number)
					->where('status', 1)
					->get()
					->row();
				
				// Check if this batch exists in other purchases (not being deleted)
				$other_purchase_check = $this->db->select('id')
					->from('db_purchaseitems')
					->where('item_id', $batch_item->item_id)
					->where('batch_number', $batch_item->batch_number)
					->where('purchase_id NOT IN', "($ids)", FALSE)
					->where('batch_number IS NOT NULL')
					->where('batch_number !=', '')
					->get()
					->row();
				
				if (!$sold_check && !$other_purchase_check) {
					// Batch hasn't been sold and doesn't exist in other purchases, safe to delete from db_item_batches
					$this->db->where('item_id', $batch_item->item_id)
						->where('batch_number', $batch_item->batch_number)
						->delete('db_item_batches');
					
					log_message('debug', "Purchase delete: Removed batch {$batch_item->batch_number} for item {$batch_item->item_id} from db_item_batches");
				} else {
					if ($sold_check) {
						// Batch has been sold, keep the entry but update remaining quantity from remaining purchase items
						log_message('debug', "Purchase delete: Kept batch {$batch_item->batch_number} for item {$batch_item->item_id} in db_item_batches (has sales)");
						
						// Recalculate remaining quantity from remaining purchases
						$remaining_purchase_qty = $this->db->select_sum('purchase_qty')
							->from('db_purchaseitems')
							->where('item_id', $batch_item->item_id)
							->where('batch_number', $batch_item->batch_number)
							->where('batch_number IS NOT NULL')
							->where('batch_number !=', '')
							->get()
							->row();
						
						$total_sold_qty = $this->db->select_sum('sales_qty')
							->from('db_salesitems')
							->where('item_id', $batch_item->item_id)
							->where('batch_number', $batch_item->batch_number)
							->where('status', 1)
							->get()
							->row();
						
						$new_remaining = max(0, ($remaining_purchase_qty->purchase_qty ?? 0) - ($total_sold_qty->sales_qty ?? 0));
						
						// Update the batch remaining quantity
						$this->db->where('item_id', $batch_item->item_id)
							->where('batch_number', $batch_item->batch_number)
							->update('db_item_batches', array('remaining_quantity' => $new_remaining));
						
						log_message('debug', "Purchase delete: Updated batch {$batch_item->batch_number} remaining_quantity to {$new_remaining}");
					} else {
						// Batch exists in other purchases, keep the entry
						log_message('debug', "Purchase delete: Kept batch {$batch_item->batch_number} for item {$batch_item->item_id} in db_item_batches (exists in other purchases)");
					}
				}
			}
		}

		// OPTIMIZED: Only update items that were actually in the deleted purchase
		if(!empty($prev_item_ids)){
			$this->load->model('pos_model');
			$unique_item_ids = array_unique($prev_item_ids);
			foreach ($unique_item_ids as $item_id) {
				if(!$this->pos_model->update_items_quantity($item_id)){
					$this->db->trans_rollback();
					return "failed";
				}
			}
		}

		##############################################START
		/*Update items in all warehouses of the item*/
		if(!empty($prev_item_ids)){
			// Convert to the format expected by update_warehouse_items (array of arrays)
			$prev_item_ids_formatted = array();
			foreach(array_unique($prev_item_ids) as $item_id){
				$prev_item_ids_formatted[] = array($item_id);
			}
			$q7=update_warehouse_items($prev_item_ids_formatted);
			if(!$q7){
				$this->db->trans_rollback();
				return "failed";
			}
		}
		##############################################END
		
		// OPTIMIZED: Only update payment status for affected suppliers
		// Recalculate purchase_due for each affected supplier
		if(!empty($supplier_ids)){
			foreach($supplier_ids as $supplier_id){
				// Recalculate supplier's purchase_due from remaining purchases
				$this->db->select("COALESCE(SUM(grand_total),0)-COALESCE(SUM(paid_amount),0) as purchase_due");
				$this->db->from("db_purchase");
				$this->db->where("supplier_id", $supplier_id);
				$this->db->where("purchase_status", "Received");
				$purchase_due_result = $this->db->get()->row();
				$purchase_due = $purchase_due_result ? $purchase_due_result->purchase_due : 0;
				
				$update_result = $this->db->where("id", $supplier_id)
										   ->update("db_suppliers", ["purchase_due" => $purchase_due]);
				if(!$update_result){
					$this->db->trans_rollback();
					return "failed";
				}
			}
		}

		//ACCOUNT RESET
        if($reset_accounts->num_rows()>0){
        	foreach ($reset_accounts->result() as $res1) {
        		if($res1->debit_account_id && !update_account_balance($res1->debit_account_id)){
					$this->db->trans_rollback();
					return 'failed';
				}

				if($res1->credit_account_id && !update_account_balance($res1->credit_account_id)){
					$this->db->trans_rollback();
					return 'failed';
				}

        	}
        }
        //ACCOUNT RESET END

		if($q3 == false || $q5 == false)
		{
			$this->db->trans_rollback();
		    return "failed";
		}
		else{
			// Update related requisitions to revert to Approved status
			$this->db->where("converted_to_purchase_id IN ($ids)")
					 ->update("db_purchase_requisitions", [
					     'status' => 'Approved',
					     'converted_to_purchase_id' => NULL,
					     'updated_date' => date('Y-m-d H:i:s')
					 ]);
			
			$this->db->trans_commit();
		        return "success";
		}
	}
	public function search_item($q){
		$json_array=array();
        $query1="select id,item_name from db_items where (upper(item_name) like upper('%$q%') or upper(item_code) like upper('%$q%')) and store_id=$store_id";

        $q1=$this->db->query($query1);
        if($q1->num_rows()>0){
            foreach ($q1->result() as $value) {
            	$json_array[]=['id'=>$value->id, 'text'=>$value->item_name];
            }
        }
        return json_encode($json_array);
	}
	
	public function find_item_details($id){
		$json_array=array();
        $query1="select id,item_name,tax_id,sales_price,price,stock,tax_type,profit_margin from db_items where id=$id";

        $q1=$this->db->query($query1);
        if($q1->num_rows()>0){
            foreach ($q1->result() as $value) {
            	$json_array=['id'=>$value->id, 
        			 'item_name'=>$value->item_name,
        			 'purchase_price'=>$value->price,
        			 'sales_price'=>$value->sales_price,
        			 'tax_id'=>$value->tax_id,
        			 'stock'=>$value->stock,
        			 'profit_margin'=>$value->profit_margin,
        			 'tax_type'=>$value->tax_type,
        			];
            }
        }
        return json_encode($json_array);
	}

	

	
	public function inclusive($price='',$tax_per){
		return $price/(($tax_per/100)+1)/10;
	}

	
	public function get_items_info($rowcount,$item_id){
		extract($_POST);
		
		$res1=$this->db->select('*')->from('db_items')->where("id=$item_id")->get()->row();
		$q3=$this->db->query("select * from db_tax where id=".$res1->tax_id)->row();
		
		$purchase_price = $res1->purchase_price;
		$converted_price = $purchase_price;
		$exchange_rate = 1.0;
		$currency_symbol = '';
		$currency_code = '';
		
		// Currency conversion for supplier's trading currency
		if (!empty($supplier_id)) {
			$supplier_currency = get_supplier_trading_currency($supplier_id);
			$base_currency = get_base_currency();
			
			if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
				$exchange_rate = get_exchange_rate($base_currency->id, $supplier_currency->id);
				
				if ($exchange_rate != 1.0) {
					$converted_price = $purchase_price * $exchange_rate;
					$converted_price = number_format($converted_price, decimals(), '.', '');
					$currency_symbol = $supplier_currency->symbol;
					$currency_code = $supplier_currency->currency_code;
				}
			}
		}
		
		$item_tax_amt = ($res1->tax_type=='Inclusive') ? calculate_inclusive($converted_price,$q3->tax) :calculate_exclusive($converted_price,$q3->tax);

		// Multi-unit information
		$main_unit_id = isset($res1->main_unit_id) ? $res1->main_unit_id : null;
		$alternate_unit_id = isset($res1->alternate_unit_id) ? $res1->alternate_unit_id : null;
		$conversion_factor = isset($res1->conversion_factor) ? $res1->conversion_factor : 1.0;
		$purchase_price_main = isset($res1->purchase_price_main) ? $res1->purchase_price_main : null;
		$purchase_price_alternate = isset($res1->purchase_price_alternate) ? $res1->purchase_price_alternate : null;
		
		// Get unit names
		$main_unit_name = '';
		$alternate_unit_name = '';
		if ($main_unit_id) {
			$main_unit = $this->db->select('unit_name')->where('id', $main_unit_id)->get('db_units')->row();
			$main_unit_name = $main_unit ? $main_unit->unit_name : '';
		}
		if ($alternate_unit_id) {
			$alternate_unit = $this->db->select('unit_name')->where('id', $alternate_unit_id)->get('db_units')->row();
			$alternate_unit_name = $alternate_unit ? $alternate_unit->unit_name : '';
		}

		$info = array(
							'item_id' 					=> $res1->id, 
							'description' 				=> '', 
							'item_name' 				=> $res1->item_name,
							'item_available_qty' 		=> $res1->stock,
							'item_price' 				=> $res1->sales_price, 
							'item_purchase_price' 		=> $converted_price, 
							'item_base_price' 			=> $purchase_price, 
							'item_currency_symbol' 		=> $currency_symbol, 
							'item_currency_code' 		=> $currency_code, 
							'item_exchange_rate' 		=> $exchange_rate, 
							'item_tax_name' 			=> $q3->tax_name, 
							'item_purchase_qty' 		=> 1, 
							'item_tax_id' 				=> $res1->tax_id, 
							'item_tax' 					=> $q3->tax, 
							'item_tax_type' 			=> $res1->tax_type, 
							'item_tax_amt' 				=> $item_tax_amt, 
							'item_discount' 			=> 0, 
							'item_discount_type' 		=> 'Percentage', 
							'item_discount_input' 		=> 0,
							'service_bit' 				=> $res1->service_bit,
							// Batch tracking information
							'batch_tracking_enabled' 	=> isset($res1->batch_tracking_enabled) ? $res1->batch_tracking_enabled : 0,
							'tracking_type' 				=> isset($res1->tracking_type) ? $res1->tracking_type : 'none',
							'expiry_enabled' 			=> isset($res1->expiry_enabled) ? $res1->expiry_enabled : 0,
							// Multi-unit information
							'main_unit_id' 				=> $main_unit_id,
							'alternate_unit_id' 		=> $alternate_unit_id,
							'conversion_factor' 		=> $conversion_factor,
							'purchase_price_main' 		=> $purchase_price_main,
							'purchase_price_alternate' 	=> $purchase_price_alternate,
							'main_unit_name' 			=> $main_unit_name,
							'alternate_unit_name' 		=> $alternate_unit_name,
						);

		$this->return_row_with_data($rowcount,$info);
	}

	/* For Purchase Items List Retrieve*/
	public function return_purchase_list($purchase_id){
		$q1=$this->db->select('*')->from('db_purchaseitems')->where("purchase_id=$purchase_id")->get();
		$rowcount =1;
		foreach ($q1->result() as $res1) {
			$res2=$this->db->query("select * from db_items where id=".$res1->item_id)->row();
			$q3=$this->db->query("select * from db_tax where id=".$res1->tax_id)->row();
			
			
			$info = array(
							'item_id' 					=> $res1->item_id, 
							'description' 				=> $res1->description, 
							'item_name' 				=> $res2->item_name,
							'item_available_qty' 		=> $res2->stock,
							'item_price' 				=> $res2->price, 
							'item_purchase_price' 		=> $res1->price_per_unit, 
							'item_tax_name' 			=> $q3->tax_name, 
							'item_purchase_qty' 		=> $res1->purchase_qty, 
							'item_tax_id' 				=> $res1->tax_id, 
							'item_tax' 					=> $q3->tax, 
							'item_tax_type' 			=> $res1->tax_type, 
							'item_tax_amt' 				=> $res1->tax_amt, 
							'item_discount' 			=> $res1->discount_input, 
							'item_discount_type' 		=> $res1->discount_type, 
							'item_discount_input' 		=> $res1->discount_input, 
							'discount_amt' 				=> isset($res1->discount_amt) ? $res1->discount_amt : 0,
							'total_cost' 				=> isset($res1->total_cost) ? $res1->total_cost : null,
							'unit_total_cost' 			=> isset($res1->unit_total_cost) ? $res1->unit_total_cost : null,
							'service_bit' 				=> $res2->service_bit,
							// Batch tracking information from items table
							'batch_tracking_enabled' 	=> isset($res2->batch_tracking_enabled) ? $res2->batch_tracking_enabled : 0,
							'tracking_type' 				=> isset($res2->tracking_type) ? $res2->tracking_type : 'none',
							'expiry_enabled' 			=> isset($res2->expiry_enabled) ? $res2->expiry_enabled : 0,
							// Batch details from purchase items table
							'batch_number' 				=> isset($res1->batch_number) ? $res1->batch_number : '',
							'manufacturing_date' 		=> isset($res1->manufacturing_date) ? $res1->manufacturing_date : '',
							'expiry_date' 				=> isset($res1->expiry_date) ? $res1->expiry_date : '',
							// Multi-unit information
							'main_unit_id' 				=> isset($res2->main_unit_id) ? $res2->main_unit_id : null,
							'alternate_unit_id' 		=> isset($res2->alternate_unit_id) ? $res2->alternate_unit_id : null,
							'conversion_factor' 		=> isset($res2->conversion_factor) ? $res2->conversion_factor : 1.0,
							'purchase_price_main' 		=> isset($res2->purchase_price_main) ? $res2->purchase_price_main : null,
							'purchase_price_alternate' 	=> isset($res2->purchase_price_alternate) ? $res2->purchase_price_alternate : null,
							'unit_type' 				=> isset($res1->unit_type) ? $res1->unit_type : 'main',
						);
			
			// Get unit names
			if (!empty($info['main_unit_id'])) {
				$main_unit = $this->db->select('unit_name')->where('id', $info['main_unit_id'])->get('db_units')->row();
				$info['main_unit_name'] = $main_unit ? $main_unit->unit_name : '';
			} else {
				$info['main_unit_name'] = '';
			}
			if (!empty($info['alternate_unit_id'])) {
				$alternate_unit = $this->db->select('unit_name')->where('id', $info['alternate_unit_id'])->get('db_units')->row();
				$info['alternate_unit_name'] = $alternate_unit ? $alternate_unit->unit_name : '';
			} else {
				$info['alternate_unit_name'] = '';
			}

			$result = $this->return_row_with_data($rowcount++,$info);
		}
		return $result;
	}

	public function return_row_with_data($rowcount,$info){
		extract($info);
		
		// Use actual saved values from database instead of recalculating
		// This ensures we display the exact values that were saved
		if(isset($total_cost) && $total_cost > 0){
			$item_amount = $total_cost;
		} else {
			// Fallback calculation if total_cost not available
			$discount_amt_value = isset($discount_amt) ? $discount_amt : 0;
			if($item_tax_type == 'Inclusive'){
				$item_amount = ($item_purchase_price * $item_purchase_qty) - $discount_amt_value;
			} else {
				$item_amount = ($item_purchase_price * $item_purchase_qty) - $discount_amt_value + $item_tax_amt;
			}
		}
		
		// Calculate original taxable amount for data attribute
		$original_taxable = 0;
		if ($item_amount > 0) {
			if ($item_tax_type == 'Exclusive') {
				$original_taxable = $item_amount - $item_tax_amt;
			} else { // Inclusive
				$original_taxable = $item_amount; // For inclusive, total_cost is the taxable base
			}
		}
		
		if(isset($unit_total_cost) && $unit_total_cost > 0){
			$item_unit_cost = $unit_total_cost;
		} else {
			// Fallback calculation
			$item_unit_cost = ($item_amount / max($item_purchase_qty, 1));
		}
	
		?>
            <tr id="row_<?=$rowcount;?>" data-row='<?=$rowcount;?>'>
               <td id="td_<?=$rowcount;?>_1">
                  <label class='form-control' style='height:auto;' data-toggle="tooltip" title='Edit ?' >
                  <a id="td_data_<?=$rowcount;?>_1" href="javascript:void()" onclick="show_purchase_item_modal(<?=$rowcount;?>)" title=""><?=$item_name;?></a> 
                  		<i onclick="show_purchase_item_modal(<?=$rowcount;?>)" class="fa fa-edit pointer"></i>
                  		<?php if (isset($batch_tracking_enabled) && $batch_tracking_enabled == 1): ?>
                  		<i onclick="show_batch_details_modal(<?=$rowcount;?>, <?=$item_id;?>)" class="fa fa-cubes pointer text-warning" style="margin-left: 5px;" title="Add Batch Details"></i>
                  		<?php endif; ?>
                  		<?php 
                  		// Display existing batch details ONLY if batch tracking is enabled
                  		$batch_display = '';
                  		if (isset($batch_tracking_enabled) && $batch_tracking_enabled == 1) {
                  		    if (isset($batch_number) && !empty($batch_number)) {
                  		        $batch_display .= '<br><small class="text-info"><strong>Batch:</strong> ' . $batch_number . '</small>';
                  		    }
                  		    if (isset($manufacturing_date) && !empty($manufacturing_date) && $manufacturing_date != '0000-00-00') {
                  		        $formatted_mfg_date = date('m/d/Y', strtotime($manufacturing_date));
                  		        $batch_display .= '<br><small class="text-info"><strong>MFG:</strong> ' . $formatted_mfg_date . '</small>';
                  		    }
                  		    if (isset($expiry_date) && !empty($expiry_date) && $expiry_date != '0000-00-00') {
                  		        $formatted_exp_date = date('m/d/Y', strtotime($expiry_date));
                  		        $batch_display .= '<br><small class="text-warning"><strong>EXP:</strong> ' . $formatted_exp_date . '</small>';
                  		    }
                  		}
                  		if (!empty($batch_display)) {
                  		    echo $batch_display;
                  		}
                  		?>
                  	</label>
               </td>
               <!-- Qty with Unit Selector -->
               <td id="td_<?=$rowcount;?>_3">
                  <div class="input-group">
                     <span class="input-group-btn">
                     <button onclick="decrement_qty(<?=$rowcount;?>)" type="button" class="btn btn-default btn-flat"><i class="fa fa-minus text-danger"></i></button></span>
                     <input type="text" value="<?=format_qty($item_purchase_qty);?>" class="form-control no-padding text-center" onkeyup="calculate_tax(<?=$rowcount;?>); updateUnitConversion(<?=$rowcount;?>);" id="td_data_<?=$rowcount;?>_3" name="td_data_<?=$rowcount;?>_3">
                     <span class="input-group-btn">
                     <button onclick="increment_qty(<?=$rowcount;?>)" type="button" class="btn btn-default btn-flat"><i class="fa fa-plus text-success"></i></button></span>
                  </div>
                  <?php if (isset($main_unit_id) && isset($alternate_unit_id) && $main_unit_id && $alternate_unit_id): ?>
                  <?php 
                  $initial_unit_type = (!isset($unit_type) || $unit_type == 'main') ? 'main' : 'alternate';
                  ?>
                  <div class="input-group" style="margin-top: 5px;">
                     <select class="form-control input-sm" id="unit_type_<?=$rowcount;?>" name="unit_type_<?=$rowcount;?>" data-previous-unit="<?=$initial_unit_type;?>" onfocus="$(this).data('previous-unit', $(this).val());" onchange="updateUnitPriceWithPrevious(<?=$rowcount;?>); updateUnitConversion(<?=$rowcount;?>);" style="font-size: 11px;">
                        <option value="main" <?php echo ($initial_unit_type == 'main') ? 'selected' : ''; ?>>Main (<?=$main_unit_name;?>)</option>
                        <option value="alternate" <?php echo ($initial_unit_type == 'alternate') ? 'selected' : ''; ?>>Alt (<?=$alternate_unit_name;?>)</option>
                     </select>
                  </div>
                  <script>
                  $(document).ready(function() {
                      // Initialize previous unit type on page load
                      $("#unit_type_<?=$rowcount;?>").data('previous-unit', '<?=$initial_unit_type;?>');
                  });
                  </script>
                  <?php else: ?>
                  <input type="hidden" id="unit_type_<?=$rowcount;?>" name="unit_type_<?=$rowcount;?>" value="main" data-previous-unit="main">
                  <?php endif; ?>
               </td>
               <!-- Purchase Price -->
               <td id="td_<?=$rowcount;?>_4"><input type="text" name="td_data_<?=$rowcount;?>_4" id="td_data_<?=$rowcount;?>_4" class="form-control text-right no-padding only_currency text-center" onfocus="if(this.value=='0' || this.value=='0.00'){this.value='';this.select();}" onkeyup="calculate_tax(<?=$rowcount;?>);" onblur="if(this.value==''){this.value='0';} calculate_tax(<?=$rowcount;?>);" value="<?=store_number_format($item_purchase_price,0);?>" ></td>

              
               <!-- Discount -->
               <td id="td_<?=$rowcount;?>_8">
                  <input type="text" data-toggle="tooltip" title="Click to Change" name="td_data_<?=$rowcount;?>_8" id="td_data_<?=$rowcount;?>_8" class="pointer form-control text-right no-padding only_currency text-center item_discount" value="<?=store_number_format(isset($discount_amt) ? $discount_amt : 0,0);?>" onclick="show_purchase_item_modal(<?=$rowcount;?>)" readonly>
               </td>

               <!-- Tax Amount -->
               <td id="td_<?=$rowcount;?>_5"><input type="text" name="td_data_<?=$rowcount;?>_5" id="td_data_<?=$rowcount;?>_5" class="form-control text-right no-padding only_currency text-center" readonly  value="<?=store_number_format($item_tax_amt,0);?>"></td>

               <!-- Unit Cost -->
               <td id="td_<?=$rowcount;?>_10"><input type="text" name="td_data_<?=$rowcount;?>_10" id="td_data_<?=$rowcount;?>_10" class="form-control text-right no-padding only_currency text-center" readonly value="<?=store_number_format($item_unit_cost,0);?>"></td>

               <!-- Amount -->
               <td id="td_<?=$rowcount;?>_9"><input type="text" name="td_data_<?=$rowcount;?>_9" id="td_data_<?=$rowcount;?>_9" class="form-control text-right no-padding only_currency text-center" style='border-color: #f39c12;' title='Total (Editable - will auto-calculate unit price)' onfocus="if(this.value=='0' || this.value=='0.00'){this.value='';this.select();}" onkeyup="calculate_from_total(<?=$rowcount;?>);" onblur="if(this.value==''){this.value='0';} calculate_from_total(<?=$rowcount;?>);" value="<?=store_number_format($item_amount,0);?>" data-original-amount="<?=$item_amount;?>" data-original-taxable="<?=$original_taxable;?>"></td>

               <!-- ADD button -->
               <td id="td_<?=$rowcount;?>_16" style="text-align: center;">
                  <a class=" fa fa-fw fa-minus-square text-red" style="cursor: pointer;font-size: 34px;" onclick="removerow(<?=$rowcount;?>)" title="Delete ?" name="td_data_<?=$rowcount;?>_16" id="td_data_<?=$rowcount;?>_16"></a>
               </td>
               <input type="hidden" id="tr_available_qty_<?=$rowcount;?>_13" value="<?=$item_available_qty;?>">
               <input type="hidden" id="tr_item_id_<?=$rowcount;?>" name="tr_item_id_<?=$rowcount;?>" value="<?=$item_id;?>" data-batch-tracking-enabled="<?=isset($batch_tracking_enabled) ? $batch_tracking_enabled : 0;?>">

               <input type="hidden" id="tr_tax_type_<?=$rowcount;?>" name="tr_tax_type_<?=$rowcount;?>" value="<?=$item_tax_type;?>">
               <input type="hidden" id="tr_tax_id_<?=$rowcount;?>" name="tr_tax_id_<?=$rowcount;?>" value="<?=$item_tax_id;?>">
               <input type="hidden" id="tr_tax_value_<?=$rowcount;?>" name="tr_tax_value_<?=$rowcount;?>" value="<?=$item_tax;?>">

               <input type="hidden" id="description_<?=$rowcount;?>" name="description_<?=$rowcount;?>" value="<?=$description;?>">
               <input type="hidden" id="service_bit_<?=$rowcount;?>" name="service_bit_<?=$rowcount;?>" value="<?=$service_bit;?>">

               <input type="hidden" id="item_discount_type_<?=$rowcount;?>" name="item_discount_type_<?=$rowcount;?>" value="<?=$item_discount_type;?>">
               <input type="hidden" id="item_discount_input_<?=$rowcount;?>" name="item_discount_input_<?=$rowcount;?>" value="<?=store_number_format($item_discount_input,0);?>">
               
               <!-- Batch tracking hidden fields -->
               <input type="hidden" id="batch_tracking_enabled_<?=$rowcount;?>" name="batch_tracking_enabled_<?=$rowcount;?>" value="<?=isset($batch_tracking_enabled) ? $batch_tracking_enabled : 0;?>">
               <input type="hidden" id="tracking_type_<?=$rowcount;?>" name="tracking_type_<?=$rowcount;?>" value="<?=isset($tracking_type) ? $tracking_type : 'none';?>">
               <input type="hidden" id="expiry_enabled_<?=$rowcount;?>" name="expiry_enabled_<?=$rowcount;?>" value="<?=isset($expiry_enabled) ? $expiry_enabled : 0;?>">
               
               <!-- Existing batch details hidden fields (for editing) -->
               <input type="hidden" id="batch_number_<?=$rowcount;?>" name="batch_number_<?=$rowcount;?>" value="<?=isset($batch_number) ? $batch_number : '';?>">
               <input type="hidden" id="manufacturing_date_<?=$rowcount;?>" name="manufacturing_date_<?=$rowcount;?>" value="<?=isset($manufacturing_date) ? $manufacturing_date : '';?>">
               <input type="hidden" id="expiry_date_<?=$rowcount;?>" name="expiry_date_<?=$rowcount;?>" value="<?=isset($expiry_date) ? $expiry_date : '';?>">
               <input type="hidden" id="batch_notes_<?=$rowcount;?>" name="batch_notes_<?=$rowcount;?>" value="">
               
               <!-- Multi-unit hidden fields -->
               <input type="hidden" id="main_unit_id_<?=$rowcount;?>" name="main_unit_id_<?=$rowcount;?>" value="<?=isset($main_unit_id) ? $main_unit_id : '';?>">
               <input type="hidden" id="alternate_unit_id_<?=$rowcount;?>" name="alternate_unit_id_<?=$rowcount;?>" value="<?=isset($alternate_unit_id) ? $alternate_unit_id : '';?>">
               <input type="hidden" id="conversion_factor_<?=$rowcount;?>" name="conversion_factor_<?=$rowcount;?>" value="<?=isset($conversion_factor) ? $conversion_factor : '1.0';?>">
               <input type="hidden" id="purchase_price_main_<?=$rowcount;?>" name="purchase_price_main_<?=$rowcount;?>" value="<?=isset($purchase_price_main) ? $purchase_price_main : '';?>">
               <input type="hidden" id="purchase_price_alternate_<?=$rowcount;?>" name="purchase_price_alternate_<?=$rowcount;?>" value="<?=isset($purchase_price_alternate) ? $purchase_price_alternate : '';?>">
               <input type="hidden" id="main_unit_name_<?=$rowcount;?>" name="main_unit_name_<?=$rowcount;?>" value="<?=isset($main_unit_name) ? $main_unit_name : '';?>">
               <input type="hidden" id="alternate_unit_name_<?=$rowcount;?>" name="alternate_unit_name_<?=$rowcount;?>" value="<?=isset($alternate_unit_name) ? $alternate_unit_name : '';?>">
               
            </tr>
		<?php

	}

	public function show_pay_now_modal($purchase_id){
		$q1=$this->db->query("select * from db_purchase where id=$purchase_id");
		$res1=$q1->row();
		$supplier_id = $res1->supplier_id;
		$q2=$this->db->query("select * from db_suppliers where id=$supplier_id");
		$res2=$q2->row();

		$supplier_name=$res2->supplier_name;
	    $supplier_mobile=$res2->mobile;
	    $supplier_phone=$res2->phone;
	    $supplier_email=$res2->email;
	    $supplier_state=$res2->state_id;
	    $supplier_address=$res2->address;
	    $supplier_postcode=$res2->postcode;
	    $supplier_gst_no=$res2->gstin;
	    $supplier_tax_number=$res2->tax_number;
	    $supplier_opening_balance=$res2->opening_balance;

	    $purchase_date=$res1->purchase_date;
	    $reference_no=$res1->reference_no;
	    $purchase_code=$res1->purchase_code;
	    $purchase_note=$res1->purchase_note;
	    $grand_total=$res1->grand_total;
	    $paid_amount=$res1->paid_amount;
	    $due_amount =$grand_total - $paid_amount;

	    $supplier_country = $this->db->query("select country from db_country where id=".$res2->country_id)->row()->country;
	    if(!empty($supplier_state)){
    		$supplier_state = $this->db->query("select state from db_states where id=".$res2->state_id)->row()->state;
    	}


		?>
		<div class="modal fade" id="pay_now">
		  <div class="modal-dialog ">
		    <div class="modal-content">
		      <div class="modal-header header-custom">
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
		          <span aria-hidden="true">&times;</span></button>
		        <h4 class="modal-title text-center"><?= $this->lang->line('payments'); ?></h4>
		      </div>
		      <div class="modal-body">
		        
		    <div class="row">
		      <div class="col-md-12">
		      	<div class="row invoice-info">
			        <div class="col-sm-4 invoice-col">
			          <?= $this->lang->line('supplier_details'); ?>
			          <address>
			            <strong><?php echo  $supplier_name; ?></strong><br>
			            <?php echo (!empty(trim($supplier_mobile))) ? $this->lang->line('mobile').": ".$supplier_mobile."<br>" : '';?>
			            <?php echo (!empty(trim($supplier_phone))) ? $this->lang->line('phone').": ".$supplier_phone."<br>" : '';?>
			            <?php echo (!empty(trim($supplier_email))) ? $this->lang->line('email').": ".$supplier_email."<br>" : '';?>
			            <?php echo (!empty(trim($supplier_gst_no))) ? $this->lang->line('gst_number').": ".$supplier_gst_no."<br>" : '';?>
			            <?php echo (!empty(trim($supplier_tax_number))) ? $this->lang->line('tax_number').": ".$supplier_tax_number."<br>" : '';?>
			          </address>
			        </div>
			        <!-- /.col -->
			        <div class="col-sm-4 invoice-col">
			          <?= $this->lang->line('purchase_details'); ?>:
			          <address>
			            <b><?= $this->lang->line('invoice'); ?> #<?php echo  $purchase_code; ?></b><br>
			            <b><?= $this->lang->line('date'); ?> :<?php echo  show_date($purchase_date); ?></b><br>
			            <b><?= $this->lang->line('grand_total'); ?> :<?php echo $grand_total; ?></b><br>
			          </address>
			        </div>
			        <!-- /.col -->
			        <div class="col-sm-4 invoice-col">
			          <b><?= $this->lang->line('paid_amount'); ?> :<span><?php echo number_format($paid_amount,decimals(),'.',''); ?></span></b><br>
			          <b><?= $this->lang->line('due_amount'); ?> :<span id='due_amount_temp'><?php echo number_format($due_amount,decimals(),'.',''); ?></span></b><br>
			         
			        </div>
			        <!-- /.col -->
			      </div>
			      <!-- /.row -->
		      </div>
		      <div class="col-md-12">
		        <div>
		        <input type="hidden" name="payment_row_count" id='payment_row_count' value="1">
		        <div class="col-md-12  payments_div">
		          <div class="box box-solid bg-gray">
		            <div class="box-body">
		              <div class="row">
		         		<div class="col-md-6">
		                  <div class="">
		                  <label for="payment_date"><?= $this->lang->line('date'); ?></label>
		                    <div class="input-group date">
			                      <div class="input-group-addon">
			                      <i class="fa fa-calendar"></i>
			                      </div>
			                      <input type="text" class="form-control pull-right datepicker" value="<?= show_date(date("d-m-Y")); ?>" id="payment_date" name="payment_date" readonly>
			                    </div>
		                      <span id="payment_date_msg" style="display:none" class="text-danger"></span>
		                </div>
		               </div>
		                <div class="col-md-6">
		                  <div class="">
		                  <label for="amount"><?= $this->lang->line('amount'); ?></label>
		                    <input type="text" class="form-control text-right paid_amt" id="amount" name="amount" placeholder="" value="<?=$due_amount;?>" onkeyup="calculate_payments(); checkAccountBalance();">
		                      <span id="amount_msg" style="display:none" class="text-danger"></span>
		                </div>
		               </div>
		                <div class="col-md-6">
		                  <div class="">
		                    <label for="payment_type"><?= $this->lang->line('payment_type'); ?></label>
		                    <select class="form-control" id='payment_type' name="payment_type">
		                      <?php
		                        $q1=$this->db->query("select * from db_paymenttypes where status=1 and store_id=".get_current_store_id());
		                         if($q1->num_rows()>0){
		                             foreach($q1->result() as $res1){
		                             echo "<option value='".$res1->payment_type."'>".$res1->payment_type ."</option>";
		                           }
		                         }
		                         else{
		                            echo "No Records Found";
		                         }
		                        ?>
		                    </select>
		                    <span id="payment_type_msg" style="display:none" class="text-danger"></span>
		                  </div>
		                </div>
                <div class="col-md-6">
                  <div class="">
                    <label for="payment_currency">Payment Currency</label>
                    <select class="form-control" id='payment_currency' name="payment_currency" onchange="updatePaymentCurrencyPurchase(); validateAccountCurrencyPurchase(); checkPaymentCurrencyExchangeRatePurchase(); autoSelectCurrencyAccountPurchase();">
                      <?php
                        $base_currency = get_base_currency();
                        $supplier_currency = get_supplier_trading_currency($supplier_id);
                        
                        // Always show both currencies for flexibility
                        if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
                            // Supplier has different trading currency - default to supplier currency
                            echo "<option value='".$supplier_currency->id."' selected>".$supplier_currency->currency_name." (".$supplier_currency->currency_code.") - Supplier Currency</option>";
                            echo "<option value='".$base_currency->id."'>".$base_currency->currency_name." (".$base_currency->currency_code.") - Base Currency</option>";
                        } else {
                            // Supplier currency same as base or not set - default to base currency
                            echo "<option value='".$base_currency->id."' selected>".$base_currency->currency_name." (".$base_currency->currency_code.") - Base Currency</option>";
                            // Still show supplier currency if it exists but is same as base
                            if ($supplier_currency) {
                                echo "<option value='".$supplier_currency->id."'>".$supplier_currency->currency_name." (".$supplier_currency->currency_code.") - Supplier Currency</option>";
                            }
                        }
                                ?>
                    </select>
                    <span id="payment_currency_msg" style="display:none" class="text-danger"></span>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="">
                    <label for="account_id"><?= $this->lang->line('account'); ?></label>
                    <select class="form-control" id='account_id' name="account_id" onchange="checkAccountBalance()">
                      <option value="">-Select Currency First-</option>
                    </select>
                    <span id="account_id_msg" style="display:none" class="text-danger"></span>
                    <div id="account_balance_display" class="text-info" style="margin-top: 5px; font-size: 12px; min-height: 20px;"></div>
                    <div id="account_currency_alert" class="alert alert-warning" style="display:none; margin-top: 5px;">
                       <i class="fa fa-exclamation-triangle"></i> <strong>Warning:</strong> Selected account currency doesn't match payment currency. Consider selecting a matching currency account.
                    </div>
                  </div>
                </div>
		            <div class="clearfix"></div>
		        </div>  
		        <div class="row">
		               <div class="col-md-12">
		                  <div class="">
		                    <label for="payment_note"><?= $this->lang->line('payment_note'); ?></label>
		                    <textarea type="text" class="form-control" id="payment_note" name="payment_note" placeholder="" ></textarea>
		                    <span id="payment_note_msg" style="display:none" class="text-danger"></span>
		                  </div>
		               </div>
		                
		            <div class="clearfix"></div>
		        </div>   
		        </div>
		        </div>
		      </div><!-- col-md-12 -->
		    </div>
		      </div><!-- col-md-9 -->
		      <!-- RIGHT HAND -->
		    </div>
		      </div>
		      <div class="modal-footer">
		      	<input type="hidden" id="supplier_id" value="<?=$supplier_id?>">
		        <button type="button" class="btn btn-default btn-lg" data-dismiss="modal">Close</button>
		        <button type="button" onclick="save_payment(<?=$purchase_id;?>)" class="btn bg-green btn-lg place_order btn-lg payment_save">Save<i class="fa  fa-check "></i></button>
		      </div>
		    </div>
		    <!-- /.modal-content -->
		  </div>
		  <!-- /.modal-dialog -->
		</div>
		
		<script type="text/javascript">
		$(document).ready(function() {
			// Initialize only once when modal is shown
			$('#pay_now').off('shown.bs.modal.payment').on('shown.bs.modal.payment', function () {
				console.log('Purchase payment modal opened');
				
				// Small delay to ensure all elements are loaded
				setTimeout(function() {
					// Initialize payment currency and accounts only once
					if (typeof updatePaymentCurrencyPurchase === 'function') {
						updatePaymentCurrencyPurchase();
					}
				}, 300);
			});
			
			// Clear cache when modal is hidden
			$('#pay_now').off('hidden.bs.modal.payment').on('hidden.bs.modal.payment', function () {
				console.log('Purchase payment modal closed');
				if (typeof clearAccountCache === 'function') {
					clearAccountCache();
				}
			});
			
			// Payment currency change handler
			$('#payment_currency').off('change.payment').on('change.payment', function() {
				console.log('Payment currency changed');
				if (typeof updatePaymentCurrencyPurchase === 'function') {
					updatePaymentCurrencyPurchase();
				}
			});
			
			// Account change handler
			$('#account_id').off('change.payment').on('change.payment', function() {
				console.log('Account changed');
				if (typeof checkAccountBalance === 'function') {
					checkAccountBalance();
				}
				if (typeof validateAccountCurrencyPurchase === 'function') {
					validateAccountCurrencyPurchase();
				}
			});
			
			// Amount change handler with debouncing
			var amountTimeout;
			$('#amount').off('input.payment keyup.payment').on('input.payment keyup.payment', function() {
				clearTimeout(amountTimeout);
				amountTimeout = setTimeout(function() {
					if (typeof checkAccountBalance === 'function') {
						checkAccountBalance();
					}
				}, 500); // Debounce for 500ms
			});
		});
		</script>
		<?php
	}

	public function save_payment(){
		extract($this->xss_html_filter(array_merge($this->data,$_POST,$_GET)));
		//print_r($this->xss_html_filter(array_merge($this->data,$_POST,$_GET)));exit();
    	if($amount=='' || $amount==0){$amount=null;}
		if($amount>0 && !empty($payment_type)){

			// Validate account balance if account is selected
			if(!empty($account_id)){
				$account_balance = get_account_balance($account_id);
				
				// Get account currency
				$account_currency = $this->db->select('currency_id')->where('id', $account_id)->get('ac_accounts')->row();
				$account_currency_id = $account_currency ? $account_currency->currency_id : get_base_currency_id();
				
				// Convert payment amount to account currency for comparison
				$payment_amount_in_account_currency = $amount;
				$base_currency = get_base_currency();
				if ($base_currency && $base_currency->id != $account_currency_id) {
					$payment_amount_in_account_currency = convert_currency($amount, $base_currency->id, $account_currency_id);
				}
				
				if ($account_balance < $payment_amount_in_account_currency) {
					$account_currency_info = $this->db->select('symbol, currency_code')->where('id', $account_currency_id)->get('db_currency')->row();
					$base_currency_info = $this->db->select('symbol, currency_code')->where('id', $base_currency->id)->get('db_currency')->row();
					
					return "Insufficient account balance. Available: " . format_currency_amount($account_balance, $account_currency_id) . 
						   ", Required: " . format_currency_amount($payment_amount_in_account_currency, $account_currency_id) . 
						   " (from " . format_currency_amount($amount, $base_currency->id) . ")";
				}
			}

			// Get payment currency information from form data
			$payment_currency_id = isset($_POST['payment_currency']) ? $_POST['payment_currency'] : null;
			$exchange_rate = 1.0;
			$base_currency_amount = $amount;
			
			// Check if payment currency is specified
			if (!empty($payment_currency_id)) {
				$base_currency = get_base_currency();
				if ($payment_currency_id != $base_currency->id) {
					$exchange_rate = get_exchange_rate($base_currency->id, $payment_currency_id);
					$base_currency_amount = $amount / $exchange_rate;
				}
			}

			$payment_code=get_init_code('purchase_payment');

			$purchasepayments_entry = array(
					'payment_code' 		=> $payment_code,
		    		'count_id'	  		=> get_count_id('db_purchasepayments'),
					'purchase_id' 		=> $purchase_id, 
					'payment_date'		=> system_fromatted_date($payment_date),//Current Payment with Purchase entry
					'payment_type' 		=> $payment_type,
					'payment' 			=> $amount, // Original payment amount in payment currency
					'payment_currency_id' => $payment_currency_id,
					'exchange_rate' 	=> $exchange_rate,
					'base_currency_amount' => $base_currency_amount, // Converted amount in base currency
					'payment_note' 		=> $payment_note,
					'created_date' 		=> $CUR_DATE,
    				'created_time' 		=> $CUR_TIME,
    				'created_by' 		=> $CUR_USERNAME,
    				'system_ip' 		=> $SYSTEM_IP,
    				'system_name' 		=> $SYSTEM_NAME,
    				'status' 			=> 1,
    				'account_id' 		=> (empty($account_id)) ? null : $account_id,
    				'supplier_id' 		=> $supplier_id,
				);
			$purchasepayments_entry['store_id']=$this->db->select("store_id")->where('id',$purchase_id)->get('db_purchase')->row()->store_id;
			$q3 = $this->db->insert('db_purchasepayments', $purchasepayments_entry);
			//Set the payment to specified account
			if(!empty($account_id)){
				//ACCOUNT INSERT - Use original amount in account's currency
				$insert_bit = insert_account_transaction(array(
															'transaction_type'  	=> 'PURCHASE PAYMENT',
															'reference_table_id'  	=> $this->db->insert_id(),
															'debit_account_id'  	=> $account_id,
															'credit_account_id'  	=> null,
															'debit_amt'  			=> $amount, // Use original amount in account's currency
															'credit_amt'  			=> 0,
															'currency_id'  			=> $payment_currency_id, // Use payment currency
															'transaction_currency_id' => $payment_currency_id, // Store transaction currency
															'exchange_rate'  		=> $exchange_rate, // Store actual exchange rate used
															'base_currency_debit_amt' => $base_currency_amount, // Store converted amount
															'process'  				=> 'SAVE',
															'note'  				=> $payment_note . ($payment_currency_id != $base_currency->id ? " (Rate: " . number_format($exchange_rate, 4) . ")" : ""),
															'transaction_date'  	=> $CUR_DATE,
															'payment_code'  		=> $payment_code,
															'customer_id'  			=> null,
															'supplier_id'  			=> $supplier_id,
													));
				if(!$insert_bit){
					return "failed";
				}
			}
			//end
		}
		else{
			return "Please Enter Valid Amount!";
		}
		
		$q10=$this->update_purchase_payment_status($purchase_id);
		if($q10!=1){
			return "failed";
		}
		return "success";

	}
	
	public function view_payments_modal($purchase_id){
		$q1=$this->db->query("select * from db_purchase where id=$purchase_id");
		$res1=$q1->row();
		$supplier_id = $res1->supplier_id;
		$q2=$this->db->query("select * from db_suppliers where id=$supplier_id");
		$res2=$q2->row();

		$supplier_name=$res2->supplier_name;
	    $supplier_mobile=$res2->mobile;
	    $supplier_phone=$res2->phone;
	    $supplier_email=$res2->email;
	    $supplier_state=$res2->state_id;
	    $supplier_address=$res2->address;
	    $supplier_postcode=$res2->postcode;
	    $supplier_gst_no=$res2->gstin;
	    $supplier_tax_number=$res2->tax_number;
	    $supplier_opening_balance=$res2->opening_balance;

	    $purchase_date=$res1->purchase_date;
	    $reference_no=$res1->reference_no;
	    $purchase_code=$res1->purchase_code;
	    $purchase_note=$res1->purchase_note;
	    $grand_total=$res1->grand_total;
	    $paid_amount=$res1->paid_amount;
	    $due_amount =$grand_total - $paid_amount;

	    $supplier_country = $this->db->query("select country from db_country where id=".$res2->country_id)->row()->country;
	    $supplier_state=(!empty($supplier_state)) ? $this->db->query("select state from db_states where id=".$res2->state_id)->row()->state : '';
	    

		?>
		<div class="modal fade" id="view_payments_modal">
		  <div class="modal-dialog modal-lg">
		    <div class="modal-content">
		      <div class="modal-header header-custom">
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
		          <span aria-hidden="true">&times;</span></button>
		        <h4 class="modal-title text-center"><?= $this->lang->line('payments'); ?></h4>
		      </div>
		      <div class="modal-body">
		        
		    <div class="row">
		      <div class="col-md-12">
		      	<div class="row invoice-info">
			        <div class="col-sm-4 invoice-col">
			          <?= $this->lang->line('supplier_details'); ?>
			          <address>
			            <strong><?php echo  $supplier_name; ?></strong><br>
			            <?php echo (!empty(trim($supplier_mobile))) ? $this->lang->line('mobile').": ".$supplier_mobile."<br>" : '';?>
			            <?php echo (!empty(trim($supplier_phone))) ? $this->lang->line('phone').": ".$supplier_phone."<br>" : '';?>
			            <?php echo (!empty(trim($supplier_email))) ? $this->lang->line('email').": ".$supplier_email."<br>" : '';?>
			            <?php echo (!empty(trim($supplier_gst_no))) ? $this->lang->line('gst_number').": ".$supplier_gst_no."<br>" : '';?>
			            <?php echo (!empty(trim($supplier_tax_number))) ? $this->lang->line('tax_number').": ".$supplier_tax_number."<br>" : '';?>
			          </address>
			        </div>
			        <!-- /.col -->
			        <div class="col-sm-4 invoice-col">
			         <?= $this->lang->line('purchase_details'); ?>:
			          <address>
			            <b><?= $this->lang->line('invoice'); ?> #<?php echo  $purchase_code; ?></b><br>
			            <b><?= $this->lang->line('date'); ?> :<?=  show_date($purchase_date); ?></b><br>
			            <b><?= $this->lang->line('grand_total'); ?> :<?php echo $grand_total; ?></b><br>
			          </address>
			        </div>
			        <!-- /.col -->
			        <div class="col-sm-4 invoice-col">
			          <b><?= $this->lang->line('paid_amount'); ?> :<span><?php echo number_format($paid_amount,decimals(),'.',''); ?></span></b><br>
			          <b><?= $this->lang->line('due_amount'); ?> :<span id='due_amount_temp'><?php echo number_format($due_amount,decimals(),'.',''); ?></span></b><br>
			         
			        </div>
			        <!-- /.col -->
			      </div>
			      <!-- /.row -->
		      </div>
		      <div class="col-md-12">
		       
		     
		              <div class="row">
		         		<div class="col-md-12">
		                  
		                      <table class="table table-bordered">
                                  <thead>
                                  <tr class="bg-primary">
                                    <th>#</th>
                                    <th><?= $this->lang->line('payment_date'); ?></th>
                                    <th><?= $this->lang->line('payment'); ?></th>
                                    <th><?= $this->lang->line('payment_type'); ?></th>
                                    <th><?= $this->lang->line('account'); ?></th>
                                    <th><?= $this->lang->line('payment_note'); ?></th>
                                    <th><?= $this->lang->line('created_by'); ?></th>
                                    <th><?= $this->lang->line('action'); ?></th>
                                  </tr>
                                </thead>
                                <tbody>
                                	<?php
                                	$q1=$this->db->query("select * from db_purchasepayments where purchase_id=$purchase_id");
									$i=1;
									$str = '';
									if($q1->num_rows()>0){
										foreach ($q1->result() as $res1) {
											echo "<tr>";
											echo "<td>".$i++."</td>";
											echo "<td>".show_date($res1->payment_date)."</td>";
											echo "<td>".$res1->payment."</td>";
											echo "<td>".$res1->payment_type."</td>";
											echo "<td>".get_account_name($res1->account_id)."</td>";
											echo "<td>".$res1->payment_note."</td>";
											echo "<td>".ucfirst($res1->created_by)."</td>";
										
											echo "<td><a onclick='delete_purchase_payment(".$res1->id.")' class='pointer btn  btn-danger' ><i class='fa fa-trash'></i></</td>";	
											echo "</tr>";
										}
									}
									else{
										echo "<tr><td colspan='7' class='text-danger text-center'>No Records Found</td></tr>";
									}
									?>
                                </tbody>
                            </table>
		               
		               </div>
		            <div class="clearfix"></div>
		        </div>    
		       
		     
		   
		      </div><!-- col-md-9 -->
		      <!-- RIGHT HAND -->
		    </div>
		      </div>
		      <div class="modal-footer">
		        <button type="button" class="btn btn-default btn-lg" data-dismiss="modal">Close</button>
		        
		      </div>
		    </div>
		    <!-- /.modal-content -->
		  </div>
		  <!-- /.modal-dialog -->
		</div>
		<?php
	}

	// Return requisition items as purchase table rows (similar to quotation to sales)
	public function return_requisition_list($requisition_id) {
		log_message('info', 'Purchase_model::return_requisition_list called with requisition_id: ' . $requisition_id);
		
		$q1 = $this->db->select('*')->from('db_purchase_requisition_items')->where("requisition_id=$requisition_id")->get();
		log_message('info', 'Found ' . $q1->num_rows() . ' requisition items');
		
		$rowcount = 1;
		$result = ''; // Variable to store the output
		
		foreach ($q1->result() as $res1) {
			$res2 = $this->db->query("select * from db_items where id=".$res1->item_id)->row();
			
			// Handle supplier (might be null)
			$supplier_name = '';
			if ($res1->supplier_id) {
				$res3 = $this->db->query("select * from db_suppliers where id=".$res1->supplier_id)->row();
				$supplier_name = $res3 ? $res3->supplier_name : '';
			}
			
			// Get default tax for the item (if any)
			$default_tax = $this->db->query("select * from db_tax where id=1")->row(); // Default tax
			if (!$default_tax) {
				$default_tax = (object) array('id' => 1, 'tax_name' => 'No Tax', 'tax' => 0);
			}
			
			$info = array(
				'item_id' => $res1->item_id, 
				'description' => $res1->description, 
				'item_name' => $res2->item_name,
				'item_available_qty' => $res2->stock,
				'item_price' => $res2->purchase_price, 
				'item_purchase_price' => $res1->unit_price, 
				'item_tax_name' => $default_tax->tax_name, 
				'item_purchase_qty' => $res1->requested_qty, 
				'item_tax_id' => $default_tax->id, 
				'item_tax' => $default_tax->tax, 
				'item_tax_type' => 'inclusive', // Default tax type
				'item_tax_amt' => 0, // Will be calculated
				'item_discount' => 0, 
				'item_discount_type' => 'percentage', 
				'item_discount_input' => 0, 
				'supplier_id' => $res1->supplier_id,
				'supplier_name' => $supplier_name,
				'batch_tracking_enabled' => isset($res2->batch_tracking_enabled) ? $res2->batch_tracking_enabled : 0,
				'tracking_type' => isset($res2->tracking_type) ? $res2->tracking_type : 'none',
				'expiry_enabled' => isset($res2->expiry_enabled) ? $res2->expiry_enabled : 0,
				'service_bit' => 1, 
			);

			// Capture the output from return_row_with_data
			ob_start();
			$this->return_row_with_data($rowcount++, $info);
			$result .= ob_get_clean();
		}
		
		return $result; // Return the captured output
	}
}
