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

class Pos extends MY_Controller
{


	public function __construct()
	{
		parent::__construct();
		$this->load->library('zend');
		$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('sales_add');
		$data = $this->data;
		$data['page_title'] = 'POS';
		$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 get_details1()
	{

		echo $this->pos_model->get_details1();
	}
	public function receive_order()
	{
		echo $this->pos_model->receive_order();
	}
	public function pos_save_update()
	{
		$result = '';
		if ($this->input->post('command') == 'update') { //Update
			$result = $this->pos_model->pos_save_update();
		} else { //Save
			$result = $this->pos_model->pos_save_update();
			//$result =$result."<<<###>>>".$this->pos_model->get_details();
			$result = $result . "<<<###>>>" . $this->pos_model->hold_invoice_list();
			$q1 = $this->db->query("SELECT * FROM db_hold");
			$data['tot_count'] = $q1->num_rows();
			$result = $result . "<<<###>>>" . $q1->num_rows();
		}

		echo $result;
		exit();
	}
	public function edit($sales_id)
	{
		$this->permission_check('sales_edit');
		$data = $this->data;
		$data['sales_id'] = $sales_id;
		$data['page_title'] = 'POS Update';
		$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");
		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');
	}
	//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));
		// Adding company details including logo to $data
		$company_details = $this->get_company_details(); 
		$data['company_logo'] = $company_details['company_logo'];

		$this->load->view('sal-invoice-pos', $data);
	}

	// Method to fetch company details including logo
	private function get_company_details()
	{
		// Fetch company details from the database or wherever you have it
		$query = $this->db->query("SELECT * FROM db_company ORDER BY id ASC LIMIT 1");
		$company_details = array();
		if ($query->num_rows() > 0) {
			$row = $query->row();
			$company_details['company_logo'] = (!empty($row->company_logo)) ? $row->company_logo : base_url('theme/images/no_image2.png');
			// Add other company details to $company_details if needed
		}
		return $company_details;
	}
	public function get_item_details()
	{
		echo $this->pos_model->get_item_details($this->input->post('item_id'));
	}
	public function restore_database()
	{
		// Disable foreign key checks
		$this->db->query('SET FOREIGN_KEY_CHECKS=0');

		// Check if a file was uploaded
		if (isset($_FILES['backupFile']) && $_FILES['backupFile']['error'] === UPLOAD_ERR_OK) {
			$file = $_FILES['backupFile']['tmp_name'];

			// Read the contents of the file
			$sql = file_get_contents($file);

			if ($sql === false) {
				echo "Failed to read the SQL file.";
				return;
			}

			// Set line to collect lines that wrap
			$templine = '';

			// Read in entire file
			$lines = explode("\n", $sql);

			// Loop through each line
			foreach ($lines as $line) {
				// Skip it if it's a comment
				if (substr($line, 0, 2) == '--' || $line == '') {
					continue;
				}

				// Add this line to the current templine we are creating
				$templine .= $line;

				// If it has a semicolon at the end, it's the end of the query so can process this templine
				if (substr(trim($line), -1, 1) == ';') {
					// Check if the query is for dropping tables
					if (strpos($templine, 'DROP TABLE') !== false) {
						// Execute the drop table query
						$this->db->query($templine);
					} else {
						// Execute the query
						$this->db->query($templine);

						// Check if the query was for creating the db_sitesettings table
						if (strpos($templine, 'CREATE TABLE `db_sitesettings`') !== false) {
							// Insert default values into db_sitesettings
							$this->insert_default_settings();
						}
					}

					// Reset temp variable to empty
					$templine = '';
				}
			}

			echo "Database restored successfully!";
			// Destroy the session
			$this->session->sess_destroy();

			// Redirect to the login page
			redirect('login');
		} else {
			// Handle if no file was uploaded
			echo "No file uploaded or error occurred while uploading!";
		}

		// Re-enable foreign key checks
		$this->db->query('SET FOREIGN_KEY_CHECKS=1');
	}

	private function insert_default_settings()
	{
		// Perform INSERT queries to add default settings into db_sitesettings table
		// Example:
		// $this->db->query("INSERT INTO db_sitesettings (site_name, version, language_id, timezone, ...) VALUES ('Default Site', '1.0', 1, 'UTC', ...)");
	}
}
