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

use Dompdf\Dompdf;
use Dompdf\Options;

class Quotation extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('quotation_model','quotation');
		$this->load->helper('sms_template_helper');
		$this->load->helper('multi_currency_helper');
	}

	public function is_sms_enabled(){
		return is_sms_enabled();
	}

	public function index()
	{
		$this->permission_check('quotation_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('quotation_list');
		$this->load->view('quotation/quotation_list',$data);
	}
	public function add()
	{	
		$this->permission_check('quotation_add');
		$data=$this->data;
		
		// Set base currency information for new quotations
		$base_currency = get_base_currency();
		if ($base_currency) {
			$data['quotation_currency_symbol'] = $base_currency->symbol;
			$data['quotation_currency_code'] = $base_currency->currency_code;
			$data['quotation_currency_id'] = $base_currency->id;
		} else {
			// If no base currency found, let the view handle it
			$data['quotation_currency_symbol'] = '';
			$data['quotation_currency_code'] = '';
			$data['quotation_currency_id'] = 0;
		}
		
		$data['page_title']=$this->lang->line('quotation');
		$this->load->view('quotation/quotation',$data);
	}
	

	public function quotation_save_and_update(){
		$this->form_validation->set_rules('quotation_date', 'Quotation Date', 'trim|required');
		$this->form_validation->set_rules('customer_id', 'Customer Name', 'trim|required');
		
		if ($this->form_validation->run() == TRUE) {
	    	$result = $this->quotation->verify_save_and_update();
	    	
	    	
	    	echo $result;
		} else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}
	
	
	public function update($id){
		$this->belong_to('db_quotation',$id);
		$this->permission_check('quotation_edit');
		$data=$this->data;
		$data=array_merge($data,array('quotation_id'=>$id));
		
		// Load quotation details including currency information
		$quotation = $this->db->select('*')->where('id', $id)->get('db_quotation')->row();
		if ($quotation) {
			$data['quotation_currency_id'] = $quotation->quotation_currency_id;
			$data['quotation_currency_symbol'] = '';
			$data['quotation_currency_code'] = '';
			
			// Get currency information
			if (!empty($quotation->quotation_currency_id)) {
				$currency = $this->db->select('symbol, currency_code')->where('id', $quotation->quotation_currency_id)->get('db_currency')->row();
				if ($currency) {
					$data['quotation_currency_symbol'] = $currency->symbol;
					$data['quotation_currency_code'] = $currency->currency_code;
				} else {
					// Fallback to base currency if quotation currency not found
					$base_currency = get_base_currency();
					if ($base_currency) {
						$data['quotation_currency_symbol'] = $base_currency->symbol;
						$data['quotation_currency_code'] = $base_currency->currency_code;
						$data['quotation_currency_id'] = $base_currency->id;
					} else {
						$data['quotation_currency_symbol'] = '';
						$data['quotation_currency_code'] = '';
						$data['quotation_currency_id'] = 0;
					}
				}
			} else {
				// No quotation currency set, use base currency
				$base_currency = get_base_currency();
				if ($base_currency) {
					$data['quotation_currency_symbol'] = $base_currency->symbol;
					$data['quotation_currency_code'] = $base_currency->currency_code;
					$data['quotation_currency_id'] = $base_currency->id;
				} else {
					$data['quotation_currency_symbol'] = '';
					$data['quotation_currency_code'] = '';
					$data['quotation_currency_id'] = 0;
				}
			}
		} else {
			// Quotation not found, use base currency
			$base_currency = get_base_currency();
			if ($base_currency) {
				$data['quotation_currency_symbol'] = $base_currency->symbol;
				$data['quotation_currency_code'] = $base_currency->currency_code;
				$data['quotation_currency_id'] = $base_currency->id;
			} else {
				$data['quotation_currency_symbol'] = '';
				$data['quotation_currency_code'] = '';
				$data['quotation_currency_id'] = 0;
			}
		}
		
		$data['page_title']=$this->lang->line('quotation');
		$this->load->view('quotation/quotation', $data);
	}
	

	public function ajax_list()
	{
		$list = $this->quotation->get_datatables();
		
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $quotation) {
			
			$no++;
			$row = array();
			$row[] = '<input type="checkbox" name="checkbox[]" value='.$quotation->id.' class="checkbox column_checkbox" >';
			
			$str='';
			        if($quotation->sales_status!='')
			          $str="<span title='Converted to Sales Invoice' class='label label-success' style='cursor:pointer'> Converted </span>";
			$row[] = show_date($quotation->quotation_date)."<br>".$str;
			$row[] = (!empty($quotation->expire_date)) ? show_date($quotation->expire_date) : '';

			$row[] = $quotation->quotation_code;
			
			$row[] = $quotation->reference_no;
			$row[] = $quotation->customer_name;
			
			// Display total with currency information
			$base_currency = get_base_currency();
			$total_display = store_number_format($quotation->grand_total);
			
			// Get transaction currency
			$transaction_currency = null;
			if (!empty($quotation->quotation_currency_id)) {
				$transaction_currency = get_currency_by_id($quotation->quotation_currency_id);
			} elseif (!empty($quotation->customer_id)) {
				// Fallback to customer's trading currency
				$transaction_currency = get_customer_trading_currency($quotation->customer_id);
			}
			
			// If no transaction currency found, use base currency
			if (!$transaction_currency) {
				$transaction_currency = $base_currency;
			}
			
			// Check if we need to convert (if transaction currency is different from base currency)
			if ($transaction_currency->id != $base_currency->id) {
				// Get exchange rate
				$exchange_rate = get_exchange_rate($transaction_currency->id, $base_currency->id);
				
				// Check if we got a valid exchange rate
				$has_exchange_rate = $this->check_exchange_rate_exists($transaction_currency->id, $base_currency->id);
				
				if ($has_exchange_rate && $exchange_rate != 1.000000) {
					// Convert amount to base currency
					$converted_total = convert_currency($quotation->grand_total, $transaction_currency->id, $base_currency->id);
					$conversion_note = ' (Rate: 1 ' . $transaction_currency->currency_code . ' = ' . number_format($exchange_rate, 6) . ' ' . $base_currency->currency_code . ')';
					$total_display = '<strong>' . store_number_format($converted_total) . ' ' . $base_currency->currency_code . '</strong><br><small class="text-muted">' . store_number_format($quotation->grand_total) . ' ' . $transaction_currency->currency_code . $conversion_note . '</small>';
				} else {
					// No exchange rate available
					$conversion_note = ' <span class="text-warning" title="Exchange rate not found">⚠ No exchange rate</span>';
					$total_display = '<strong>' . store_number_format($quotation->grand_total) . ' ' . $transaction_currency->currency_code . '</strong><br><small class="text-muted">' . $conversion_note . '</small>';
				}
			} else {
				// Same currency, no conversion needed
				$total_display = '<strong>' . store_number_format($quotation->grand_total) . ' ' . $base_currency->currency_code . '</strong>';
			}
			$row[] = $total_display;
			$row[] = ($quotation->created_by);

					 $str1=base_url().'quotation/update/';

					$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('sales_add') && $quotation->sales_status=='')
											$str2.='<li>
												<a title="Convert to Invoice" href="'.base_url().'sales/quotation/'.$quotation->id.'" >
													<i class="fa fa-fw fa-exchange text-blue"></i>Convert to Invoice
												</a>
											</li>';

											if($quotation->sales_status=='Converted')
											$str2.='<li>
												<a title="View to Invoice" href="'.base_url().'sales/invoice/'.get_sales_id_of_quotation($quotation->id).'" >
													<i class="fa fa-fw fa-eye text-blue"></i>View Sales Invoice
												</a>
											</li>';

											if($this->permissions('quotation_view'))
											$str2.='<li>
												<a title="View Invoice" href="'.base_url().'quotation/invoice/'.$quotation->id.'" >
													<i class="fa fa-fw fa-eye text-blue"></i>View Quotation
												</a>
											</li>';

											if($this->permissions('quotation_edit'))
											$str2.='<li>
												<a title="Update Record ?" href="'.$str1.$quotation->id.'">
													<i class="fa fa-fw fa-edit text-blue"></i>Edit
												</a>
											</li>';

											if($this->permissions('quotation_add') || $this->permissions('quotation_edit'))
											$str2.='<li>
												<a title="Take Print" target="_blank" href="'.base_url().'quotation/print_invoice/'.$quotation->id.'">
													<i class="fa fa-fw fa-print text-blue"></i>Print
												</a>
											</li>

											<li>
												<a title="Download PDF" target="_blank" href="'.base_url().'quotation/pdf/'.$quotation->id.'">
													<i class="fa fa-fw fa-file-pdf-o text-blue"></i>PDF
												</a>
											</li>';

											if($this->permissions('quotation_delete'))
											$str2.='<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_quotation(\''.$quotation->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->quotation->count_all(),
						"recordsFiltered" => $this->quotation->count_filtered(),
						"data" => $data,
				);
		//output to json format
		echo json_encode($output);
	}
	public function update_status(){
		$this->permission_check('quotation_edit');
		$id=$this->input->post('id');
		$status=$this->input->post('status');

		
		$result=$this->quotation->update_status($id,$status);
		return $result;
	}
	public function delete_quotation(){
		$this->permission_check_with_msg('quotation_delete');
		$id=$this->input->post('q_id');
		echo $this->quotation->delete_quotation($id);
	}
	public function multi_delete(){
		$this->permission_check_with_msg('quotation_delete');
		$ids=implode (",",$_POST['checkbox']);
		echo $this->quotation->delete_quotation($ids);
	}


	//Table ajax code
	public function search_item(){
		$q=$this->input->get('q');
		$result=$this->quotation->search_item($q);
		echo $result;
	}
	public function find_item_details(){
		$id=$this->input->post('id');
		
		$result=$this->quotation->find_item_details($id);
		echo $result;
	}

	//quotation invoice form
	public function invoice($id)
	{	
		$this->belong_to('db_quotation',$id);
		if(!$this->permissions('quotation_view')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data=array_merge($data,array('quotation_id'=>$id));
		$data['page_title']=$this->lang->line('quotation_invoice');
		$this->load->view('quotation/quotation-invoice',$data);
	}
	
	//Print quotation invoice 
	public function print_invoice($quotation_id)
	{
		$this->belong_to('db_quotation',$quotation_id);
		if(!$this->permissions('quotation_add') && !$this->permissions('quotation_edit')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data=array_merge($data,array('quotation_id'=>$quotation_id));
		$data['page_title']=$this->lang->line('quotation_invoice');
		
			$this->load->view('quotation/print-quotation-invoice-2',$data);
		
	}


	public function pdf($quotation_id){
		if(!$this->permissions('quotation_add') && !$this->permissions('quotation_edit')){
			$this->show_access_denied_page();
		}
		
		$data=$this->data;
		$data['page_title']=$this->lang->line('quotation_invoice');
        $data=array_merge($data,array('quotation_id'=>$quotation_id));
      
			$this->load->view('quotation/print-quotation-invoice-2',$data);
		
       

        // Get output html
        $html = $this->output->get_output();
        $options = new Options();
		$options->set('isRemoteEnabled', true);
        $dompdf = new Dompdf($options);

        // Load HTML content
        $dompdf->loadHtml($html,'UTF-8');
        
        // (Optional) Setup the paper size and orientation
        $dompdf->setPaper('A4', 'portrait');/*landscape or portrait*/
        
        // Render the HTML as PDF
        $dompdf->render();
        
        // Output the generated PDF (1 = download and 0 = preview)
        $dompdf->stream("Quotation_$quotation_id-".date('M')."_".date('d')."_".date('Y'), array("Attachment"=>0));
	}
	
	

	
	/*v1.1*/
	public function return_row_with_data($rowcount,$item_id){
		echo $this->quotation->get_items_info($rowcount,$item_id);
	}
	public function return_quotation_list($quotation_id){
		echo $this->quotation->return_quotation_list($quotation_id);
	}
	
	public function show_pay_now_modal(){
		$this->permission_check_with_msg('quotation_view');
		$quotation_id=$this->input->post('quotation_id');
		echo $this->quotation->show_pay_now_modal($quotation_id);
	}
	public function save_payment(){
		$this->permission_check_with_msg('quotation_add');
		echo $this->quotation->save_payment();
	}
	public function view_payments_modal(){
		$this->permission_check_with_msg('quotation_view');
		$quotation_id=$this->input->post('quotation_id');
		echo $this->quotation->view_payments_modal($quotation_id);
	}
	public function get_customers_select_list(){
		echo get_customers_select_list_for_quotation(null,$_POST['store_id']);
	}
	public function get_items_select_list(){
		echo get_items_select_list(null,$_POST['store_id']);
	}
	public function get_tax_select_list(){
		echo get_tax_select_list(null,$_POST['store_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_customer_type(){
		$customer_id = $this->input->post('customer_id');
		$response = array('status' => false, 'customer_type' => '', 'default_price_type' => '');
		
		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';
			}
		}
		
		echo json_encode($response);
	}
	/*Get warehouse select list*/
	public function get_warehouse_select_list(){
		echo get_warehouse_select_list(null,$_POST['store_id']);
	}
	//Print quotation Payment Receipt
	public function print_show_receipt($payment_id){
		if(!$this->permissions('quotation_add') && !$this->permissions('quotation_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 get_users_select_list(){
		echo get_users_select_list($this->session->userdata("role_id"),$_POST['store_id']);
	}

	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 check_currency_availability(){
		$customer_id = $this->input->post('customer_id');
		$response = array('success' => true, 'message' => '');
		
		if (!empty($customer_id)) {
			$customer_currency = get_customer_trading_currency($customer_id);
			$base_currency = get_base_currency();
			
			if ($customer_currency && $customer_currency->id != $base_currency->id) {
				$exchange_rate = get_exchange_rate($base_currency->id, $customer_currency->id);
				
				if ($exchange_rate == 1.0) {
					$response['success'] = false;
					$response['message'] = "No exchange rate found for {$base_currency->currency_name} to {$customer_currency->currency_name}. Please add an exchange rate in Exchange Rates Management.";
				}
			}
		}
		
		echo json_encode($response);
	}

	public function get_item_price_in_customer_currency(){
		$item_id = $this->input->post('item_id');
		$customer_id = $this->input->post('customer_id');
		$response = array('status' => false, 'converted_price' => '', 'currency_symbol' => '');

		if (!empty($item_id) && !empty($customer_id)) {
			// Get item details
			$item = $this->db->select('sales_price')->from('db_items')->where('id', $item_id)->get()->row();
			
			if ($item) {
				$customer_currency = get_customer_trading_currency($customer_id);
				$base_currency = get_base_currency();
				
				$sales_price = $item->sales_price;
				
				// If customer has different currency, convert the price
				if ($customer_currency && $customer_currency->id != $base_currency->id) {
					$exchange_rate = get_exchange_rate($base_currency->id, $customer_currency->id);
					
					if ($exchange_rate && $exchange_rate > 0) {
						$converted_price = $sales_price * $exchange_rate;
						$response['status'] = true;
						$response['converted_price'] = number_format($converted_price, 2, '.', '');
						$response['currency_symbol'] = $customer_currency->symbol;
						$response['exchange_rate'] = $exchange_rate;
					} else {
						$response['status'] = false;
						$response['message'] = 'No exchange rate available between ' . $base_currency->currency_code . ' and ' . $customer_currency->currency_code;
					}
				} else {
					// Same currency, no conversion needed
					$response['status'] = true;
					$response['converted_price'] = number_format($sales_price, 2, '.', '');
					$response['currency_symbol'] = $base_currency->symbol;
				}
			}
		}
		
		echo json_encode($response);
	}
}
