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

class Suppliers extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('suppliers_model','suppliers');
	}
	
	public function index()
	{
		$this->permission_check('suppliers_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('suppliers_list');
		$this->load->view('suppliers-list',$data);
	}
	public function add()
	{
		$this->permission_check('suppliers_add');
		$data=$this->data;
		$data['page_title']=$this->lang->line('suppliers');
		$data['currencies'] = get_currency_list();
		$data['base_currency'] = get_base_currency();
		$this->load->view('suppliers',$data);
	}

	public function newsuppliers(){
		$this->form_validation->set_rules('supplier_name', 'Supplier Name', 'trim|required');
		$this->form_validation->set_rules('trading_currency_id', 'Trading Currency', 'trim|required');
		
		if ($this->form_validation->run() == TRUE) {
			$result=$this->suppliers->verify_and_save();
			echo $result;
		} else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}
	public function update($id){
		$this->belong_to('db_suppliers',$id);
		$this->permission_check('suppliers_edit');
		$data=$this->data;
		$result=$this->suppliers->get_details($id,$data);
		$data=array_merge($data,$result);
		$data['page_title']=$this->lang->line('suppliers');
		$data['currencies'] = get_currency_list();
		$data['base_currency'] = get_base_currency();
		$this->load->view('suppliers', $data);
	}
	public function update_suppliers(){
		$this->form_validation->set_rules('supplier_name', 'Supplier Name', 'trim|required');
		$this->form_validation->set_rules('trading_currency_id', 'Trading Currency', 'trim|required');
		
		if ($this->form_validation->run() == TRUE) {
			$result=$this->suppliers->update_suppliers();
			echo $result;
		} else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}

	public function ajax_list()
	{
		$list = $this->suppliers->get_datatables();
		
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $suppliers) {
			$opening_balance =(!empty($suppliers->opening_balance)) ? $suppliers->opening_balance : 0;
			$opening_balance -=get_paid_sob($suppliers->id);
			$purchase_due =(!empty($suppliers->purchase_due)) ? $suppliers->purchase_due : 0;
			$purchase_return_due =(!empty($suppliers->purchase_return_due)) ? $suppliers->purchase_return_due : 0;
			$total = ($opening_balance)+$purchase_due-$purchase_return_due;

			// Get supplier currency and base currency
			$supplier_currency = get_supplier_trading_currency($suppliers->id);
			$base_currency = get_base_currency();
			
			// Convert amounts to base currency for display
			$opening_balance_converted = $opening_balance;
			$purchase_due_converted = $purchase_due;
			$purchase_return_due_converted = $purchase_return_due;
			$total_converted = $total;
			$conversion_note = '';
			
			if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
				$exchange_rate = get_exchange_rate($supplier_currency->id, $base_currency->id);
				
				// Check if we got a valid exchange rate (not the default 1.000000)
				$has_exchange_rate = $this->check_exchange_rate_exists($supplier_currency->id, $base_currency->id);
				
				if ($has_exchange_rate && $exchange_rate != 1.000000) {
					$opening_balance_converted = convert_currency($opening_balance, $supplier_currency->id, $base_currency->id);
					$purchase_due_converted = convert_currency($purchase_due, $supplier_currency->id, $base_currency->id);
					$purchase_return_due_converted = convert_currency($purchase_return_due, $supplier_currency->id, $base_currency->id);
					$total_converted = convert_currency($total, $supplier_currency->id, $base_currency->id);
					$conversion_note = ' (Rate: 1 ' . $supplier_currency->currency_code . ' = ' . number_format($exchange_rate, 4) . ' ' . $base_currency->currency_code . ')';
				} else {
					$conversion_note = ' <span class="text-warning" title="Exchange rate not found">⚠ No exchange rate</span>';
				}
			}

			$no++;
			$row = array();
			$row[] = '<input type="checkbox" name="checkbox[]" value='.$suppliers->id.' class="checkbox column_checkbox" >';
			
			$row[] = $suppliers->supplier_code;
			$row[] = $suppliers->supplier_name;
			$row[] = $suppliers->mobile;
			$row[] = $suppliers->email;
			
			// Display opening balance with currency conversion
			$opening_balance_display = store_number_format($opening_balance_converted);
			if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
				$opening_balance_display .= '<br><small class="text-muted">' . store_number_format($opening_balance) . ' ' . $supplier_currency->currency_code . $conversion_note . '</small>';
			}
			$row[] = $opening_balance_display;
			
			// Display purchase due with currency conversion
			$purchase_due_display = store_number_format($purchase_due_converted);
			if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
				$purchase_due_display .= '<br><small class="text-muted">' . store_number_format($purchase_due) . ' ' . $supplier_currency->currency_code . $conversion_note . '</small>';
			}
			$row[] = $purchase_due_display;
			
			// Display purchase return due with currency conversion
			$purchase_return_due_display = store_number_format($purchase_return_due_converted);
			if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
				$purchase_return_due_display .= '<br><small class="text-muted">' . store_number_format($purchase_return_due) . ' ' . $supplier_currency->currency_code . $conversion_note . '</small>';
			}
			$row[] = $purchase_return_due_display;
			
			// Display total with currency conversion
			$total_display = store_number_format($total_converted);
			if ($supplier_currency && $supplier_currency->id != $base_currency->id) {
				$total_display .= '<br><small class="text-muted">' . store_number_format($total) . ' ' . $supplier_currency->currency_code . $conversion_note . '</small>';
			}
			$row[] = $total_display;

			 		if($suppliers->status==1){ 
			 			$str= "<span onclick='update_status(".$suppliers->id.",0)' id='span_".$suppliers->id."'  class='label label-success' style='cursor:pointer'>Active </span>";}
					else{ 
						$str = "<span onclick='update_status(".$suppliers->id.",1)' id='span_".$suppliers->id."'  class='label label-danger' style='cursor:pointer'> Inactive </span>";
					}
			$row[] = $str;			
					$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('suppliers_edit'))
											$str2.='<li>
												<a title="Edit Record ?" href="'.base_url().'suppliers/update/'.$suppliers->id.'">
													<i class="fa fa-fw fa-edit text-blue"></i>Edit
												</a>
											</li>';
											if($this->permissions('purchase_payment_add'))
						                      $str2.='<li>
						                        <a title="Pay Opening Balance & Purchase Due Payments" class="pointer" onclick="pay_now('.$suppliers->id.')" >
						                          <i class="fa fa-fw fa-money text-blue"></i>Pay Due Payments
						                        </a>
						                      </li>';
						                      if($this->permissions('purchase_return_payment_add'))
						                      $str2.='<li>
						                        <a title="Receive Return Due" class="pointer" onclick="pay_return_due('.$suppliers->id.')" >
						                          <i class="fa fa-fw fa-money text-blue"></i>Receive Return Due
						                        </a>
						                      </li>';
											if($this->permissions('suppliers_edit'))
											$str2.='<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_suppliers('.$suppliers->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->suppliers->count_all(),
						"recordsFiltered" => $this->suppliers->count_filtered(),
						"data" => $data,
				);
		//output to json format
		echo json_encode($output);
	}
	
	/**
	 * 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);
		// Removed rate_type filter to include both manual and API rates
		$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);
		// Removed rate_type filter to include both manual and API rates
		$this->db->limit(1);
		
		$query = $this->db->get();
		return $query->num_rows() > 0;
	}
	public function update_status(){
		$this->permission_check_with_msg('suppliers_edit');
		$id=$this->input->post('id');
		$status=$this->input->post('status');

		$result=$this->suppliers->update_status($id,$status);
		return $result;
	}
	
	public function delete_suppliers(){
		$this->permission_check_with_msg('suppliers_delete');
		$id=$this->input->post('q_id');
		return $this->suppliers->delete_suppliers_from_table($id);
	}
	public function multi_delete(){
		$this->permission_check_with_msg('suppliers_delete');
		$ids=implode (",",$_POST['checkbox']);
		return $this->suppliers->delete_suppliers_from_table($ids);
	}
	
	public function show_pay_now_modal(){
	    $this->permission_check_with_msg('purchase_payment_add');
	    $supplier_id=$this->input->post('supplier_id');
	    echo $this->suppliers->show_pay_now_modal($supplier_id);
	}
	public function save_payment(){
	    $this->permission_check_with_msg('purchase_payment_add');
	    echo $this->suppliers->save_payment();
	}
	public function show_pay_return_due_modal(){
	    $this->permission_check_with_msg('purchase_return_payment_add');
	    $supplier_id=$this->input->post('supplier_id');
	    echo $this->suppliers->show_pay_return_due_modal($supplier_id);
	}
	public function save_return_due_payment(){
	    $this->permission_check_with_msg('purchase_payment_add');
	    echo $this->suppliers->save_return_due_payment();
	}
	public function delete_opening_balance_entry(){
		$this->permission_check_with_msg('sales_payment_delete');
		$entry_id = $this->input->post('entry_id');
		echo $this->suppliers->delete_opening_balance_entry($entry_id);
	}
	public function getSuppliers($id=''){
		echo $this->suppliers->getSuppliersJson($id);
	}
	
	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['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['currency_name'] = $base_currency->currency_name;
				$response['currency_code'] = $base_currency->currency_code;
				$response['currency_symbol'] = $base_currency->symbol;
			}
		}
		
		echo json_encode($response);
	}
	
	// AJAX method to check account balance for supplier 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);
	}
}
