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

class Customers extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('customers_model','customers');
	}

	public function index()
	{
		$this->permission_check('customers_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('customers_list');
		$this->load->view('customers-view',$data);
	}
	public function add()
	{
		$this->permission_check('customers_add');
		$data=$this->data;
		$data['page_title']=$this->lang->line('customers');
		$data['currencies'] = get_currency_list();
		$data['base_currency'] = get_base_currency();
		$this->load->view('customers',$data);
	}

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


	public function ajax_list()
	{
		$list = $this->customers->get_datatables();
		
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $customers) {

			$opening_balance =(!empty($customers->opening_balance)) ? $customers->opening_balance : 0;
			$opening_balance -=get_paid_cob($customers->id);
			$sales_due =(!empty($customers->sales_due)) ? $customers->sales_due : 0;
			$sales_return_due =(!empty($customers->sales_return_due)) ? $customers->sales_return_due : 0;
			$total = ($opening_balance)+$sales_due-$sales_return_due;
			
			// Get customer currency and base currency
			$customer_currency = get_customer_trading_currency($customers->id);
			$base_currency = get_base_currency();
			
			// Convert amounts to base currency for display
			$opening_balance_converted = $opening_balance;
			$advance_converted = $customers->tot_advance;
			$conversion_note = '';
			
			if ($customer_currency && $customer_currency->id != $base_currency->id) {
				$exchange_rate = get_exchange_rate($customer_currency->id, $base_currency->id);
				
				// Check if we got a valid exchange rate (not the default 1.000000)
				// We need to check if there's actually an exchange rate record
				$has_exchange_rate = $this->check_exchange_rate_exists($customer_currency->id, $base_currency->id);
				
				if ($has_exchange_rate && $exchange_rate != 1.000000) {
					$opening_balance_converted = convert_currency($opening_balance, $customer_currency->id, $base_currency->id);
					$advance_converted = convert_currency($customers->tot_advance, $customer_currency->id, $base_currency->id);
					$conversion_note = ' (Rate: 1 ' . $customer_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();
			$disable = ($customers->delete_bit==1) ? 'disabled' : '';
			
			$row[] = ($customers->delete_bit==1) ? '<span data-toggle="tooltip" title="Resticted" class="text-danger fa fa-fw fa-ban"></span>' : '<input type="checkbox" name="checkbox[]" '.$disable.' value='.$customers->id.' class="checkbox column_checkbox" >';
			
			
			$row[] = $customers->customer_code;
			$row[] = $customers->customer_name;
			$row[] = $customers->customer_type;
			$row[] = $customers->mobile;
			$row[] = $customers->email;
			$row[] = (!empty($customers->location_link)) ? '<a target="_blank" title="Click to View Location!" href="'.$customers->location_link.'"><i class="fa fa-fw fa-map-marker"></i> Link</a>' : '';
			$row[] = ($customers->credit_limit==-1) ? "<span class='badge'>No Limit</span>" :store_number_format($customers->credit_limit);
			
			// Display opening balance with currency conversion
			$opening_balance_display = store_number_format($opening_balance_converted);
			if ($customer_currency && $customer_currency->id != $base_currency->id) {
				$opening_balance_display .= '<br><small class="text-muted">' . store_number_format($opening_balance) . ' ' . $customer_currency->currency_code . $conversion_note . '</small>';
			}
			$row[] = $opening_balance_display;
			
			$row[] = store_number_format($sales_return_due);
			
			// Display advance with currency conversion
			$advance_display = store_number_format($advance_converted);
			if ($customer_currency && $customer_currency->id != $base_currency->id) {
				$advance_display .= '<br><small class="text-muted">' . store_number_format($customers->tot_advance) . ' ' . $customer_currency->currency_code . $conversion_note . '</small>';
			}
			$row[] = $advance_display;
			

			 		if($customers->status==1){ 
			 			$str= "<span onclick='update_status(".$customers->id.",0)' id='span_".$customers->id."'  class='label label-success' style='cursor:pointer'>Active </span>";}
					else{ 
						$str = "<span onclick='update_status(".$customers->id.",1)' id='span_".$customers->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(is_store_admin())
											$str2.='<li>
												<a title="Discount Coupon" href="'.base_url().'customer_coupon/generate/'.$customers->id.'">
													<i class="fa fa-fw fa-tags text-blue"></i>Generate Discount Coupon
												</a>
											</li>';

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

											if($this->permissions('cust_adv_payments_view'))
											$str2.='<li>
												<a title="Advance Payments View" href="'.base_url().'customers_advance">
													<i class="fa fa-fw fa-edit text-blue"></i>Advance Payments
												</a>
											</li>';

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

											if($this->permissions('sales_payment_add'))
											$str2.='<li>
												<a title="Receive Previous Balance & Sales Due Payments" class="pointer" onclick="pay_now('.$customers->id.')" >
													<i class="fa fa-fw fa-money text-blue"></i>Receive Due Payments
												</a>
											</li>';
											if($this->permissions('sales_return_payment_add'))
											$str2.='<li>
												<a title="Pay Return Due" class="pointer" onclick="pay_return_due('.$customers->id.')" >
													<i class="fa fa-fw fa-money text-blue"></i>Pay Return Due
												</a>
											</li>';

											if($this->permissions('promotional_sms') && !empty($customers->mobile))
											$str2.='<li>
												<a title="Send SMS" class="pointer" onclick="send_sms_to_customer('.$customers->id.', \''.$customers->customer_name.'\', \''.$customers->mobile.'\')" >
													<i class="fa fa-fw fa-envelope text-green"></i>Send SMS
												</a>
											</li>';

											if($this->permissions('customers_delete') && $customers->delete_bit!=1)
											$str2.='<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_customers('.$customers->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->customers->count_all(),
						"recordsFiltered" => $this->customers->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);
		// Include both manual and API rates - whatever is available
		$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);
		// Include both manual and API rates - whatever is available
		$this->db->limit(1);
		
		$query = $this->db->get();
		return $query->num_rows() > 0;
	}
	public function update_status(){
		$this->permission_check_with_msg('customers_edit');
		$id=$this->input->post('id');
		$status=$this->input->post('status');

		$result=$this->customers->update_status($id,$status);
		return $result;
	}
	
	public function delete_customers(){
		$this->permission_check_with_msg('customers_delete');
		$id=$this->input->post('q_id');
		return $this->customers->delete_customers_from_table($id);
	}
	public function multi_delete(){
		$this->permission_check_with_msg('customers_delete');
		$ids=implode (",",$_POST['checkbox']);
		return $this->customers->delete_customers_from_table($ids);
	}
	public function show_pay_now_modal(){
		$this->permission_check_with_msg('sales_payment_add');
		$customer_id=$this->input->post('customer_id');
		echo $this->customers->show_pay_now_modal($customer_id);
	}
	public function save_payment(){
		$this->permission_check_with_msg('sales_payment_add');
		echo $this->customers->save_payment();
	}
	public function show_pay_return_due_modal(){
		$this->permission_check_with_msg('sales_return_payment_add');
		$customer_id=$this->input->post('customer_id');
		echo $this->customers->show_pay_return_due_modal($customer_id);
	}
	public function save_return_due_payment(){
		$this->permission_check_with_msg('sales_payment_add');
		echo $this->customers->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->customers->delete_opening_balance_entry($entry_id);
	}
	/*27-06-2020*/
	public function view_payment_list_modal(){
		$this->permission_check_with_msg('sales_payment_add');
		$customer_id=$this->input->post('customer_id');
		echo $this->customers->view_payment_list_modal($customer_id);
	}
	/*28-06-2020*/
	//Print Customer Bulk Payment Receipt
	public function print_show_receipt($payment_id){
		if(!$this->permissions('sales_add') && !$this->permissions('sales_edit')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data['page_title']=$this->lang->line('payment_receipt');
		$data=array_merge($data,array('payment_id'=>$payment_id));
		$this->load->view('print-cust-payment-receipt',$data);
	}

	public function restore_customer_list(){
		echo get_customers_select_list($this->input->post('customer_id'),get_current_store_id());
	}

	public function getCustomers($id=''){
		echo $this->customers->getCustomersJson($id);
	}
	
	public function get_customer_currency(){
		$customer_id = $this->input->post('customer_id');
		$response = array('status' => false, 'currency_name' => '', 'currency_code' => '', 'currency_symbol' => '');
		
		if (!empty($customer_id)) {
			$customer_currency = get_customer_trading_currency($customer_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 ($customer_currency && $customer_currency->id != $base_currency->id) {
				$response['customer_currency_id'] = $customer_currency->id;
				$response['customer_currency_name'] = $customer_currency->currency_name;
				$response['customer_currency_code'] = $customer_currency->currency_code;
				$response['currency_name'] = $customer_currency->currency_name;
				$response['currency_code'] = $customer_currency->currency_code;
				$response['currency_symbol'] = $customer_currency->symbol;
			} else {
				// Customer has same currency as base, but still show it
				$response['customer_currency_id'] = $base_currency->id;
				$response['customer_currency_name'] = $base_currency->currency_name;
				$response['customer_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);
	}

	public function get_exchange_rate(){
		$from_currency = $this->input->post('from_currency');
		$to_currency = $this->input->post('to_currency');
		$response = array('status' => false);
		
		if (!empty($from_currency) && !empty($to_currency)) {
			$exchange_rate = get_exchange_rate($from_currency, $to_currency);
			$base_currency = get_base_currency();
			
			// Check if exchange rate actually exists in database
			$has_exchange_rate = $this->check_exchange_rate_exists($from_currency, $to_currency);
			
			// Get currency details
			$from_currency_details = get_currency_by_id($from_currency);
			$to_currency_details = get_currency_by_id($to_currency);
			
			$response['status'] = true;
			$response['exchange_rate'] = $has_exchange_rate ? $exchange_rate : null;
			$response['base_symbol'] = $base_currency->symbol;
			$response['from_code'] = $from_currency_details ? $from_currency_details->currency_code : '';
			$response['base_code'] = $base_currency->currency_code;
		}
		
		echo json_encode($response);
	}
	
	public function get_base_currency(){
		$base_currency = get_base_currency();
		$response = array('status' => false);
		
		if ($base_currency) {
			$response['status'] = true;
			$response['currency_id'] = $base_currency->id;
			$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_customer_type(){
		$customer_id = $this->input->post('customer_id');
		$response = array('status' => false, 'customer_type' => '', 'default_price_type' => '');
		
		// Debug logging
		log_message('debug', 'Getting customer type for ID: ' . $customer_id);
		
		if (!empty($customer_id)) {
			$this->db->select('customer_type, default_price_type');
			$this->db->from('db_customers');
			$this->db->where('id', $customer_id);
			$customer = $this->db->get()->row();
			
			if ($customer) {
				$response['status'] = true;
				$response['customer_type'] = $customer->customer_type ?: 'retail';
				$response['default_price_type'] = $customer->default_price_type ?: 'retail';
				
				// Debug logging
				log_message('debug', 'Customer type: ' . $response['customer_type'] . ', Default price type: ' . $response['default_price_type']);
			} else {
				log_message('debug', 'No customer found with ID: ' . $customer_id);
			}
		}
		
		echo json_encode($response);
	}
}
