<?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->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;
		$data['warehouse_id'] = '';
		// Hold list loaded via AJAX so initial POS page renders faster
		$data['result'] = '<tr><td colspan="4" class="text-center text-muted">Loading...</td></tr>';
		$data['tot_count'] = 0;
		$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(){

    // 🔥 SANITIZE ALL NUMERIC INPUTS (CRITICAL FIX)
    $_REQUEST['tot_qty']   = isset($_REQUEST['tot_qty'])   ? (float)str_replace(',', '', $_REQUEST['tot_qty'])   : 0;
    $_REQUEST['tot_amt']   = isset($_REQUEST['tot_amt'])   ? (float)str_replace(',', '', $_REQUEST['tot_amt'])   : 0;
    $_REQUEST['tot_disc']  = isset($_REQUEST['tot_disc'])  ? (float)str_replace(',', '', $_REQUEST['tot_disc'])  : 0;
    $_REQUEST['tot_grand'] = isset($_REQUEST['tot_grand']) ? (float)str_replace(',', '', $_REQUEST['tot_grand']) : 0;
    $_REQUEST['paid_amt']  = isset($_REQUEST['paid_amt'])  ? (float)str_replace(',', '', $_REQUEST['paid_amt'])  : 0;
    $_REQUEST['balance']   = isset($_REQUEST['balance'])   ? (float)str_replace(',', '', $_REQUEST['balance'])   : 0;

    // Optional: log incoming data for debugging
    // log_message('error', 'POS DATA: '.print_r($_REQUEST, true));

    try {

        $response = $this->pos_model->pos_save_update();

        $explode = explode("<<<###>>>",$response);

        if(isset($explode[0]) && $explode[0]=='success'){
            $init_code = get_only_init_code('sales');
            $count_id  = get_last_count_id('db_sales');
            $customer_remaining_advance = get_customer_details($_REQUEST['customer_id'])->tot_advance;

            $response .= "<<<###>>>".$init_code."<<<###>>>".$count_id."<<<###>>>".$customer_remaining_advance;
        }

        echo $response;

    } catch (Exception $e) {

        // 🔥 RETURN CLEAN ERROR (NO BLANK RESPONSE)
        log_message('error', 'POS SAVE ERROR: '.$e->getMessage());

        echo "error<<<###>>>".$e->getMessage();
    }
}
	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;
	    $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(){
		$row = $this->db->select('COUNT(*) as cnt')->where('store_id', get_current_store_id())->get('db_hold')->row();
		return $row ? (int) $row->cnt : 0;
	}
	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(){

	$item_id = $this->input->post('item_id');

	$unit_id        = $this->input->post('unit_id');
	$unit_name      = $this->input->post('unit_name');
	$conversion_qty = $this->input->post('conversion_qty');
	$sales_price    = $this->input->post('sales_price');
	$alternate_id   = $this->input->post('alternate_id');

	echo $this->pos_model->get_item_details(
		$item_id,
		$unit_id,
		$unit_name,
		$conversion_qty,
		$sales_price,
		$alternate_id
	);
}	
	public function return_row_with_data($rowcount,$item_id){
		echo $this->pos_model->get_items_info($rowcount,$item_id);
	}
	
	/**
	 * Get account information for Pay All functionality
	 * Returns account details with currency validation
	 */
	public function get_pay_all_account_info() {
		$store_id = get_current_store_id();
		$base_currency_id = get_base_currency()->id;
		
		// Get default account from store settings
		$store_details = get_store_details();
		$default_account_id = $store_details->default_account_id;
		
		$account_info = array(
			'success' => false,
			'message' => '',
			'account_id' => null,
			'account_name' => '',
			'currency_id' => null,
			'currency_code' => '',
			'needs_selection' => false
		);
		
		if (!empty($default_account_id)) {
			// Check if the default account uses base currency
			$this->db->select('a.id, a.account_name, a.currency_id, c.currency_code');
			$this->db->from('ac_accounts a');
			$this->db->join('db_currency c', 'c.id = a.currency_id', 'left');
			$this->db->where('a.id', $default_account_id);
			$this->db->where('a.store_id', $store_id);
			$this->db->where('(a.delete_bit = 0 OR a.delete_bit = 1)'); // Include both regular and cash accounts
			$this->db->where('a.status', 1); // Only active accounts
			$account = $this->db->get()->row();
			
			if ($account) {
				if ($account->currency_id == $base_currency_id) {
					// Default account uses base currency - good to use
					$account_info['success'] = true;
					$account_info['account_id'] = $account->id;
					$account_info['account_name'] = $account->account_name;
					$account_info['currency_id'] = $account->currency_id;
					$account_info['currency_code'] = $account->currency_code;
				} else {
					// Default account uses different currency - need selection
					$account_info['needs_selection'] = true;
					$account_info['message'] = 'Default account uses different currency. Please select a base currency account.';
				}
			} else {
				$account_info['needs_selection'] = true;
				$account_info['message'] = 'Default account not found. Please select an account.';
			}
		} else {
			$account_info['needs_selection'] = true;
			$account_info['message'] = 'No default account set. Please select an account.';
		}
		
		// If needs selection, get available base currency accounts
		if ($account_info['needs_selection']) {
			$this->db->select('a.id, a.account_name, c.currency_code');
			$this->db->from('ac_accounts a');
			$this->db->join('db_currency c', 'c.id = a.currency_id', 'left');
			$this->db->where('a.store_id', $store_id);
			$this->db->where('a.currency_id', $base_currency_id);
			$this->db->where('(a.delete_bit = 0 OR a.delete_bit = 1)'); // Include both regular and cash accounts
			$this->db->where('a.status', 1); // Only active accounts
			$this->db->order_by('a.account_name', 'ASC');
			$accounts = $this->db->get()->result();
			
			$account_info['available_accounts'] = $accounts;
		}
		
		echo json_encode($account_info);
	}
	
	/**
	 * Set account for Pay All functionality
	 * Stores the selected account in session temporarily
	 */
	public function set_pay_all_account() {
		$account_id = $this->input->post('account_id');
		$store_id = get_current_store_id();
		$base_currency_id = get_base_currency()->id;
		
		$response = array(
			'success' => false,
			'message' => ''
		);
		
		if (empty($account_id)) {
			$response['message'] = 'Account ID is required.';
			echo json_encode($response);
			return;
		}
		
		// Verify the account exists and uses base currency
		$this->db->select('id, account_name, currency_id');
		$this->db->where('id', $account_id);
		$this->db->where('store_id', $store_id);
		$this->db->where('currency_id', $base_currency_id);
		$this->db->where('(delete_bit = 0 OR delete_bit = 1)'); // Include both regular and cash accounts
		$this->db->where('status', 1); // Only active accounts
		$account = $this->db->get('ac_accounts')->row();
		
		if ($account) {
			// Store in session for this Pay All operation
			$this->session->set_userdata('pay_all_account_id', $account_id);
			$response['success'] = true;
			$response['message'] = 'Account set successfully.';
		} else {
			$response['message'] = 'Invalid account or account does not use base currency.';
		}
		
		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);
	}

	// ------------------------- Customer Display -------------------------

	/**
	 * Full-screen customer display page (open in second monitor/window)
	 */
	public function customer_display() {
		$this->permission_check('pos');
		$data = $this->data;
		$data['page_title'] = 'Customer Display';
		$this->load->view('customer_display', $data);
	}

	/**
	 * AJAX: Return current cart for customer display (from session, updated by sync_display_cart)
	 */
	public function customer_display_data() {
		header('Content-Type: application/json');
		$cart = $this->session->userdata('pos_display_cart');
		if (!is_array($cart)) {
			$cart = array('items' => array(), 'tot_qty' => 0, 'tot_amt' => 0, 'tot_disc' => 0, 'tot_grand' => 0, 'customer_name' => '', 'store_name' => $this->session->userdata('store_name'), 'currency' => '', 'paid_amount' => 0, 'payment_methods' => array(), 'balance_due' => 0, 'change_return' => 0);
		}
		if (!isset($cart['paid_amount'])) $cart['paid_amount'] = 0;
		if (!isset($cart['payment_methods'])) $cart['payment_methods'] = array();
		if (!isset($cart['balance_due'])) $cart['balance_due'] = 0;
		if (!isset($cart['change_return'])) $cart['change_return'] = 0;
		if (empty($cart['store_name'])) {
			$cart['store_name'] = $this->session->userdata('store_name');
		}
		if (empty($cart['currency']) && function_exists('get_base_currency')) {
			$bc = get_base_currency();
			$cart['currency'] = isset($bc->symbol) ? $bc->symbol : '';
		}
		echo json_encode($cart);
	}

	/**
	 * AJAX: Receive cart from POS and store in session for customer display
	 */
	public function sync_display_cart() {
		header('Content-Type: application/json');
		$raw = $this->input->post('cart');
		if (is_string($raw)) {
			$cart = json_decode($raw, true);
		} else {
			$cart = $raw;
		}
		if (!is_array($cart)) {
			$cart = array();
		}
		$data = array(
			'items'            => isset($cart['items']) ? $cart['items'] : array(),
			'tot_qty'          => isset($cart['tot_qty']) ? (float)$cart['tot_qty'] : 0,
			'tot_amt'          => isset($cart['tot_amt']) ? (float)$cart['tot_amt'] : 0,
			'tot_disc'         => isset($cart['tot_disc']) ? (float)$cart['tot_disc'] : 0,
			'tot_grand'        => isset($cart['tot_grand']) ? (float)$cart['tot_grand'] : 0,
			'customer_name'    => isset($cart['customer_name']) ? $cart['customer_name'] : '',
			'store_name'       => $this->session->userdata('store_name'),
			'paid_amount'      => isset($cart['paid_amount']) ? (float)$cart['paid_amount'] : 0,
			'payment_methods'  => isset($cart['payment_methods']) && is_array($cart['payment_methods']) ? $cart['payment_methods'] : array(),
			'balance_due'      => isset($cart['balance_due']) ? (float)$cart['balance_due'] : 0,
			'change_return'    => isset($cart['change_return']) ? (float)$cart['change_return'] : 0
		);
		if (function_exists('get_base_currency')) {
			$bc = get_base_currency();
			$data['currency'] = isset($bc->symbol) ? $bc->symbol : '';
		} else {
			$data['currency'] = '';
		}
		$this->session->set_userdata('pos_display_cart', $data);
		echo json_encode(array('success' => true));
	}


}
