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

use Dompdf\Dompdf;
use Dompdf\Options;

class Purchase extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('purchase_model','purchase');
	}

	public function index()
	{
		$this->permission_check('purchase_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('purchase_list');
		$this->load->view('purchase-list',$data);
	}
	
	public function add()
	{
		$this->permission_check('purchase_add');
		$data=$this->data;
		$data['page_title']=$this->lang->line('purchase');
		
		// Check if this is a converted requisition
		$converted_requisition = $this->session->userdata('converted_requisition');
		if ($converted_requisition) {
			$data['converted_requisition'] = $converted_requisition;
			// Don't clear session data here - let the AJAX call handle it
			// The session data will be cleared after the purchase is saved
		}
		
		$this->load->view('purchase',$data);
	}

	public function purchase_save_and_update(){
		$this->form_validation->set_rules('pur_date', 'Purchase Date', 'trim|required');
		$this->form_validation->set_rules('supplier_id', 'Supplier Name', 'trim|required');
		
		if ($this->form_validation->run() == TRUE) {
	    	$result = $this->purchase->verify_save_and_update();
	    	
	    	// Check if this purchase was created from a requisition
	    	$converted_requisition = $this->session->userdata('converted_requisition');
	    	if ($converted_requisition && strpos($result, 'success<<<###>>>') !== false) {
	    		// Extract purchase ID from result
	    		$purchase_id = str_replace('success<<<###>>>', '', $result);
	    		if (is_numeric($purchase_id)) {
	    			// Update requisition with actual purchase ID and status
	    			$update_result = $this->db->where('id', (int)$converted_requisition['requisition_id'])
	    			         ->update('db_purchase_requisitions', [
	    			             'status' => 'Converted',
	    			             'converted_to_purchase_id' => (int)$purchase_id,
	    			             'updated_date' => date('Y-m-d H:i:s')
	    			         ]);
	    			         
	    			// Log the update result for debugging
	    			log_message('info', 'Updated requisition ' . $converted_requisition['requisition_id'] . ' to Converted status with purchase ID ' . $purchase_id . '. Update result: ' . ($update_result ? 'SUCCESS' : 'FAILED'));
	    			         
	    			// Clear the session data
	    			$this->session->unset_userdata('converted_requisition');
	    		}
	    	}
	    	
	    	echo $result;
		} else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}
	
	// Check if item has batch tracking enabled
	public function check_item_batch_tracking() {
		$item_id = $this->input->post('item_id');
		
		if (empty($item_id)) {
			echo json_encode(array('success' => false, 'message' => 'Item ID is required'));
			return;
		}
		
		$this->db->select('batch_tracking_enabled, expiry_enabled, tracking_type');
		$this->db->from('db_items');
		$this->db->where('id', $item_id);
		$this->db->where('status', 1);
		
		$query = $this->db->get();
		
		if ($query->num_rows() > 0) {
			$item = $query->row();
			echo json_encode(array(
				'success' => true,
				'batch_tracking_enabled' => $item->batch_tracking_enabled == 1,
				'expiry_enabled' => $item->expiry_enabled == 1,
				'tracking_type' => $item->tracking_type
			));
		} else {
			echo json_encode(array('success' => false, 'message' => 'Item not found'));
		}
	}
	
	public function update($id){
		$this->belong_to('db_purchase',$id);
		$this->permission_check('purchase_edit');
		$data=$this->data;
		$data=array_merge($data,array('purchase_id'=>$id));
		$data['page_title']=$this->lang->line('purchase');
		$this->load->view('purchase', $data);
	}
	
	//adding new item from Modal
	public function newsupplier(){
	
		$this->form_validation->set_rules('supplier_name', 'supplier Name', 'trim|required');
		
		if ($this->form_validation->run() == TRUE) {
			$this->load->model('suppliers_model');
			$result=$this->suppliers_model->verify_and_save();
			//fetch latest item details
			$res=array();
			$query=$this->db->query("select id,supplier_name from db_suppliers order by id desc limit 1");
			$res['id']=$query->row()->id;
			$res['supplier_name']=$query->row()->supplier_name;
			$res['result']=$result;
			
			echo json_encode($res);

		} 
		else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}

	public function ajax_list()
	{
		try {
		$list = $this->purchase->get_datatables();
		
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $purchase) {
			
			$no++;
			$row = array();
			$row[] = '<input type="checkbox" name="checkbox[]" value='.$purchase->id.' class="checkbox column_checkbox" >';
			
			$row[] = show_date($purchase->purchase_date);

			$info = (!empty($purchase->return_bit)) ? "<br><span class='label label-danger' style='cursor:pointer'><i class='fa fa-fw fa-undo'></i>Return Raised</span>" : '';

			$row[] = $purchase->purchase_code.$info;
			$row[] = $purchase->purchase_status;
			$row[] = $purchase->reference_no;
			$row[] = $purchase->supplier_name;
			
			// Display total with currency information
			$base_currency = get_base_currency();
			$total_display = store_number_format($purchase->grand_total);
			
			// Get transaction currency
			$transaction_currency = null;
			if (!empty($purchase->transaction_currency_id)) {
				$transaction_currency = get_currency_by_id($purchase->transaction_currency_id);
			} elseif (!empty($purchase->supplier_id)) {
				// Fallback to supplier's trading currency
				$transaction_currency = get_supplier_trading_currency($purchase->supplier_id);
			}
			
			// If no transaction currency found, use base currency
			if (!$transaction_currency) {
				$transaction_currency = $base_currency;
			}
			
			// Check if we need to convert (if transaction currency is different from base currency)
			if ($transaction_currency->id != $base_currency->id) {
				// Get exchange rate
				$exchange_rate = get_exchange_rate($transaction_currency->id, $base_currency->id);
				
				// Check if we got a valid exchange rate
				$has_exchange_rate = $this->check_exchange_rate_exists($transaction_currency->id, $base_currency->id);
				
				if ($has_exchange_rate && $exchange_rate != 1.000000) {
					// Convert amount to base currency
					$converted_total = convert_currency($purchase->grand_total, $transaction_currency->id, $base_currency->id);
					$conversion_note = ' (Rate: 1 ' . $transaction_currency->currency_code . ' = ' . number_format($exchange_rate, 6) . ' ' . $base_currency->currency_code . ')';
					$total_display = '<strong>' . store_number_format($converted_total) . ' ' . $base_currency->currency_code . '</strong><br><small class="text-muted">' . store_number_format($purchase->grand_total) . ' ' . $transaction_currency->currency_code . $conversion_note . '</small>';
				} else {
					// No exchange rate available
					$conversion_note = ' <span class="text-warning" title="Exchange rate not found">⚠ No exchange rate</span>';
					$total_display = '<strong>' . store_number_format($purchase->grand_total) . ' ' . $transaction_currency->currency_code . '</strong><br><small class="text-muted">' . $conversion_note . '</small>';
				}
			} else {
				// Same currency, no conversion needed
				$total_display = '<strong>' . store_number_format($purchase->grand_total) . ' ' . $base_currency->currency_code . '</strong>';
			}
			$row[] = $total_display;
			
			// Display paid amount with currency information
			$paid_display = store_number_format($purchase->paid_amount);
			
			// Check if we need to convert (if transaction currency is different from base currency)
			if ($transaction_currency->id != $base_currency->id) {
				// Get exchange rate
				$exchange_rate = get_exchange_rate($transaction_currency->id, $base_currency->id);
				
				// Check if we got a valid exchange rate
				$has_exchange_rate = $this->check_exchange_rate_exists($transaction_currency->id, $base_currency->id);
				
				if ($has_exchange_rate && $exchange_rate != 1.000000) {
					// Convert amount to base currency
					$converted_paid = convert_currency($purchase->paid_amount, $transaction_currency->id, $base_currency->id);
					$paid_conversion_note = ' (Rate: 1 ' . $transaction_currency->currency_code . ' = ' . number_format($exchange_rate, 6) . ' ' . $base_currency->currency_code . ')';
					$paid_display = '<strong>' . store_number_format($converted_paid) . ' ' . $base_currency->currency_code . '</strong><br><small class="text-muted">' . store_number_format($purchase->paid_amount) . ' ' . $transaction_currency->currency_code . $paid_conversion_note . '</small>';
				} else {
					// No exchange rate available
					$paid_conversion_note = ' <span class="text-warning" title="Exchange rate not found">⚠ No exchange rate</span>';
					$paid_display = '<strong>' . store_number_format($purchase->paid_amount) . ' ' . $transaction_currency->currency_code . '</strong><br><small class="text-muted">' . $paid_conversion_note . '</small>';
				}
			} else {
				// Same currency, no conversion needed
				$paid_display = '<strong>' . store_number_format($purchase->paid_amount) . ' ' . $base_currency->currency_code . '</strong>';
			}
			$row[] = $paid_display;
					$str='';
					if($purchase->payment_status=='Unpaid')
			          $str= "<span class='label label-danger' style='cursor:pointer'>Unpaid </span>";
			        if($purchase->payment_status=='Partial')
			          $str="<span class='label label-warning' style='cursor:pointer'> Partial </span>";
			        if($purchase->payment_status=='Paid')
			          $str="<span class='label label-success' style='cursor:pointer'> Paid </span>";

			$row[] = $str;
			$row[] = ($purchase->created_by);
					$str2 = '<div class="btn-group" title="View Account">
										<a class="btn btn-primary btn-o dropdown-toggle" data-toggle="dropdown" href="#">
											Action <span class="caret"></span>
										</a>
										<ul role="menu" class="dropdown-menu dropdown-light pull-right">';
											if($this->permissions('purchase_view'))
											$str2.='<li>
												<a title="View Invoice" href="'.base_url().'purchase/invoice/'.$purchase->id.'" ><i class="fa fa-fw fa-eye text-blue"></i>View Purchase
												</a>
											</li>';

											if($this->permissions('purchase_edit'))
											$str2.='<li>
												<a title="Update Record ?" href="'.base_url().'purchase/update/'.$purchase->id.'">
													<i class="fa fa-fw fa-edit text-blue"></i>Edit
												</a>
											</li>';

											if($this->permissions('purchase_payment_view'))
											$str2.='
											<li>
												<a title="Pay" class="pointer" onclick="view_payments('.$purchase->id.')" >
													<i class="fa fa-fw fa-money text-blue"></i>View Payments
												</a>
											</li>';

											if($this->permissions('purchase_payment_add'))
											$str2.='<li>
												<a title="Pay" class="pointer" onclick="pay_now('.$purchase->id.')" >
													<i class="fa fa-fw  fa-hourglass-half text-blue"></i>Pay Now
												</a>
											</li>';

											if($this->permissions('purchase_add') || $this->permissions('purchase_edit'))
											$str2.='<li>
												<a title="Take Print" target="_blank" href="purchase/print_invoice/'.$purchase->id.'">
													<i class="fa fa-fw fa-print text-blue"></i>Print
												</a>
											</li>
											<li>
												<a title="Download PDF" target="_blank" href="'.base_url().'purchase/pdf/'.$purchase->id.'">
													<i class="fa fa-fw fa-file-pdf-o text-blue"></i>PDF
												</a>
											</li>';

											if($this->permissions('purchase_return_add'))
											$str2.='<li>
												<a title="Purchase Return" href="'.base_url().'purchase_return/add/'.$purchase->id.'">
													<i class="fa fa-fw fa-undo text-blue"></i>Purchase Return
												</a>
											</li>';

											if($this->permissions('purchase_delete'))
											$str2.='<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_purchase(\''.$purchase->id.'\')">
													<i class="fa fa-fw fa-trash text-red"></i>Delete
												</a>
											</li>
											
										</ul>
									</div>';			

			$row[] = $str2;
			$data[] = $row;
		}

		$output = array(
						"draw" => $_POST['draw'],
						"recordsTotal" => $this->purchase->count_all(),
						"recordsFiltered" => $this->purchase->count_filtered(),
						"data" => $data,
				);
		//output to json format
		echo json_encode($output);
		} catch (Exception $e) {
			error_log('Purchase ajax_list error: ' . $e->getMessage());
			echo json_encode(array(
				"draw" => $_POST['draw'],
				"recordsTotal" => 0,
				"recordsFiltered" => 0,
				"data" => array(),
				"error" => "Error loading purchase data"
			));
		}
	}
	
	public function delete_purchase(){
		$this->permission_check_with_msg('purchase_delete');
		$id=$this->input->post('q_id');
		echo $this->purchase->delete_purchase($id);
	}
	public function multi_delete(){
		$this->permission_check_with_msg('purchase_delete');
		$ids=implode (",",$_POST['checkbox']);
		echo $this->purchase->delete_purchase($ids);
	}


	//Table ajax code
	public function search_item(){
		$q=$this->input->get('q');
		$result=$this->purchase->search_item($q);
		echo $result;
	}
	public function find_item_details(){
		$id=$this->input->post('id');
		
		$result=$this->purchase->find_item_details($id);
		echo $result;
	}

	//Purchase invoice form
	public function invoice($id)
	{
		$this->belong_to('db_purchase',$id);
		if(!$this->permissions('purchase_add') && !$this->permissions('purchase_edit')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data=array_merge($data,array('purchase_id'=>$id));
		$data['page_title']=$this->lang->line('purchase_invoice');
		$this->load->view('pur-invoice',$data);
	}
	
	//Print Purchase invoice 
	public function print_invoice($purchase_id)
	{
		$this->belong_to('db_purchase',$purchase_id);
		if(!$this->permissions('purchase_add') && !$this->permissions('purchase_edit')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data=array_merge($data,array('purchase_id'=>$purchase_id));
		$data['page_title']=$this->lang->line('purchase_invoice');
		$this->load->view('print-purchase-invoice-2',$data);
	}
	public function pdf($purchase_id)
	{
		$this->belong_to('db_purchase',$purchase_id);
		if(!$this->permissions('purchase_add') && !$this->permissions('purchase_edit')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data=array_merge($data,array('purchase_id'=>$purchase_id));
		$data['page_title']=$this->lang->line('purchase_invoice');
		$this->load->view('print-purchase-invoice-2',$data);

		mb_internal_encoding('UTF-8');

		// Get output html
        $html = $this->output->get_output();
        
        $options = new Options();
		$options->set('isRemoteEnabled', true);
        $dompdf = new Dompdf($options);

        // Load HTML content
        $dompdf->loadHtml($html,'UTF-8');
        
        // (Optional) Setup the paper size and orientation
        $dompdf->setPaper('A4', 'portrait');/*landscape or portrait*/
        
        // Render the HTML as PDF
        $dompdf->render();
        
        // Output the generated PDF (1 = download and 0 = preview)
        $dompdf->stream("Purchase-invoice-$purchase_id-".date('M')."_".date('d')."_".date('Y'), array("Attachment"=>0));
	}


	//Purchase Barcode image
	public function barcode_image($item_code)
	{
		$this->load->library('zend');
	    $this->zend->load('Zend/Barcode');
	    Zend_Barcode::render('code39', 'image', array('text' => $item_code), array());
	}


	public function return_row_with_data($rowcount,$item_id){
		$supplier_id = $this->input->post('supplier_id');
		echo $this->purchase->get_items_info($rowcount,$item_id,$supplier_id);
	}
	public function return_purchase_list($purchase_id){
		echo $this->purchase->return_purchase_list($purchase_id);
	}
	public function delete_payment(){
		$this->permission_check_with_msg('purchase_payment_delete');
		$payment_id = $this->input->post('payment_id');
		echo $this->purchase->delete_payment($payment_id);
	}

	public function show_pay_now_modal(){
		$this->permission_check_with_msg('purchase_view');
		$purchase_id=$this->input->post('purchase_id');
		echo $this->purchase->show_pay_now_modal($purchase_id);
	}

	public function save_payment(){
		$this->permission_check_with_msg('purchase_add');
		echo $this->purchase->save_payment();
	}
	
	public function view_payments_modal(){
		$this->permission_check_with_msg('purchase_view');
		$purchase_id=$this->input->post('purchase_id');
		echo $this->purchase->view_payments_modal($purchase_id);
	}
	public function get_suppliers_select_list(){
		echo get_suppliers_select_list(null,$_POST['store_id']);
	}
	
	public function check_currency_availability(){
		$supplier_id = $this->input->post('supplier_id');
		$response = array('success' => true, 'message' => '');
		
		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) {
					$response['success'] = false;
					$response['message'] = "No exchange rate found for {$base_currency->currency_name} to {$supplier_currency->currency_name}. Please add an exchange rate in Exchange Rates Management.";
				}
			}
		}
		
		echo json_encode($response);
	}

	public function get_supplier_currency(){
		$supplier_id = $this->input->post('supplier_id');
		$response = array('status' => false, 'currency_name' => '', 'currency_code' => '', 'currency_symbol' => '');

		if (!empty($supplier_id)) {
			$supplier_currency = get_supplier_trading_currency($supplier_id);
			$base_currency = get_base_currency();

			$response['status'] = true;
			$response['base_currency_id'] = $base_currency->id;
			$response['base_currency_name'] = $base_currency->currency_name;
			$response['base_currency_code'] = $base_currency->currency_code;

			if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
				$response['supplier_currency_id'] = $supplier_currency->id;
				$response['supplier_currency_name'] = $supplier_currency->currency_name;
				$response['supplier_currency_code'] = $supplier_currency->currency_code;
				$response['supplier_currency_symbol'] = $supplier_currency->symbol;
				$response['currency_name'] = $supplier_currency->currency_name;
				$response['currency_code'] = $supplier_currency->currency_code;
				$response['currency_symbol'] = $supplier_currency->symbol;
			} else {
				// Supplier has same currency as base, but still show it
				$response['supplier_currency_id'] = $base_currency->id;
				$response['supplier_currency_name'] = $base_currency->currency_name;
				$response['supplier_currency_code'] = $base_currency->currency_code;
				$response['supplier_currency_symbol'] = $base_currency->symbol;
				$response['currency_name'] = $base_currency->currency_name;
				$response['currency_code'] = $base_currency->currency_code;
				$response['currency_symbol'] = $base_currency->symbol;
			}
		}
		echo json_encode($response);
	}

	public function get_item_price_in_supplier_currency(){
		$item_id = $this->input->post('item_id');
		$supplier_id = $this->input->post('supplier_id');
		$response = array('status' => false, 'converted_price' => '', 'currency_symbol' => '');

		if (!empty($item_id) && !empty($supplier_id)) {
			// Get item details
			$item = $this->db->select('purchase_price')->from('db_items')->where('id', $item_id)->get()->row();
			
			if ($item) {
				$supplier_currency = get_supplier_trading_currency($supplier_id);
				$base_currency = get_base_currency();
				
				$purchase_price = $item->purchase_price;
				
				// If supplier has different currency, convert the price
				if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
					$exchange_rate = get_exchange_rate($base_currency->id, $supplier_currency->id);
					
					if ($exchange_rate && $exchange_rate > 0) {
						$converted_price = $purchase_price * $exchange_rate;
						$response['status'] = true;
						$response['converted_price'] = number_format($converted_price, 2, '.', '');
						$response['currency_symbol'] = $supplier_currency->symbol;
						$response['exchange_rate'] = $exchange_rate;
					} else {
						$response['status'] = false;
						$response['message'] = 'No exchange rate available between ' . $base_currency->currency_code . ' and ' . $supplier_currency->currency_code;
					}
				} else {
					// Same currency, no conversion needed
					$response['status'] = true;
					$response['converted_price'] = number_format($purchase_price, 2, '.', '');
					$response['currency_symbol'] = $base_currency->symbol;
				}
			}
		}
		
		echo json_encode($response);
	}

	public function get_currency_details(){
		$currency_id = $this->input->post('currency_id');
		$response = array('status' => false, 'currency_name' => '', 'currency_code' => '', 'currency_symbol' => '');

		if (!empty($currency_id)) {
			$currency = get_currency_by_id($currency_id);
			
			if ($currency) {
				$response['status'] = true;
				$response['currency_name'] = $currency->currency_name;
				$response['currency_code'] = $currency->currency_code;
				$response['currency_symbol'] = $currency->symbol;
			}
		}
		
		echo json_encode($response);
	}

	public function get_account_currency(){
		$account_id = $this->input->post('account_id');
		$response = array('currency_id' => null);

		if (!empty($account_id)) {
			$account = $this->db->select('currency_id')->where('id', $account_id)->get('ac_accounts')->row();
			if ($account) {
				$response['currency_id'] = $account->currency_id;
			}
		}
		
		echo json_encode($response);
	}

	public function get_accounts_by_currency(){
		$currency_id = $this->input->post('currency_id');
		$supplier_id = $this->input->post('supplier_id');
		$response = array('accounts' => array());

		if (!empty($currency_id)) {
			$this->db->select('a.id, a.account_name, a.balance, a.currency_id, c.currency_name, c.currency_code, c.symbol as currency_symbol');
			$this->db->from('ac_accounts a');
			$this->db->join('db_currency c', 'a.currency_id = c.id', 'left');
			$this->db->where('a.currency_id', $currency_id);
			$this->db->where('a.store_id', get_current_store_id());
			$this->db->where('a.status', 1);
			$this->db->where('(a.delete_bit = 0 OR a.delete_bit = 1)'); // Include both regular and cash accounts
			$this->db->order_by('a.account_name', 'ASC');
			
			$query = $this->db->get();
			$response['accounts'] = $query->result();
			
			// Also get supplier currency for auto-selection
			if ($supplier_id) {
				$supplier_currency = get_supplier_trading_currency($supplier_id);
				if ($supplier_currency) {
					$response['supplier_currency_id'] = $supplier_currency->id;
				}
			}
		}
		
		echo json_encode($response);
	}

	public function test_accounts(){
		// Simple test to see if there are any accounts at all
		$this->db->select('a.id, a.account_name, a.currency_id, c.currency_code, a.store_id, a.status, a.delete_bit');
		$this->db->from('ac_accounts a');
		$this->db->join('db_currency c', 'a.currency_id = c.id', 'left');
		$this->db->where('a.store_id', get_current_store_id());
		$query = $this->db->get();
		
		$all_accounts = $query->result_array();
		
		echo json_encode(array(
			'store_id' => get_current_store_id(),
			'total_accounts' => count($all_accounts),
			'accounts' => $all_accounts
		));
	}

	public function get_account_balance(){
		$account_id = $this->input->post('account_id');
		$response = array('success' => false, 'balance' => 0, 'currency_symbol' => '', 'currency_position' => 'before', 'currency_id' => null);

		if (!empty($account_id)) {
			$this->db->select('a.balance, a.currency_id, c.symbol, c.currency_position');
			$this->db->from('ac_accounts a');
			$this->db->join('db_currency c', 'a.currency_id = c.id', 'left');
			$this->db->where('a.id', $account_id);
			$this->db->where('a.store_id', get_current_store_id());
			$this->db->where('a.status', 1);
			$query = $this->db->get();
			
			if ($query->num_rows() > 0) {
				$account = $query->row();
				$response['success'] = true;
				$response['balance'] = $account->balance;
				$response['currency_symbol'] = $account->symbol;
				$response['currency_position'] = $account->currency_position;
				$response['currency_id'] = $account->currency_id;
			}
		}
		
		echo json_encode($response);
	}

	/**
	 * Check if exchange rate exists between two currencies
	 */
	private function check_exchange_rate_exists($from_currency_id, $to_currency_id, $store_id = null) {
		if ($store_id === null) {
			$store_id = get_current_store_id();
		}
		
		$date = date('Y-m-d');
		
		// Check direct rate
		$this->db->select('id');
		$this->db->from('db_exchange_rates');
		$this->db->where('from_currency_id', $from_currency_id);
		$this->db->where('to_currency_id', $to_currency_id);
		$this->db->where('effective_date <=', $date);
		$this->db->where('status', 1);
		$this->db->limit(1);
		
		$query = $this->db->get();
		if ($query->num_rows() > 0) {
			return true;
		}
		
		// Check reverse rate
		$this->db->select('id');
		$this->db->from('db_exchange_rates');
		$this->db->where('from_currency_id', $to_currency_id);
		$this->db->where('to_currency_id', $from_currency_id);
		$this->db->where('effective_date <=', $date);
		$this->db->where('status', 1);
		$this->db->limit(1);
		
		$query = $this->db->get();
		return $query->num_rows() > 0;
	}

	// AJAX method to check account balance for purchase payments
	public function check_account_balance(){
		$account_id = $this->input->post('account_id');
		$amount = $this->input->post('amount');
		$currency_id = $this->input->post('currency_id');
		
		// Recalculate account balance to ensure it's up to date
		update_account_balance($account_id);
		
		$account_balance = get_account_balance($account_id);
		$account_info = $this->db->select('a.account_name, a.currency_id, c.symbol, c.currency_code')
								->from('ac_accounts a')
								->join('db_currency c', 'a.currency_id = c.id', 'left')
								->where('a.id', $account_id)
								->get()->row();
		
		// Convert payment amount to account currency for comparison
		$payment_amount_in_account_currency = $amount;
		if ($currency_id && $currency_id != $account_info->currency_id) {
			$payment_amount_in_account_currency = convert_currency($amount, $currency_id, $account_info->currency_id);
		}
		
		$response = array(
			'success' => true,
			'balance' => $account_balance,
			'account_currency_id' => $account_info->currency_id,
			'account_currency_symbol' => $account_info->symbol,
			'account_currency_code' => $account_info->currency_code,
			'payment_amount_in_account_currency' => $payment_amount_in_account_currency,
			'is_sufficient' => $account_balance >= $payment_amount_in_account_currency
		);
		
		echo json_encode($response);
	}

	// Return requisition items as purchase table rows (similar to quotation to sales)
	public function return_requisition_list($requisition_id) {
		// Log the request for debugging
		log_message('info', 'return_requisition_list called with requisition_id: ' . $requisition_id);
		
		$this->load->model('Purchase_model');
		$result = $this->Purchase_model->return_requisition_list($requisition_id);
		
		// Log the result length for debugging
		log_message('info', 'return_requisition_list result length: ' . strlen($result));
		
		echo $result;
	}
	
}
