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

use App\Traits\InventorySchemaTrait;
use App\Traits\UpdateInfoTrait;

class Updated_queries extends CI_Model
{
	use InventorySchemaTrait;
	use UpdateInfoTrait;
	private $custom_db = null;
	private $custom_dbforge = null;
	protected $db;
	protected $dbforge;
	public function __construct()
	{
		parent::__construct();

		$this->load->database();
		$this->db = $this->load->database('', TRUE);

		$this->load->dbforge();
		$this->dbforge = $this->load->dbforge($this->db, TRUE);

		$this->db->query("SET sql_mode = ''");
	}

	public function set_custom_db($config)
	{
		try {
			$this->custom_db = $this->load->database($config, TRUE);

			$this->custom_dbforge = $this->load->dbforge($this->custom_db, TRUE);

			$this->custom_db->query("SET sql_mode = ''");

			return ['st' => 1, 'msg' => 'Database connected successfully'];
		} catch (Exception $e) {
			return ['st' => 0, 'msg' => 'Database connection failed: ' . $e->getMessage()];
		}
	}

	public function install_version($version, $current_version = null, $is_custom = false)
	{
		// Switch database connection if custom
		if ($is_custom && $this->custom_db) {
			$original_db = $this->db;
			$original_dbforge = $this->dbforge;
			$this->db = $this->custom_db;
			$this->dbforge = $this->custom_dbforge;
		}

		$data = [];

		$settings = $is_custom ? [] : settings();
		$language = isset($settings['language']) ? $settings['language'] : 'english';
		$current_version = $is_custom ? $current_version : NEW_VERSION;

		if ($version >= $current_version) {
			return ['st' => 1, 'msg' => 'Already updated', 'version' => $version];
		}

		do {

			if ($version > 1.2 && $version < 2.4) {
				$new_version = 2.4;
				$data = ['st' => 3, "msg" => 'You have to update it from using YOUR_URL/update', 'version' => $new_version];
				break;
			}

			if (!function_exists('check_versions')) {
				include APPPATH . "config/update_logs.php";
			}

			$update_result = check_versions($version, $this);
			if ($update_result) {
				$data = $update_result;
				break;
			}
			//----------------------
			// New version
			//----------------------

			if ($version < '3.4.0') {
				$new_version = '3.4.0';
				


				$addColumnQueries = [
					'settings' => [
						'layouts' => "int(2) NOT NULL DEFAULT 1",
						'gradient_color' => "varchar(100) NULL",
					],

				];

				$addColumn = $this->sql_command($addColumnQueries);

				$keywords = [
					'home_modules' => ['details' => 'Home Module', 'english' => 'Home modules'],
					'show_print_btn_order_success' => ['details' => 'Show print button in pos order success page', 'english' => 'Show print button in pos order success page'],
					'automated_print' => ['details' => 'Automated print', 'english' => 'Automated print'],
					'copies' => ['details' => 'Copies', 'english' => 'Copies'],
					'theme' => ['details' => 'Theme', 'english' => 'Theme'],
				];

				$this->insertLanguage($keywords);

				if (isset($addColumn['st']) && $addColumn['st'] == 0):
					$data = ["st" => 0, "msg" => $addColumn['msg'], 'version' => $new_version];
				else:
					$data = ['st' => 1, "msg" => 'Updated Successfully', 'version' => $new_version];
				endif;
			}


			if ($version < '3.3.9') {
				$new_version = '3.3.9';
				if (!$this->db->table_exists('home_module_title_list')):
					$this->db->query('CREATE TABLE `home_module_title_list` (
						`id` int(11) NOT NULL AUTO_INCREMENT,
						`name` VARCHAR(100) NULL,
						`icon` VARCHAR(200) NULL,
						`language` VARCHAR(50) NULL,
						`status` int(11) NOT NULL DEFAULT 1,
						`created_at` datetime NOT NULL,
						PRIMARY KEY (`id`)
					) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;');
				endif;

				if (!$this->db->table_exists('home_module_list')):
					$this->db->query('CREATE TABLE `home_module_list` (
						`id` int(11) NOT NULL AUTO_INCREMENT,
						`module_id` int(11) NOT NULL,
						`module_details` LONGTEXT NULL,
						`language` VARCHAR(50) NULL,
						`status` int(11) NOT NULL DEFAULT 1,
						PRIMARY KEY (`id`)
					) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;');
				endif;


				$addColumnQueries = [
					'settings' => [
						'layouts' => "int(2) NOT NULL DEFAULT 1",
						'gradient_color' => "varchar(100) NULL",
					],

					'users' => [
						'google_id' => "varchar(255) NULL",
						'google_email' => "varchar(100) NULL",
						'email_verified' => "int(2) NOT NULL DEFAULT 0",
						'picture' => "varchar(255) NULL",
					],
					'staff_list' => [
						'google_id' => "varchar(255) NULL",
						'google_email' => "varchar(100) NULL",
						'email_verified' => "int(2) NOT NULL DEFAULT 0",
						'picture' => "varchar(255) NULL",
					],

					'customer_list' => [
						'google_id' => "varchar(255) NULL",
						'google_email' => "varchar(100) NULL",
						'email_verified' => "int(2) NOT NULL DEFAULT 0",
						'picture' => "varchar(255) NULL",
					],

				];

				$addColumn = $this->sql_command($addColumnQueries);

				$keywords = [
					'google_login' => ['details' => 'Google login', 'english' => 'Google login'],
					'client_id' => ['details' => 'Google client ID', 'english' => 'client ID'],
					'google_auth_credentials' => ['details' => 'Google auth credentials', 'english' => 'Google auth credentials'],
					'connect_it_from_your_user_panel_first' => ['details' => 'Connect it from your user panel first', 'english' => 'connect it from your user panel first'],
					'no_account_found_associated_with_this' => ['details' => 'No account found associated with this', 'english' => 'No account found associated with this'],
					'want_to_unlink_google_account' => ['details' => 'Want to unlink? have to connect new account again', 'english' => 'Want to unlink? have to connect new account again'],
					'try_different_one' => ['details' => 'Try different one', 'english' => 'Try different one'],
					'google_account_connected' => ['details' => 'Google Account Connected', 'english' => 'Google Account Connected'],
					'or_sign_in_with_email' => ['details' => 'Or sign in with email/username', 'english' => 'or sign in with email/username'],
					'social_login' => ['details' => 'Social login', 'english' => 'Social login'],
					'sign_in_with_google' => ['details' => 'Sign in with Google', 'english' => 'Sign in with Google'],
					'why_choose_section' => ['details' => 'Why choose section', 'english' => 'Why choose section'],
					'gradient_color' => ['details' => 'Gradient color', 'english' => 'Gradient color'],
					'module_sub_heading' => ['details' => 'Cloud POS, online store, digital menu, and offline mode — everything to run your business efficiently.', 'english' => 'Cloud POS, online store, digital menu, and offline mode — everything to run your business efficiently.'],
					'module_heading' => ['details' => 'Powerful Tools for Operations', 'english' => 'Powerful Tools for Operations'],
					'setup_in_minutes' => ['details' => 'Setup In 5 Minutes', 'english' => 'Setup In 5 Minutes'],
					'contact_less' => ['details' => 'Contact less', 'english' => 'Contact less'],
					'app_slogan' => ['details' => 'Restaurant • Café • Bakery • Supermarket • Online Store', 'english' => 'Restaurant • Café • Bakery • Supermarket • Online Store'],
				];

				$this->insertLanguage($keywords);

				if (isset($addColumn['st']) && $addColumn['st'] == 0):
					$data = ["st" => 0, "msg" => $addColumn['msg'], 'version' => $new_version];
				else:
					$data = ['st' => 1, "msg" => 'Updated Successfully', 'version' => $new_version];
				endif;
			}

			
			/*----------------------------------------------
					  VERSION END 
					  ----------------------------------------------*/
					} while ($version == $current_version);

		// Restore original database connection if using custom
					if ($is_custom && $this->custom_db) {
						$this->db = $original_db;
						$this->dbforge = $original_dbforge;
					}

					if (empty($data)) {
						$data = ['st' => 1, 'msg' => 'Already updated', 'version' => $version];
					}

					return $data;
	} //install_version
}
