<?php
ini_set("display_errors", 1);

require_once(__DIR__ . "/lib/ErrorHandler.php");

if (!array_key_exists("SHELL", $_SERVER)) {
	ErrorHandler::hook();
}

require_once(__DIR__ . "/lib/Session.php");

Session::init("memcache", 11211);

define('ROOT', __DIR__);
require_once(ROOT . "/vendor/autoload.php");

$args = array_merge($_GET, $_POST);

use \Michelf\Markdown;
use \Jenssegers\Blade\Blade;

_add_code_dir(ROOT . "/lib");
//$dir = opendir(ROOT . "/lib");
//while ($file = readdir($dir)) {
//	if (str_ends_with($file, ".php")) {
//		require_once(ROOT . "/lib/" . $file);
//	}
//}
//closedir($dir);


DB::getInstance()->connect(
    Config::get("DB_USER"),
    Config::get("DB_PASS"),
    Config::get("DB_HOST"),
    Config::get("DB_DATABASE")
);

_add_code_dir(ROOT . "/app");
//$dir = opendir(ROOT . "/app");
//while ($file = readdir($dir)) {
//	if (str_ends_with($file, ".php")) {
//		require_once(ROOT . "/app/" . $file);
//	}
//}
//closedir($dir);

require_once("lib/App.php");

require_once("routes/api.php");
require_once("routes/web.php");

Model::cache_connect("memcache", 11211);

if ($_SERVER['argc'] == 0) {
	$blade = new Blade(ROOT . '/views', ROOT . '/cache');
	$req = new Request;
	App::dispatch($req);
}


function blade($name, $args = []) {
	global $blade;

	$args['flash_error'] = Session::get("flash_error");
	$args['flash_warn'] = Session::get("flash_warn");
	$args['flash_success'] = Session::get("flash_info");
	$args['flash_info'] = Session::get("flash_success");

	Session::unset("flash_error");
	Session::unset("flash_warn");
	Session::unset("flash_info");
	Session::unset("flash_success");

	return $blade->render($name, $args);
}

function get_user() {
	$uid = 	Session::get("user");
	if ($uid) {
		return new User($uid);
	}
	return false;
}

function flash($type, $message) {
	if ($_SERVER['argc'] == 0) {
		Session::set("flash_" . $type, $message);
	} else {
		print("$type: $message\n");
	}
}

function fmt_date($month, $year) {
	if (($year < 1900) && ($year > 50)) {
		$year = 1900 + $year;
	}

	if (($year < 1900) && ($year <= 50)) {
		$year = 2000 + $year;
	}

	if ($month > 0) {
		$dt = DateTime::createFromFormat("!m/Y", $month . "/" . $year);
		return $dt->format("F Y");
	} else {
		$dt = DateTime::createFromFormat("!Y", $year);
		return $dt->format("Y");
	}
}

function format_size($s) {
    if ($s < 102400) return sprintf("%.1fkB", $s / 1024);
    if ($s < 10485760) return sprintf("%.1fMB", $s / (1024 * 1024));
    return sprintf("%dMB", $s / (1024 * 1024));
}

function redirect($url) {
	return [
		302, "", [
			"Location" => $url
		]
	];

//	if ($_SERVER['argc'] == 0) {
//		header("Location: $url");
//		exit(0);
//	}
}

function jsredirect($url) {
	print('<script>document.location="' . $url . '";</script>');
	exit(0);
}

function back() {
	return redirect($_SERVER['HTTP_REFERER']);
}

function __unref($v) {
	if ($v instanceof Model) {
		return $v->id;
	}
	return $v;
}

function _add_code_dir($path) {
	$dir = opendir($path);
	while ($file = readdir($dir)) {
		if (str_starts_with($file, ".")) {
			continue;
		}

		if (is_dir($path . "/" . $file)) {
			_add_code_dir($path . "/" . $file);
			continue;
		}

		if (str_ends_with($file, ".php")) {
			require_once($path . "/" . $file);
		}
	}
	closedir($dir);
}

function strtolower_null($a) {
	if (!is_string($a)) return $a;
	return strtolower($a);
}
