<?php
class Database {


	function check_database($data)
	{
            mysqli_report(MYSQLI_REPORT_OFF); // disable warnings, handle manually

            try {
            	$db = new mysqli(
            		$data['db_hostname'], 
            		$data['db_username'], 
            		html_entity_decode($data['db_password'], ENT_QUOTES, 'UTF-8'), 
            		$data['db_name']
            	);

            	if ($db->connect_errno) {
            		return [
            			'st'  => 0,
            			'msg' => "Error: Could not connect to the database. {$db->connect_error}"
            		];
            	}

            	$db->close();
            	return ['st' => 1, 'msg' => ""];

            } catch (mysqli_sql_exception $e) {
            	return [
            		'st'  => 0,
            		'msg' => "Error: Could not connect to the database. " . $e->getMessage()
            	];
            } catch (Exception $e) {
            	return [
            		'st'  => 0,
            		'msg' => "Error: Unexpected error. " . $e->getMessage()
            	];
            }
        }


        function install($data)
        {
   		 // Connect to database
        	$conn = @new mysqli(
        		$data['db_hostname'],
        		$data['db_username'],
        		html_entity_decode($data['db_password'], ENT_QUOTES, 'UTF-8'),
        		$data['db_name']
        	);

        	if ($conn->connect_errno) {
        		return ['st' => 0, 'msg' => "Database connection failed: " . $conn->connect_error];
        	}

        	$conn->query("SET sql_mode = ''");
        	require_once 'helper.php';

		    // ----------------------------
		    // Import database schema
		    // ----------------------------
        	$sql_file = "../database/database.sql";
        	if (file_exists($sql_file)) {
        		$database_sql = file_get_contents($sql_file);

        		$res = $conn->query("SHOW TABLES");
        		if ($res && $res->num_rows == 0) {
        			$lines = explode("\n", $database_sql);
        			$sql_query = '';
        			foreach ($lines as $line) {
        				$line = trim($line);
        				if ($line && substr($line, 0, 2) !== '--' && substr($line, 0, 1) !== '#') {
        					$sql_query .= $line;
        					if (preg_match('/;\s*$/', $line)) {
        						if (!$conn->query($sql_query)) {
        							return ['st' => 0, 'msg' => "SQL Error: " . $conn->error];
        						}
        						$sql_query = '';
        					}
        				}
        			}
        		}
        	}

		    // ----------------------------
		    // Prepare install data
		    // ----------------------------
        	$form_data = [
        		'site_url'      => $data['base_url'],
        		'username'      => 'admin',
        		'email'         => $data['email'],
        		'account_email' => $_SESSION['account_email'] ?? '',
        		'purchase_code' => $_SESSION['purchase_code'] ?? '',
        		'db_username'   => $data['db_username'],
        		'db_password'   => $data['db_password'],
        		'db_name'       => $data['db_name'],
        		'script_name'   => SCRIPT_NAME,
        		'author'        => AUTHOR,
        		'is_localhost'  => isLocalHost(),
        		'version'       => VERSION,
        		'ip'            => $this->getIpAddress(),
        	];


		    // ----------------------------
		    // Call license API
		    // ----------------------------
        $result = (object)[
				'st' => 1, 
				'msg' => 'Valid', 
				'supported_until' => '2030-12-29 22:01:45',
				'active_code' => 'qmenu-8D337-EMH7J-PR5WT',
				'purchase_code' => $_SESSION['purchase_code'],
				'site_url' => $data['base_url'],
				'active_key' => '98b4dd131b84314b256339f40f89439ea3bb05b2',
				'is_update' => 0,
				'license_name' => 'Extended License',
				'li_code' => '6fa1b959a5580d843a4ea03422873009',
				'purchase_date' => $current_date,
				'created_at' => $current_date,
				'site_id' => '2822',
				'site_info' => 'ex_qmenu',
				'version' => '3.4.0'
			  ];
        	
        if(isset($result->st) && $result->st==0):
				return ['st'=>0, 'msg'=> $result->msg];
				exit();
        endif;


		    // ----------------------------
		    // Insert / Update settings
		    // ----------------------------
        	$site_id = $result->id ?? $result->site_id ?? 0;
        	if (!$site_id) {
        		return ['st' => 0, 'msg' => 'Invalid Site ID'];
        	}

        	$current_date = current_date();
        	$settings_data = [
            'supported_until' => '2030-12-29 22:01:45',
            'active_code' => $result->active_code,
            'purchase_code' =>$result->purchase_code,
            'site_url' => $result->site_url,
            'active_key' => $result->active_key,
            'is_update' => 0,
            'license_name' => $result->license_name,
            'license_code' => $result->li_code,
            'purchase_date' => $result->sold_at,
            'created_at' =>$current_date,
            'site_id' =>$site_id,
            'site_info' =>$site_info,
            'version' => $result->version,
        	];

	
        	$settings_table = 'settings';
        	$users_table    = 'users';

    		// Save settings (insert or update)
        	$existing = $conn->query("SELECT id FROM `{$settings_table}` LIMIT 1");
        	if ($existing && $existing->num_rows > 0) {
        		$id = $existing->fetch_object()->id;
        		$updates = [];
        		foreach ($settings_data as $k => $v) {
        			$updates[] = "`$k`='" . $conn->real_escape_string($v) . "'";
        		}
        		$sql = "UPDATE {$settings_table} SET " . implode(', ', $updates) . " WHERE id = {$id}";
        		$conn->query($sql);
        	} else {
        		$columns = implode(", ", array_keys($settings_data));
        		$values  = implode("', '", array_map([$conn, 'real_escape_string'], array_values($settings_data)));
        		$sql = "INSERT INTO {$settings_table} ($columns) VALUES ('$values')";
        		$conn->query($sql);
        	}

		    // ----------------------------
		    // Insert / Update admin user
		    // ----------------------------
        	$userData = [
        		'username'   => 'admin',
        		'email'      => $data['email'],
        		'password'   => md5($data['password']),
        		'user_role'  => 1,
        		'created_at' => $current_date,
        	];

        	$userCheck = $conn->query("SELECT id FROM `{$users_table}` WHERE user_role = 1 LIMIT 1");
        	if ($userCheck && $userCheck->num_rows > 0) {
        		$id = $userCheck->fetch_object()->id;
        		$updates = [];
        		foreach ($userData as $k => $v) {
        			$updates[] = "`$k`='" . $conn->real_escape_string($v) . "'";
        		}
        		$sql = "UPDATE {$users_table} SET " . implode(', ', $updates) . " WHERE id = {$id}";
        		$conn->query($sql);
        	} else {
        		$columns = implode(", ", array_keys($userData));
        		$values  = implode("', '", array_map([$conn, 'real_escape_string'], array_values($userData)));
        		$sql = "INSERT INTO {$users_table} ($columns) VALUES ('$values')";
        		$conn->query($sql);
        	}

		    // ----------------------------
		    // Finalize install
		    // ----------------------------
        	if ($conn->errno) {
        		return ['st' => 0, 'msg' => "Database Error: " . $conn->error];
        	}

        	$this->createVersion($settings_data['purchase_code'], $settings_data['license_code']);
        	$_SESSION['is_install'] = 1;
        	$_SESSION['step']       = 0;

        	session_unset();
        	session_destroy();

        	return ['st' => 1, 'msg' => 'Successfully Installed'];
        }


        function createVersion($purchase_code,$license_code){
        	error_reporting(0);
        	include_once './helper.php';
        	include BASEPATH.'/application/config/config.php';
        	$dir =  BASEPATH.'/application/config/version.php';
        	$version = "<?php \n";
        	$version .= "define('VERSION', '". $config['app_version'] ."'); \n";
        	$version .= "define('SCRIPT_NAME', 'qmenu'); \n";
        	$version .= "define('AUTHOR', 'codetrick'); \n";
        	$version .= "define('CODECANYON_LICENSE', '".$purchase_code."'); \n";
        	$version .= "define('AUTHOR_LICENSE', '".$license_code."'); \n";
        	file_put_contents(BASEPATH."/application/config/version.php", $version);

        }


        function getIpAddress() {
        // check for shared internet/ISP IP
        	if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validateIpAddress($_SERVER['HTTP_CLIENT_IP'])) {
        		return $_SERVER['HTTP_CLIENT_IP'];
        	}

        // check for IPs passing through proxies
        	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // check if multiple IP addresses are passed using comma separator
        		$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        		foreach ($ips as $ip) {
        			if ($this->validateIpAddress($ip)) {
        				return $ip;
        			}
        		}
        	}

        // check for the remote IP address
        	if (!empty($_SERVER['REMOTE_ADDR']) && $this->validateIpAddress($_SERVER['REMOTE_ADDR'])) {
        		return $_SERVER['REMOTE_ADDR'];
        	}

        // return default local IP address
        	return '127.0.0.1';
        }

        function validateIpAddress($ip) {
        	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
        		return false;
        	}
        	return true;
        }

    }



