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

//use chillerlan\QRCode\{QRCode, QROptions};


class Pos extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('pos_model','pos_model');
		$this->load->model('sales_types_model','sales_types');
		$this->load->helper('sms_template_helper');
	}

	public function is_sms_enabled(){
		return is_sms_enabled();
	}
	
	public function index()
	{
		$this->permission_check('pos');
		$data=$this->data;

		//Sales Code
		$init_code=get_only_init_code('sales');
      	$count_id=get_last_count_id('db_sales');

		$data['page_title']='POS';
		$data['init_code']=$init_code;
		$data['count_id']=$count_id;
		
		//Load Sales Types
		$data['sales_types'] = $this->get_all_sales_types();
		
		//Get default sales type from store settings (you can add this to store configuration)
		$default_sales_type_query = $this->db->query("SELECT id FROM db_sales_types WHERE store_id = ? AND status = 1 ORDER BY id ASC LIMIT 1", [get_current_store_id()]);
		$data['default_sales_type_id'] = ($default_sales_type_query->num_rows() > 0) ? $default_sales_type_query->row()->id : '';

		$data['warehouse_id'] = '';
		$data['result'] = $this->get_hold_invoice_list();
		$data['tot_count'] = $this->get_hold_invoice_count();
		$this->load->view('pos',$data);
	}

	//adding new item from Modal
	public function newcustomer(){
	
		$this->form_validation->set_rules('customer_name', 'Customer Name', 'trim|required');
		
		if ($this->form_validation->run() == TRUE) {
			$this->load->model('customers_model');
			$result=$this->customers_model->verify_and_save();
			//fetch latest item details
			$res=array();
			$query=$this->db->query("select id,customer_name from db_customers order by id desc limit 1");
			$res['id']=$query->row()->id;
			$res['customer_name']=$query->row()->customer_name;
			$res['result']=$result;
			
			echo json_encode($res);

		} 
		else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}

	public function get_details(){
		echo $this->pos_model->get_details();
	}
	public function receive_order(){
	    echo $this->pos_model->receive_order();
	}
	public function pos_save_update(){
	    $response = $this->pos_model->pos_save_update();

	    $explode = explode("<<<###>>>",$response);
	    if($explode[0]=='success'){
	    	// Get sales type initial and count ID from the selected sales type instead of store settings
	    	$sales_type_id = $this->input->post('sales_type_id');
	    	$init_code_from_form = $this->input->post('init_code'); // Get the init_code that was actually saved
	    	$count_id_from_form = $this->input->post('count_id'); // Get the count_id that was actually saved
	    	
	    	if(!empty($sales_type_id)){
	    		// Get sales type initial for verification
	    		$this->db->select('sales_type_initial');
	    		$this->db->where('id', $sales_type_id);
	    		$this->db->where('store_id', get_current_store_id());
	    		$sales_type = $this->db->get('db_sales_types')->row();
	    		$init_code = $sales_type ? $sales_type->sales_type_initial : $init_code_from_form;
	    		
	    		// Use the count_id from the form since it's the one that was actually saved
	    		$count_id = $count_id_from_form;
	    	} else {
	    		// Fallback to form values if no sales type selected
	    		$init_code = $init_code_from_form ? $init_code_from_form : get_only_init_code('sales');
	    		$count_id = $count_id_from_form ? $count_id_from_form : get_last_count_id('db_sales');
	    	}
      		$customer_id = $_REQUEST['customer_id'];
      		$customer_details=get_customer_details($customer_id);
      		
      		// Use new accurate calculation functions
      		$customer_remaining_advance=$customer_details->tot_advance;
      		$customer_previous_due=get_customer_actual_due($customer_id);
      		$customer_balance=get_customer_account_balance($customer_id);
      		
	    	$response .="<<<###>>>".$init_code."<<<###>>>".$count_id."<<<###>>>".$customer_remaining_advance."<<<###>>>".$customer_previous_due."<<<###>>>".$customer_balance;
	    }
	    echo $response;
	}
	public function edit($sales_id){
		$this->belong_to('db_sales',$sales_id);
		$this->permission_check('sales_edit');
	    $data=$this->data;
	    $data['sales_id']=$sales_id;
	    $data['page_title']='POS Update';

	    //Get sales details
	    $sales_details = get_sales_details($sales_id);
	    $customer_id = $sales_details->customer_id;
	    $init_code = $sales_details->init_code;
	    $count_id = $sales_details->count_id;

	    $data['warehouse_id'] = '';
	    
	    $data['customer_id']=$customer_id;
	    $data['init_code']=$init_code;
	    $data['count_id']=$count_id;
	    
	    //Load Sales Types for edit mode
	    $data['sales_types'] = $this->get_all_sales_types();
	    
	    //Get default sales type from store settings
	    $default_sales_type_query = $this->db->query("SELECT id FROM db_sales_types WHERE store_id = ? AND status = 1 ORDER BY id ASC LIMIT 1", [get_current_store_id()]);
	    $data['default_sales_type_id'] = ($default_sales_type_query->num_rows() > 0) ? $default_sales_type_query->row()->id : '';
	    
	    $data['result'] = $this->get_hold_invoice_list();
		$data['tot_count'] = $this->get_hold_invoice_count();
		$this->load->view('pos',$data);
	}
	public function fetch_sales($sales_id){
	    $result=$this->pos_model->edit_pos($sales_id);
	}
	/* ######################################## HOLD INVOICE ############################# */
	public function hold_invoice(){
	    echo $this->pos_model->hold_list_save_update();
	}
	public function hold_invoice_list(){
		$data =array();
		$data['result'] = $this->get_hold_invoice_list();
		$data['tot_count'] = $this->get_hold_invoice_count();
		echo json_encode($data);
	}

	public function get_hold_invoice_list(){
		$data =array();
		$result= $this->pos_model->hold_invoice_list();
		return $result;
	}
	public function get_hold_invoice_count(){
		$q1=$this->db->query("SELECT * FROM db_hold WHERE store_id=".get_current_store_id());
		return $q1->num_rows();
	}
	public function hold_invoice_delete($invoice_id){
		$result=$this->pos_model->hold_invoice_delete($invoice_id);
		echo trim($result);
	}
	public function hold_invoice_edit(){
		echo $this->pos_model->hold_invoice_edit();
	}
	public function add_payment_row(){
		return $this->load->view('modals_pos_payment/modal_payments_multi_sub');
	}

	public function print_qr($data='')
	{
		$this->load->model('Qrcode_model','qr');

		return $this->qr->qr_image($data);

		exit;

		$data  = trim($data);	

		//if the parameter value has slash
		$data = base64_decode(str_replace('-', '=', str_replace('_', '/', $data)));

		// quick and simple:
		//return '<img src="'.(new QRCode)->render($data).'" alt="QR Code" />';
		$options = new QROptions([
			
		]);

		return (!empty($data)) ? '<img src="'.(new QRCode($options))->render($data).'" alt="QR Code" />' : '';		
	}

	//Print sales POS invoice 
	public function print_invoice_pos($sales_id){
		if(!$this->permissions('sales_add') && !$this->permissions('sales_edit')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data['page_title']=$this->lang->line('sales_invoice');
		$data=array_merge($data,array('sales_id'=>$sales_id));
		
		$this->load->view('sal-invoice-pos',$data);
		
	}
	public function get_item_details(){
		echo $this->pos_model->get_item_details($this->input->post('item_id'));
	}
	
	public function collect_customer_payment(){
		$this->permission_check('pos');
		
		$customer_id = $this->input->post('customer_id');
		$amount = $this->input->post('amount');
		$payment_type = $this->input->post('payment_type');
		$payment_note = $this->input->post('payment_note');
		
		// Validation
		if(empty($customer_id) || $customer_id == 1){
			echo "Error: Invalid customer selected";
			return;
		}
		
		if(empty($amount) || $amount <= 0){
			echo "Error: Invalid payment amount";
			return;
		}
		
		// Get customer's current due
		$customer_due = get_customer_actual_due($customer_id);
		
		// REMOVED: Payment validation to allow overpayments (credit balance)
		// Overpayments are now allowed and will create customer credit balance
		if($amount > $customer_due){
			// This will create a customer credit balance - allowed for better credit management
			// You can add logging here if needed
		}
		
		// Process the payment
		$result = $this->pos_model->process_customer_payment_collection($customer_id, $amount, $payment_type, $payment_note);
		
		if($result){
			echo "Success: Payment of " . store_number_format($amount) . " collected successfully";
		} else {
			echo "Error: Failed to process payment";
		}
	}

	//Get all sales types for dropdown
	public function get_all_sales_types(){
		return $this->sales_types->get_all_active_sales_types();
	}

	//Get invoice details based on sales type
	public function get_sales_type_invoice_details(){
		$sales_type_id = $this->input->post('sales_type_id');
		
		if(!$sales_type_id){
			echo json_encode(['error' => 'Invalid sales type']);
			return;
		}

		//Get sales type details
		$this->db->select('sales_type_initial');
		$this->db->where('id', $sales_type_id);
		$this->db->where('store_id', get_current_store_id());
		$sales_type = $this->db->get('db_sales_types')->row();

		if(!$sales_type){
			echo json_encode(['error' => 'Sales type not found']);
			return;
		}

		//Get next count ID for this sales type
		$count_id = $this->get_next_sales_type_count_id($sales_type_id);
		
		$result = [
			'init_code' => $sales_type->sales_type_initial,
			'count_id' => $count_id,
			'invoice_no' => $sales_type->sales_type_initial . str_pad($count_id, 4, '0', STR_PAD_LEFT)
		];

		echo json_encode($result);
	}

	//Get next count ID for specific sales type
	private function get_next_sales_type_count_id($sales_type_id){
		$store_id = get_current_store_id();
		
		// Get maximum count_id for this sales type and store
		$this->db->select_max('count_id');
		$this->db->where('sales_type_id', $sales_type_id);
		$this->db->where('store_id', $store_id);
		$query = $this->db->get('db_sales');
		
		$max_count = $query->row()->count_id;
		
		// Return next count ID
		return ($max_count) ? ($max_count + 1) : 1;
	}

}
