<?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('whatsapp_model','whatsapp_model');
		$this->load->helper('sms_template_helper');
	}

	public function is_sms_enabled(){
		return is_sms_enabled();
	}
	
	public function is_whatsapp_enabled(){
		$store_details = get_store_details();
		return (isset($store_details->whatsapp_status) && $store_details->whatsapp_status == 1);
	}

	// Generate invoice image URL for WhatsApp
	public function get_invoice_image_url($sales_id) {
		// This method can be used to generate a shareable invoice image
		// For now, we'll return the print URL, but this could be enhanced
		// to generate actual image files
		return base_url() . "pos/print_invoice_pos/" . $sales_id . "?format=image";
	}
	
	public function index()
	{
		$this->permission_check('pos');
		$data=$this->data;

		//Default sales type (first active sales type)
		$default_sales_type = $this->db->select('id')
		                               ->where('status', 1)
		                               ->where('store_id', get_current_store_id())
		                               ->order_by('sort_order', 'ASC')
		                               ->limit(1)
		                               ->get('db_sales_types');
		
		$sales_type_id = ($default_sales_type->num_rows() > 0) ? $default_sales_type->row()->id : 6;

		//Sales Code based on sales type
		$init_code = get_sales_type_init_code($sales_type_id);
      	$count_id = get_sales_type_count_id($sales_type_id);

		$data['page_title']='POS';
		$data['init_code']=$init_code;
		$data['count_id']=$count_id;
		$data['sales_type_id']=$sales_type_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();
	}

	//Get invoice code and count based on sales type
	public function get_sales_type_invoice_data(){
		$sales_type_id = $this->input->post('sales_type_id');
		$init_code = get_sales_type_init_code($sales_type_id);
		$count_id = get_sales_type_count_id($sales_type_id);
		
		$response = array(
			'init_code' => $init_code,
			'count_id' => $count_id
		);
		
		echo json_encode($response);
	}

	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'){
	    	$sales_type_id = $this->input->post('sales_type_id') ? $this->input->post('sales_type_id') : 1;
	    	$init_code = get_sales_type_init_code($sales_type_id);
      		$count_id = get_sales_type_count_id($sales_type_id);
      		$customer_remaining_advance=get_customer_details($_REQUEST['customer_id'])->tot_advance;
	    	$response .="<<<###>>>".$init_code."<<<###>>>".$count_id."<<<###>>>".$customer_remaining_advance;
	    }
	    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;
	    $sales_type_id = isset($sales_details->sales_type_id) ? $sales_details->sales_type_id : 1;

	    $data['warehouse_id'] = '';
	    
	    $data['customer_id']=$customer_id;
	    $data['init_code']=$init_code;
	    $data['count_id']=$count_id;
	    $data['sales_type_id']=$sales_type_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));
		
		// Get store details to determine which template to use
		$store_details = get_store_details();
		$pos_format_id = $store_details->pos_invoice_format_id;
		
		// Load appropriate template based on format ID
		switch($pos_format_id) {
			case 3: // Simple format
				$this->load->view('sal-invoice-pos-simple',$data);
				break;
			case 4: // A5 Modern format
				$this->load->view('sal-invoice-pos-a5',$data);
				break;
			case 5: // A5 Simple format
				$this->load->view('sal-invoice-pos-a5-simple',$data);
				break;
			case 6: // A4 Professional format
				$this->load->view('sal-invoice-pos-a4',$data);
				break;
			case 7: // Thermal Printer format
				$this->load->view('sal-invoice-pos-thermal',$data);
				break;
			case 2: // GST format
			case 1: // Default format
			default:
				$this->load->view('sal-invoice-pos',$data);
				break;
		}
		
	}
	public function get_item_details(){
		echo $this->pos_model->get_item_details($this->input->post('item_id'));
	}

	public function get_daily_summary(){
		$this->permission_check('pos');
		
		$store_id = get_current_store_id();
		$today = date('Y-m-d');
		
		// Get today's sales summary
		$sales_query = "SELECT 
			COUNT(*) as total_sales,
			COALESCE(SUM(grand_total), 0) as total_sales_amount,
			COALESCE(SUM(grand_total - paid_amount), 0) as total_due_amount
			FROM db_sales 
			WHERE store_id = ? AND DATE(created_date) = ? AND status = 1";
		
		$sales_result = $this->db->query($sales_query, array($store_id, $today))->row();
		
		// Get today's expenses summary
		$expense_query = "SELECT 
			COUNT(*) as total_expenses,
			COALESCE(SUM(expense_amt), 0) as total_expense_amount
			FROM db_expense 
			WHERE store_id = ? AND DATE(created_date) = ? AND status = 1";
		
		$expense_result = $this->db->query($expense_query, array($store_id, $today))->row();
		
		// Get payments by mode for today
		$payment_mode_query = "SELECT 
			sp.payment_type,
			COUNT(*) as payment_count,
			COALESCE(SUM(sp.payment), 0) as payment_amount
			FROM db_salespayments sp
			INNER JOIN db_sales s ON sp.sales_id = s.id
			WHERE s.store_id = ? AND DATE(sp.created_date) = ? AND sp.status = 1
			GROUP BY sp.payment_type
			ORDER BY payment_amount DESC";
		
		$payment_modes = $this->db->query($payment_mode_query, array($store_id, $today))->result();
		
		// Get customer dues summary
		$customer_due_query = "SELECT 
			COUNT(DISTINCT customer_id) as customers_with_due,
			COALESCE(SUM(grand_total - paid_amount), 0) as total_customer_due
			FROM db_sales 
			WHERE store_id = ? AND status = 1 AND (grand_total - paid_amount) > 0";
		
		$customer_due_result = $this->db->query($customer_due_query, array($store_id))->row();
		
		// Calculate balance (Sales - Expenses)
		$balance = $sales_result->total_sales_amount - $expense_result->total_expense_amount;
		
		// Get total paid amount for today
		$paid_query = "SELECT COALESCE(SUM(paid_amount), 0) as total_paid_today
			FROM db_sales 
			WHERE store_id = ? AND DATE(created_date) = ? AND status = 1";
		
		$paid_result = $this->db->query($paid_query, array($store_id, $today))->row();
		
		$summary = array(
			'date' => $today,
			'store_id' => $store_id,
			'sales' => array(
				'count' => $sales_result->total_sales,
				'amount' => $sales_result->total_sales_amount,
				'due_amount' => $sales_result->total_due_amount,
				'paid_amount' => $paid_result->total_paid_today
			),
			'expenses' => array(
				'count' => $expense_result->total_expenses,
				'amount' => $expense_result->total_expense_amount
			),
			'balance' => $balance,
			'payment_modes' => $payment_modes,
			'customer_dues' => array(
				'customers_count' => $customer_due_result->customers_with_due,
				'total_amount' => $customer_due_result->total_customer_due
			)
		);
		
		echo json_encode($summary);
	}

	public function print_daily_summary(){
		$this->permission_check('pos');
		
		$store_id = get_current_store_id();
		$today = date('Y-m-d');
		
		// Get today's sales summary
		$sales_query = "SELECT 
			COUNT(*) as total_sales,
			COALESCE(SUM(grand_total), 0) as total_sales_amount,
			COALESCE(SUM(grand_total - paid_amount), 0) as total_due_amount
			FROM db_sales 
			WHERE store_id = ? AND DATE(created_date) = ? AND status = 1";
		
		$sales_result = $this->db->query($sales_query, array($store_id, $today))->row();
		
		// Get today's expenses summary
		$expense_query = "SELECT 
			COUNT(*) as total_expenses,
			COALESCE(SUM(expense_amt), 0) as total_expense_amount
			FROM db_expense 
			WHERE store_id = ? AND DATE(created_date) = ? AND status = 1";
		
		$expense_result = $this->db->query($expense_query, array($store_id, $today))->row();
		
		// Get payments by mode for today
		$payment_mode_query = "SELECT 
			sp.payment_type,
			COUNT(*) as payment_count,
			COALESCE(SUM(sp.payment), 0) as payment_amount
			FROM db_salespayments sp
			INNER JOIN db_sales s ON sp.sales_id = s.id
			WHERE s.store_id = ? AND DATE(sp.created_date) = ? AND sp.status = 1
			GROUP BY sp.payment_type
			ORDER BY payment_amount DESC";
		
		$payment_modes = $this->db->query($payment_mode_query, array($store_id, $today))->result();
		
		// Get customer dues summary
		$customer_due_query = "SELECT 
			COUNT(DISTINCT customer_id) as customers_with_due,
			COALESCE(SUM(grand_total - paid_amount), 0) as total_customer_due
			FROM db_sales 
			WHERE store_id = ? AND status = 1 AND (grand_total - paid_amount) > 0";
		
		$customer_due_result = $this->db->query($customer_due_query, array($store_id))->row();
		
		// Get total paid amount for today
		$paid_query = "SELECT COALESCE(SUM(paid_amount), 0) as total_paid_today
			FROM db_sales 
			WHERE store_id = ? AND DATE(created_date) = ? AND status = 1";
		
		$paid_result = $this->db->query($paid_query, array($store_id, $today))->row();
		
		// Calculate balance (Sales - Expenses)
		$balance = $sales_result->total_sales_amount - $expense_result->total_expense_amount;
		
		// Prepare data for the view
		$data = array(
			'date' => $today,
			'store_id' => $store_id,
			'sales' => array(
				'count' => $sales_result->total_sales,
				'amount' => $sales_result->total_sales_amount,
				'due_amount' => $sales_result->total_due_amount,
				'paid_amount' => $paid_result->total_paid_today
			),
			'expenses' => array(
				'count' => $expense_result->total_expenses,
				'amount' => $expense_result->total_expense_amount
			),
			'balance' => $balance,
			'payment_modes' => $payment_modes,
			'customer_dues' => array(
				'customers_count' => $customer_due_result->customers_with_due,
				'total_amount' => $customer_due_result->total_customer_due
			)
		);
		
		$this->load->view('daily-summary-print', $data);
	}

}
