<?php

class Status {

	const DEBUG = false;

	# ~ Entry point for health status check	 - - - - - - - - - - - - - - - - - - - #
	public function Status() {

		# Build the health string
		$this->errors = array_filter([
			'mysql' => $this->mysql(),
			'disk'  => $this->disk()
		]);

		# Display debug data
		if (Status::DEBUG) {
			$errors = [];

			# Prepare css
			echo '<style>body { padding: 20px; line-height: 350%; font: 140%/250% "Monospace", "Courier new"; white-space: pre }</style>';

			# Iterate over each error
			foreach ($this->errors as $key => $error) {
				$errors[] = str_pad($key, 8) . ': ' . $error;
			}

			# Show errors
			if ($errors) {
				echo implode("\n", $errors);
				exit(1);
			}
		}

		# Show OK if all fine
		echo $this->errors ? 'FAIL' : 'OK';
		exit((int) $this->errors);
	}

	# ~ Get the configuration  - - - - - - - - - - - - - - - - - - - - - - - - - - #
	private function getDatabaseConnection() {

		# Get the configuration
		require '../../app/Config/config.php';

		# Return the array
		return [
			'host'     => DATABASE_CONFIG::$default['host'],
			'user'     => DATABASE_CONFIG::$default['login'],
			'pass'     => DATABASE_CONFIG::$default['password'],
			'database' => DATABASE_CONFIG::$default['database']
		];
	}

	# ~ Check MySQL	 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	private function mysql() {
		$this->Database = new Mysqli();

		# Get the mysql configuration
		$conf = $this->getDatabaseConnection();

		# Try to connect
		if (!$this->Database->real_connect($conf['host'], $conf['user'], $conf['pass'], $conf['database'])) {
			return "Cannot connect to database: {$this->Database->connect_error}";
		}

		# Try query
		if (!$this->Database->query("SELECT `id` FROM `users`")) {
			return "Cannot query tha database: {$this->Database->error}";
		}

		# All well
		return null;
	}

	# ~ Check remaninig space on disk  - - - - - - - - - - - - - - - - - - - - - - #
	private function disk() {

		# Get the values
		$free = disk_free_space('/');
		$total = disk_total_space('/');

		# Make sure we have at least 20% available
		$percentage = round(100 * $free / $total);
		return $percentage < 20 ? "Disk space critical: {$percentage}%" : null;
	}

}

new Status();

class Configure {
	public function write() {
	}
}
