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

class Customers_advance extends MY_Controller {
	public function __construct() {
		parent::__construct();
		$this->load_global();
		$this->load->model('customers_advance_model', 'advance');
	}

	public function index() {
		$this->permission_check('cust_adv_payments_add');
		$data = $this->data;
		$data['page_title'] = $this->lang->line('advance_payments_list');
		$this->load->view('customers_advance/list', $data);
	}

	public function add() {
		$this->permission_check('cust_adv_payments_add');
		$data = $this->data;
		$data['page_title'] = $this->lang->line('new_advance');
		$this->load->view('customers_advance/create', $data);
	}
	public function new_advance() {
		$this->form_validation->set_rules('payment_date', 'Advance Date', 'trim|required');
		$this->form_validation->set_rules('customer_id', 'Customer Name', 'trim|required');
		$this->form_validation->set_rules('amount', 'Amount', 'trim|required');
		$this->form_validation->set_rules('payment_type', 'Payment Type', 'trim|required');

		if ($this->form_validation->run() == TRUE) {

			$result = $this->advance->store_record();
			echo $result;
		} else {
			echo "Please fill compulsary(*) fields!!";
		}
	}
	public function update($id) {
		$this->belong_to('db_custadvance', $id);
		$this->permission_check('cust_adv_payments_edit');
		$data = $this->data;

		$result = $this->advance->get_details($id, $data);
		$data = array_merge($data, $result);
		$data['page_title'] = $this->lang->line('edit_advance');
		$this->load->view('customers_advance/create', $data);
	}
	public function update_advance() {
		$this->form_validation->set_rules('payment_date', 'Advance Date', 'trim|required');
		$this->form_validation->set_rules('customer_id', 'Customer Name', 'trim|required');
		$this->form_validation->set_rules('amount', 'Amount', 'trim|required');
		$this->form_validation->set_rules('payment_type', 'Payment Type', 'trim|required');
		$this->form_validation->set_rules('q_id', '', 'trim|required');

		if ($this->form_validation->run() == TRUE) {
			$result = $this->advance->store_record('update');
			echo $result;
		} else {
			echo "Please fill compulsary(*) fields!!";
		}
	}
	

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

		$data = array();
		$no = $_POST['start'];
		foreach ($list as $rec) {
			$base_currency = get_base_currency();
			
			// Use stored currency information if available, otherwise fallback to customer's trading currency
			if (!empty($rec->currency_id) && !empty($rec->currency_code)) {
				// Use stored currency from the advance record
				$customer_currency = (object) array(
					'id' => $rec->currency_id,
					'currency_code' => $rec->currency_code
				);
			} else {
				// Fallback: Get customer's trading currency directly from database
				$sql = "SELECT c.trading_currency_id, curr.* FROM db_customers c LEFT JOIN db_currency curr ON curr.id = c.trading_currency_id WHERE c.id = ?";
				$query = $this->db->query($sql, array($rec->customer_id));
				$customer_currency = $query->row();
				
				// If no customer currency found, use base currency
				if (!$customer_currency || !$customer_currency->trading_currency_id) {
					$customer_currency = $base_currency;
				}
			}
			
			// Debug: Add a comment to see what currency we're using
			$debug_info = "<!-- Customer ID: " . $rec->customer_id . ", Currency: " . $customer_currency->currency_code . " (Stored: " . (!empty($rec->currency_code) ? $rec->currency_code : 'No') . ", Base: " . $base_currency->currency_code . ") -->";
			
			// Format the original amount with customer's currency
			$original_amount = store_number_format($rec->amount) . ' ' . $customer_currency->currency_code;
			
			// Check if we need to convert (if customer currency is different from base currency)
			if ($customer_currency->id != $base_currency->id) {
				// Get exchange rate
				$exchange_rate = get_exchange_rate($customer_currency->id, $base_currency->id);
				
				// If no direct rate, try to find an indirect rate through USD
				if (!$exchange_rate || $exchange_rate == 1.000000) {
					// Check if there's a rate from customer currency to USD
					$usd_currency = $this->db->query("SELECT * FROM db_currency WHERE currency_code = 'USD'")->row();
					if ($usd_currency) {
						$rate_to_usd = get_exchange_rate($customer_currency->id, $usd_currency->id);
						$rate_usd_to_base = get_exchange_rate($usd_currency->id, $base_currency->id);
						
						if ($rate_to_usd && $rate_to_usd != 1.000000 && $rate_usd_to_base && $rate_usd_to_base != 1.000000) {
							// Calculate indirect rate
							$exchange_rate = $rate_to_usd * $rate_usd_to_base;
						}
					}
				}
				
				if ($exchange_rate && $exchange_rate != 1.000000) {
					// Convert amount to base currency
					$converted_amount = $rec->amount * $exchange_rate;
					$converted_display = store_number_format($converted_amount) . ' ' . $base_currency->currency_code;
					$rate_display = ' (Rate: 1 ' . $customer_currency->currency_code . ' = ' . number_format($exchange_rate, 6) . ' ' . $base_currency->currency_code . ')';
					
					$amount_display = $original_amount . '<br><small class="text-muted">' . $converted_display . $rate_display . '</small>';
				} else {
					// No exchange rate available
					$amount_display = $original_amount . '<br><small class="text-warning">No exchange rate</small>';
				}
			} else {
				// Same currency, no conversion needed
				$amount_display = $original_amount;
			}
			
			$no++;
			$row = array();
			$row[] = '<input type="checkbox" name="checkbox[]" value=' . $rec->id . ' class="checkbox column_checkbox" >';
			$row[] = $rec->payment_code;
			$row[] = show_date($rec->payment_date);
			$row[] = $rec->customer_name;
			$row[] = $debug_info . $amount_display;
			$row[] = $rec->payment_type;
			$row[] = ($rec->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('cust_adv_payments_edit')) {
											$str2 .= '<li>
												<a title="Edit Record ?" href="' . base_url() . 'customers_advance/update/' . $rec->id . '">
													<i class="fa fa-fw fa-edit text-blue"></i>Edit
												</a>
											</li>';
										}

										if ($this->permissions('cust_adv_payments_add')) {
											$str2 .= '<li>
												<a style="cursor:pointer" title="Print Receipt" onclick="print_receipt('.$rec->id.')">
													<i class="fa fa-fw fa-file-text text-blue"></i>Print Receipt
												</a>
											</li>';
										}

										if ($this->permissions('cust_adv_payments_delete')) {
											$str2 .= '<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_advance(' . $rec->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->advance->count_all(),
			"recordsFiltered" => $this->advance->count_filtered(),
			"data" => $data,
		);
		//output to json format
		echo json_encode($output);
	}


	public function update_status() {
		$this->permission_check_with_msg('cust_adv_payments_edit');
		$id = $this->input->post('id');
		$status = $this->input->post('status');

		$result = $this->advance->update_status($id, $status);
		return $result;
	}

	public function delete_advance() {
		$this->permission_check_with_msg('cust_adv_payments_delete');
		$id = $this->input->post('q_id');
		return $this->advance->delete_advance_from_table($id);
	}
	public function multi_delete() {
		$this->permission_check_with_msg('cust_adv_payments_delete');
		$ids = implode(",", $_POST['checkbox']);
		return $this->advance->delete_advance_from_table($ids);
	}

	//Print Receipt
	public function print_receipt($payment_id){
		if(!$this->permissions('cust_adv_payments_add')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data['page_title']=$this->lang->line('advance_payment_receipt');
		$data=array_merge($data,array('payment_id'=>$payment_id));
		$this->load->view('print-cust-advance-payment-receipt',$data);
	}

}
