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

class Money_transfer extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('money_transfer_model','money_transfer');
	}
	public function index()
	{
		$this->permission_check('money_transfer_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('money_transfer_list');
		$this->load->view('accounts/money_transfer_list',$data);
	}
	public function add()
	{
		$this->permission_check('money_transfer_add');
		$data=$this->data;
		$data['page_title']=$this->lang->line('money_transfer');
		$this->load->view('accounts/money_transfer',$data);
	}
	
	
	public function new_money_transfer(){
		$this->permission_check('money_transfer_add');
		$this->form_validation->set_rules('transfer_date', 'Transfer date', 'trim|required');
		$this->form_validation->set_rules('transfer_code', 'Transfer Code', 'trim|required');
		$this->form_validation->set_rules('debit_account_id', 'From Account', 'trim|required');
		$this->form_validation->set_rules('credit_account_id', 'To Account', 'trim|required');
		$this->form_validation->set_rules('amount', 'Amount', 'trim|required');
		
		// Custom validation: From Account and To Account must be different
		$debit_account_id = $this->input->post('debit_account_id');
		$credit_account_id = $this->input->post('credit_account_id');
		
		if ($debit_account_id && $credit_account_id && $debit_account_id == $credit_account_id) {
			echo "From Account and To Account cannot be the same!";
			return;
		}
		
		if ($this->form_validation->run() == TRUE) {
			$result=$this->money_transfer->verify_and_save();
			echo $result;
		} else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}
	public function update($id){
		$this->belong_to('ac_moneytransfer',$id);
		$this->permission_check('money_transfer_edit');
		$data=$this->data;
		$result=$this->money_transfer->get_details($id,$data);
		$data=array_merge($data,$result);
		$data['page_title']=$this->lang->line('money_transfer');
		$this->load->view('accounts/money_transfer', $data);
	}
	public function update_money_transfer(){
		$this->form_validation->set_rules('transfer_date', 'Transfer date', 'trim|required');
		$this->form_validation->set_rules('transfer_code', 'Transfer Code', 'trim|required');
		$this->form_validation->set_rules('debit_account_id', 'From Account', 'trim|required');
		$this->form_validation->set_rules('credit_account_id', 'To Account', 'trim|required');
		$this->form_validation->set_rules('amount', 'Amount', 'trim|required');
		
		// Custom validation: From Account and To Account must be different
		$debit_account_id = $this->input->post('debit_account_id');
		$credit_account_id = $this->input->post('credit_account_id');
		
		if ($debit_account_id && $credit_account_id && $debit_account_id == $credit_account_id) {
			echo "From Account and To Account cannot be the same!";
			return;
		}
		
		if ($this->form_validation->run() == TRUE) {
			$result=$this->money_transfer->update_money_transfer();
			echo $result;
		} else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}

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

			$row[] = get_account_name($money_transfer->debit_account_id);
			$row[] = get_account_name($money_transfer->credit_account_id);

			// Display amount with currency information
			$amount_display = store_number_format($money_transfer->amount);
			
			// Get transfer currency details
			$transfer_currency_id = isset($money_transfer->transfer_currency_id) ? $money_transfer->transfer_currency_id : get_base_currency_id();
			$transfer_currency = $this->db->select('currency_name, currency_code, symbol')
				->from('db_currency')
				->where('id', $transfer_currency_id)
				->get()->row();
			
			if ($transfer_currency) {
				$amount_display .= ' ' . $transfer_currency->symbol;
				
				// Show conversion info if different from base currency
				if (isset($money_transfer->base_currency_amount) && $money_transfer->base_currency_amount != $money_transfer->amount) {
					$base_currency = get_base_currency();
					$amount_display .= '<br><small class="text-muted">';
					$amount_display .= 'Converted: ' . store_number_format($money_transfer->base_currency_amount) . ' ' . $base_currency->symbol;
					if (isset($money_transfer->exchange_rate)) {
						$amount_display .= ' (Rate: ' . number_format($money_transfer->exchange_rate, 6) . ')';
					}
					$amount_display .= '</small>';
				}
			}
			
			$row[] = $amount_display;

			$row[] = ($money_transfer->created_by);			
				     $str2 = '<div class="btn-group" title="View Money Transfer">
										<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('money_transfer_view'))
											$str2.='<li>
												<a title="View Receipt" href="'.base_url().'money_transfer/receipt/'.$money_transfer->id.'" target="_blank">
													<i class="fa fa-fw fa-file-text text-green"></i>View Receipt
												</a>
											</li>';

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

											if($this->permissions('money_transfer_delete'))
											$str2.='<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_money_transfer('.$money_transfer->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->money_transfer->count_all(),
						"recordsFiltered" => $this->money_transfer->count_filtered(),
						"data" => $data,
				);
		//output to json format
		echo json_encode($output);
	}
	
	public function delete_money_transfer(){
		$this->permission_check_with_msg('money_transfer_delete');
		$id=$this->input->post('q_id');
		echo $this->money_transfer->delete_money_transfer_from_table($id);
	}
	public function multi_delete_money_transfer(){
		$this->permission_check_with_msg('money_transfer_delete');
		$ids=implode (",",$_POST['checkbox']);
		echo $this->money_transfer->delete_money_transfer_from_table($ids);
	}
	
	public function receipt($id)
	{
		$this->permission_check('money_transfer_view');
		$this->belong_to('ac_moneytransfer',$id);
		
		try {
			// Get transfer details
			$transfer = $this->money_transfer->get_details($id, array());
			
			if (empty($transfer)) {
				show_error('Transfer not found', 404);
				return;
			}
			
			// Debug: Log transfer data
			log_message('debug', 'Money Transfer Receipt - Transfer ID: ' . $id);
			log_message('debug', 'Money Transfer Receipt - Transfer Data: ' . json_encode($transfer));
		
		// Get account details
		$from_account = $this->db->select('a.account_name, a.account_code, a.currency_id as from_currency_id, a.balance as from_current_balance,
			c1.currency_name as from_currency_name, c1.currency_code as from_currency_code, c1.symbol as from_currency_symbol')
			->from('ac_accounts a')
			->join('db_currency c1', 'a.currency_id = c1.id', 'left')
			->where('a.id', $transfer['debit_account_id'])
			->get()->row();
			
		if (!$from_account) {
			log_message('error', 'Money Transfer Receipt - From account not found for ID: ' . $transfer['debit_account_id']);
			show_error('From account not found', 500);
			return;
		}
			
		$to_account = $this->db->select('a.account_name, a.account_code, a.currency_id as to_currency_id, a.balance as to_current_balance,
			c2.currency_name as to_currency_name, c2.currency_code as to_currency_code, c2.symbol as to_currency_symbol')
			->from('ac_accounts a')
			->join('db_currency c2', 'a.currency_id = c2.id', 'left')
			->where('a.id', $transfer['credit_account_id'])
			->get()->row();
			
		if (!$to_account) {
			log_message('error', 'Money Transfer Receipt - To account not found for ID: ' . $transfer['credit_account_id']);
			show_error('To account not found', 500);
			return;
		}
		
		// Get transfer currency details
		$transfer_currency_id = isset($transfer['transfer_currency_id']) ? $transfer['transfer_currency_id'] : get_base_currency_id();
		$transfer_currency = $this->db->select('currency_name, currency_code, symbol')
			->from('db_currency')
			->where('id', $transfer_currency_id)
			->get()->row();
			
		// Fallback if currency not found
		if (!$transfer_currency) {
			log_message('error', 'Money Transfer Receipt - Transfer currency not found for ID: ' . $transfer_currency_id);
			$base_currency = get_base_currency();
			if (!$base_currency) {
				log_message('error', 'Money Transfer Receipt - Base currency not found');
				show_error('Currency information not available', 500);
				return;
			}
			$transfer_currency = (object) array(
				'currency_name' => $base_currency->currency_name,
				'currency_code' => $base_currency->currency_code,
				'symbol' => $base_currency->symbol
			);
		}
		
		// Calculate new balances
		$amount = $transfer['amount'];
		$from_new_balance = $from_account->from_current_balance;
		$to_new_balance = $to_account->to_current_balance;
		
		// Calculate currency conversion info
		$conversion_info = '';
		
		// Calculate amount to deduct from from_account
		if ($from_account->from_currency_id != $transfer_currency_id) {
			$exchange_rate = get_exchange_rate($transfer_currency_id, $from_account->from_currency_id);
			if ($exchange_rate === false) {
				$conversion_info .= '<p class="text-danger"><strong>From Account Conversion:</strong> No exchange rate available for ' . $from_account->from_currency_code . '</p>';
				$from_new_balance = $from_account->from_current_balance; // Don't change balance if no rate
			} else {
				$converted_amount = $amount * $exchange_rate;
				$from_new_balance = $from_account->from_current_balance - $converted_amount;
				$conversion_info .= '<p><strong>From Account Conversion:</strong> ' . $from_account->from_currency_symbol . ' ' . number_format($converted_amount, 2) . ' (Rate: ' . number_format($exchange_rate, 4) . ')</p>';
			}
		} else {
			$from_new_balance = $from_account->from_current_balance - $amount;
		}
		
		// Calculate amount to add to to_account
		if ($to_account->to_currency_id != $transfer_currency_id) {
			$exchange_rate = get_exchange_rate($transfer_currency_id, $to_account->to_currency_id);
			if ($exchange_rate === false) {
				$conversion_info .= '<p class="text-danger"><strong>To Account Conversion:</strong> No exchange rate available for ' . $to_account->to_currency_code . '</p>';
				$to_new_balance = $to_account->to_current_balance; // Don't change balance if no rate
			} else {
				$converted_received = $amount * $exchange_rate;
				$to_new_balance = $to_account->to_current_balance + $converted_received;
				$conversion_info .= '<p><strong>To Account Conversion:</strong> ' . $to_account->to_currency_symbol . ' ' . number_format($converted_received, 2) . ' (Rate: ' . number_format($exchange_rate, 4) . ')</p>';
			}
		} else {
			$to_new_balance = $to_account->to_current_balance + $amount;
		}
		
		// Get store details for logo and email
		$store_details = get_store_details();
		if (!$store_details) {
			log_message('error', 'Money Transfer Receipt - Store details not found');
			show_error('Store information not available', 500);
			return;
		}
		$company_logo = (!empty($store_details->store_logo)) ? $store_details->store_logo : store_demo_logo();
		$company_email = $store_details->email;
		$company_name = $store_details->store_name;
		$company_address = $store_details->address;
		$company_city = $store_details->city;
		$company_state = $store_details->state;
		$company_phone = $store_details->mobile;
		$company_website = $store_details->store_website;
		
		// Prepare data for receipt
		$data = array(
			'transfer_code' => $transfer['transfer_code'],
			'transfer_date' => $transfer['transfer_date'],
			'transfer_time' => $transfer['created_time'],
			'amount' => $amount,
			'transfer_currency_symbol' => $transfer_currency->symbol,
			'from_account_name' => $from_account->account_name,
			'from_account_code' => $from_account->account_code,
			'from_currency_name' => $from_account->from_currency_name,
			'from_currency_code' => $from_account->from_currency_code,
			'from_currency_symbol' => $from_account->from_currency_symbol,
			'from_current_balance' => $from_account->from_current_balance,
			'from_new_balance' => $from_new_balance,
			'to_account_name' => $to_account->account_name,
			'to_account_code' => $to_account->account_code,
			'to_currency_name' => $to_account->to_currency_name,
			'to_currency_code' => $to_account->to_currency_code,
			'to_currency_symbol' => $to_account->to_currency_symbol,
			'to_current_balance' => $to_account->to_current_balance,
			'to_new_balance' => $to_new_balance,
			'reference_no' => $transfer['reference_no'],
			'note' => $transfer['note'],
			'created_by' => $transfer['created_by'],
			'system_ip' => $transfer['system_ip'],
			'company_logo' => $company_logo,
			'company_email' => $company_email,
			'company_name' => $company_name,
			'company_address' => $company_address,
			'company_city' => $company_city,
			'company_state' => $company_state,
			'company_phone' => $company_phone,
			'company_website' => $company_website,
			'conversion_info' => $conversion_info,
			'base_url' => base_url()
		);
		
		$this->load->view('accounts/money_transfer_receipt', $data);
		
		} catch (Exception $e) {
			log_message('error', 'Money Transfer Receipt Error: ' . $e->getMessage());
			show_error('Error generating receipt: ' . $e->getMessage(), 500);
		}
	}


}
