<?php
define('VERSION','0.9.2');
//define('INSTALLER_MODE','1');
require_once 'lib/loadTwig.php';

$db_file = __DIR__."/sqlite.db3";
if (is_file($db_file)){ //Go to install if not.
	header('Location: index.php'); //Ya está instalado. Borra la base de datos si quieres forzar una reinstalación
}

if (!isset($_POST['websiteName']) && !isset($_POST['username']) && !isset($_POST['passw1']) && !isset($_POST['passw2'])){
  echo $twig->render('install.twig');
}else{
	if ($_POST['passw1'] !== $_POST['passw2']){
		die("Passwords didn't match");
	}else{
		//Creamos toda la base de datos
		require_once "lib/dbwrapper.php"; //For using database
		$db_conn = dbw_connect("sqlite",$db_file); //Create database
		$sqlcreate='
BEGIN TRANSACTION;
CREATE TABLE "VISITS" (
	`ID_C`	INTEGER,
	`date`	INTEGER,
	`visits`	INTEGER DEFAULT 0,
	`uniqueVisits`	INTEGER DEFAULT 0,
	FOREIGN KEY(`ID_C`) REFERENCES `Sites`(`ID_Site`)
);
CREATE TABLE "USERS" (
	`ID_U`	INTEGER PRIMARY KEY AUTOINCREMENT,
	`nick`	TEXT NOT NULL UNIQUE,
	`passw`	TEXT,
	`fullRights`	INTEGER NOT NULL
);
CREATE TABLE "TOKENS" (
	`ID_T`	TEXT UNIQUE,
	`name`	TEXT,
	PRIMARY KEY(`ID_T`)
);
CREATE TABLE "SYS" (
	`option`	TEXT UNIQUE,
	`value`	TEXT
);
CREATE TABLE "NEWS" (
	`ID_N`	INTEGER PRIMARY KEY AUTOINCREMENT,
	`text`	TEXT NOT NULL,
	`timestamp`	INTEGER NOT NULL,
	`sentBy`	TEXT
);
CREATE TABLE "GROUPS" (
	`ID_G`	INTEGER PRIMARY KEY AUTOINCREMENT,
	`name`	TEXT NOT NULL
);
CREATE TABLE "CHKHIST" (
	`ID_CHist`	INTEGER PRIMARY KEY AUTOINCREMENT,
	`ID_C`	INTEGER,
	`code`	INTEGER,
	`errorText`	TEXT,
	`timestamp`	INTEGER,
	FOREIGN KEY(`ID_C`) REFERENCES `Sites`(`ID_Site`)
);
CREATE TABLE "CHECKS" (
	`ID_C`	INTEGER PRIMARY KEY AUTOINCREMENT,
	`ID_G`	INTEGER,
	`name`	TEXT NOT NULL,
	`URL`	TEXT,
	`manStatus`	INTEGER,
	`ID_TC`	INTEGER,
	`TCParam`	TEXT,
	FOREIGN KEY(`ID_G`) REFERENCES `GROUPS`(`ID_G`),
	FOREIGN KEY(`ID_TC`) REFERENCES `TYPECHK`(`ID_TC`)
);
COMMIT;';
		dbw_multi_query($db_conn,$sqlcreate); //Create scheme
		$user = $_POST[username];
		$pass = hash("sha256",$_POST['passw1']);
		dbw_query($db_conn,"INSERT INTO USERS (nick,passw,fullRights) VALUES('$user','$pass',1)"); //Create user
		
		//System opts
		dbw_query($db_conn,"INSERT INTO SYS VALUES ('maxTimeSave',14)");
		dbw_query($db_conn,"INSERT INTO SYS VALUES ('lang','$_POST[lang]')");
		dbw_query($db_conn,"INSERT INTO SYS VALUES ('websiteTitle','Status')");
		dbw_query($db_conn,"INSERT INTO SYS VALUES ('version','".VERSION."')");
		
		echo $twig->render('install.twig', array('part' => 2));
	}
}

?>

