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

class Cash_transactions extends MY_Controller {
	public function __construct() {
		parent::__construct();
		$this->load_global();
		$this->load->model('cash_transactions_model', 'cash');
	}

	public function ajax_list() {
		try {
			$list = $this->cash->get_datatables();

			$data = array();
			$no = $_POST['start'];
			$prev_balance = 0;
			foreach ($list as $cash) {
			$no++;
			$row = array();
			$row[] = show_date($cash->payment_date);
			$row[] = $cash->payment_code;
			$row[] = $cash->payment_type;
			
			// Display payment amount with proper currency formatting
			$payment_currency_id = $cash->currency_id ?: get_base_currency()->id;
			$base_currency_id = get_base_currency()->id;
			
			// Use the proper currency formatting function
			if ($payment_currency_id == $base_currency_id) {
				// Same currency, just format normally
				$payment_display = format_currency_amount($cash->payment, $payment_currency_id);
			} else {
				// Different currency, show account currency with base currency in parentheses
				$payment_display = format_currency_with_system($cash->payment, $payment_currency_id, $base_currency_id);
			}
			
			$row[] = $payment_display;
			
			$row[] = $cash->payment_note;
			$row[] = get_user_name($cash->created_by);
			$row[] = get_account_name($cash->account_id);
					 $account_of=0;
					 if($cash->SALES_PAYMENT == "SALES_PAYMENT"){
					 	$account_of = 1;
					 }
					 if($cash->SALES_PAYMENT == "PURCHASE_PAYMENT"){
					 	$account_of = 2;
					 }
					 if($cash->SALES_PAYMENT == "SALES_RETURN_PAYMENT"){
					 	$account_of = 3;
					 }
					 if($cash->SALES_PAYMENT == "PURCHASE_RETURN_PAYMENT"){
					 	$account_of = 4;
					 }
					 if($cash->SALES_PAYMENT == "EXPENSE"){
					 	$account_of = 5;
					 }


			// Check if account is already assigned
			if (!empty($cash->account_id) && $cash->account_id != 0) {
				// Account already assigned - show disabled button
				$row[] = '<button type="button" class="btn btn-default btn-flat btn-sm" disabled title="Account already assigned">Account Linked</button>';
			} else {
				// No account assigned - show active link button
				$row[] = '<button type="button" class="btn btn-primary btn-flat btn-sm" onclick="link_account('.$account_of.','.$cash->id.','.$cash->account_id.')">Link Account</button>';
			}
			$data[] = $row;
		}

			$output = array(
				"draw" => $_POST['draw'],
				"recordsTotal" => $this->cash->count_all(),
				"recordsFiltered" => $this->cash->count_filtered(),
				"data" => $data,
			);
			//output to json format
			echo json_encode($output);
		} catch (Exception $e) {
			// Log the error
			log_message('error', 'Cash Transactions AJAX Error: ' . $e->getMessage());
			
			// Return error response
			$output = array(
				"draw" => $_POST['draw'],
				"recordsTotal" => 0,
				"recordsFiltered" => 0,
				"data" => array(),
				"error" => "Error loading data: " . $e->getMessage()
			);
			echo json_encode($output);
		}
	}

	public function delete_transaction() {
		$entry_of = $this->input->post('entry_of');

		$this->permission_check_with_msg('cash_delete');
		$id = $this->input->post('q_id');

		if ($entry_of == 'transfer') {
			$this->load->model('money_transfer_model');
			echo $this->money_transfer_model->delete_money_transfer_from_table($id);
		} else if ($entry_of == 'deposit') {
			$this->load->model('money_deposit_model');
			echo $this->money_deposit_model->delete_money_deposit_from_table($id);
		}

	}

	public function link_account(){
		try {
			// Clear any previous output
			if (ob_get_level()) {
				ob_clean();
			}
			
			// Log the POST data
			log_message('debug', 'Link Account POST Data: ' . json_encode($_POST));
			
			$result = $this->cash->link_account();
			log_message('debug', 'Link Account Result: ' . $result);
			
			// Ensure we only output the result
			echo $result;
		} catch (Exception $e) {
			log_message('error', 'Cash Transactions Link Account Error: ' . $e->getMessage());
			log_message('error', 'Stack trace: ' . $e->getTraceAsString());
			echo "failed";
		}
	}
	
	public function get_transaction_details(){
		// Clear any previous output
		if (ob_get_level()) {
			ob_clean();
		}
		
		$account_of = $this->input->post('account_of');
		$rec_id = $this->input->post('rec_id');
		
		$amount = 0;
		$currency_id = get_base_currency_id();
		
		// Ensure we have a valid currency ID
		if (empty($currency_id)) {
			$currency_id = 1; // Default to currency ID 1
		}
		
		// Validate input
		if(empty($account_of) || empty($rec_id)) {
			echo json_encode(array(
				'success' => false,
				'message' => 'Missing required parameters'
			));
			return;
		}
		
		// Get transaction details based on type
		if($account_of == 1) { // Sales Payment
			$transaction = $this->db->where('id', $rec_id)->get('db_salespayments')->row();
			if($transaction && isset($transaction->payment)) {
				$amount = (float)$transaction->payment;
			}
		} elseif($account_of == 2) { // Purchase Payment
			$transaction = $this->db->where('id', $rec_id)->get('db_purchasepayments')->row();
			if($transaction && isset($transaction->payment)) {
				$amount = (float)$transaction->payment;
			}
		} elseif($account_of == 3) { // Sales Return Payment
			$transaction = $this->db->where('id', $rec_id)->get('db_salespaymentsreturn')->row();
			if($transaction && isset($transaction->payment)) {
				$amount = (float)$transaction->payment;
			}
		} elseif($account_of == 4) { // Purchase Return Payment
			$transaction = $this->db->where('id', $rec_id)->get('db_purchasepaymentsreturn')->row();
			if($transaction && isset($transaction->payment)) {
				$amount = (float)$transaction->payment;
			}
		} elseif($account_of == 5) { // Expense
			$transaction = $this->db->where('id', $rec_id)->get('db_expense')->row();
			if($transaction && isset($transaction->expense_amt)) {
				$amount = (float)$transaction->expense_amt;
				$currency_id = !empty($transaction->expense_currency_id) ? (int)$transaction->expense_currency_id : get_base_currency_id();
			}
		}
		
		// Ensure all values are properly formatted
		$response = array(
			'success' => true,
			'amount' => (float)$amount,
			'currency_id' => (int)$currency_id
		);
		
		// Remove any null values
		$response = array_filter($response, function($value) {
			return $value !== null;
		});
		
		echo json_encode($response);
	}
	
	public function get_conversion_preview(){
		// Clear any previous output
		if (ob_get_level()) {
			ob_clean();
		}
		
		$account_id = $this->input->post('account_id');
		$transaction_amount = $this->input->post('transaction_amount');
		$transaction_currency = $this->input->post('transaction_currency');
		
		// Validate input
		if(empty($account_id) || empty($transaction_amount) || empty($transaction_currency)) {
			echo json_encode(array('success' => false, 'message' => 'Missing required parameters'));
			return;
		}
		
		// Convert to proper types
		$account_id = (int)$account_id;
		$transaction_amount = (float)$transaction_amount;
		$transaction_currency = (int)$transaction_currency;
		
		// Get account currency
		$account = $this->db->select('a.currency_id, c.currency_name, c.currency_code, c.symbol')
			->from('ac_accounts a')
			->join('db_currency c', 'a.currency_id = c.id', 'left')
			->where('a.id', $account_id)
			->get()->row();
			
		if(!$account) {
			echo json_encode(array('success' => false, 'message' => 'Account not found'));
			return;
		}
		
		// Get transaction currency
		$transaction_currency_info = $this->db->where('id', $transaction_currency)->get('db_currency')->row();
		if(!$transaction_currency_info) {
			$transaction_currency_info = get_base_currency();
		}
		
		// Ensure we have valid currency data
		if(!$transaction_currency_info) {
			echo json_encode(array('success' => false, 'message' => 'Currency information not found'));
			return;
		}
		
		$needs_conversion = ($account->currency_id != $transaction_currency);
		$converted_amount = $transaction_amount;
		$exchange_rate = 1.000000;
		
		if($needs_conversion) {
			$conversion_rate = get_exchange_rate($transaction_currency, $account->currency_id);
			if($conversion_rate !== false && $conversion_rate > 0) {
				$exchange_rate = $conversion_rate;
				$converted_amount = $transaction_amount * $conversion_rate;
			} else {
				// If no exchange rate found, show error message
				$response = array(
					'success' => false,
					'message' => 'No exchange rate found between ' . $transaction_currency_info->currency_code . ' and ' . $account->currency_code . '. Please add exchange rate first.',
					'needs_conversion' => true,
					'original_amount' => number_format($transaction_amount, 2),
					'original_symbol' => !empty($transaction_currency_info->symbol) ? $transaction_currency_info->symbol : '$',
					'account_currency_name' => !empty($account->currency_name) ? $account->currency_name : 'Unknown Currency',
					'account_currency_code' => !empty($account->currency_code) ? $account->currency_code : 'USD',
					'account_symbol' => !empty($account->symbol) ? $account->symbol : '$'
				);
				echo json_encode($response);
				return;
			}
		}
		
		// Ensure all values are properly formatted
		$response = array(
			'success' => true,
			'original_amount' => number_format($transaction_amount, 2),
			'original_symbol' => !empty($transaction_currency_info->symbol) ? $transaction_currency_info->symbol : '$',
			'account_currency_name' => !empty($account->currency_name) ? $account->currency_name : 'Unknown Currency',
			'account_currency_code' => !empty($account->currency_code) ? $account->currency_code : 'USD',
			'account_symbol' => !empty($account->symbol) ? $account->symbol : '$',
			'needs_conversion' => (bool)$needs_conversion,
			'converted_amount' => number_format($converted_amount, 2),
			'exchange_rate' => number_format($exchange_rate, 6)
		);
		
		// Remove any null values
		$response = array_filter($response, function($value) {
			return $value !== null;
		});
		
		echo json_encode($response);
	}

}
