<?php

// Hide default template
TaskerMAN\WebInterface\WebInterface::showTemplate(false);
// Intialize installation engine
$install = new TaskerMAN\Core\Install();
if (!$install->required()) {
    throw new TaskerMAN\Core\FatalException('Install Not Required', new \Exception('All database tables already exist, so an install is not required.'));
}
$alert = null;
if (isset($_POST['submit'])) {
    // Create tables
    $install->createTables();
    // Create user
    try {
        $uid = TaskerMAN\Application\UserManagement::create(TaskerMAN\Core\IO::POST('email'), TaskerMAN\Core\IO::POST('name'), TaskerMAN\Core\IO::POST('password'), true);
        header('Location: index.php?p=user&id=' . $uid);
    } catch (TaskerMAN\Application\UserManagementException $e) {
        $alert = '<div class="alert alert-danger" role="alert">' . $e->getMessage() . '</div>';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Install &middot; TaskerMAN</title>
<?php

// Check if the application is installed, if not, bounce to install page
if (TaskerMAN\Core\Install::required()) {
    header('Location: index.php?p=install');
    exit;
}
// If user is already logged in, take them to main dashboard
if (TaskerMAN\WebInterface\Session::isLoggedIn()) {
    header('Location: index.php?p=main');
    exit;
}
// Hide template
TaskerMAN\WebInterface\WebInterface::showTemplate(false);
$error = null;
if (isset($_POST['submit'])) {
    $user = TaskerMAN\Application\Login::verifyCredentials(TaskerMAN\Core\IO::POST('email'), TaskerMAN\Core\IO::POST('password'));
    if (!$user) {
        // Login failed
        $error = '<span style="align: center; color: red">Invalid username or password combination</span>';
    } elseif (!$user->admin) {
        $error = '<span style="align: center; color: red">Your account does not have access to this control panel</span>';
    } else {
        TaskerMAN\WebInterface\Session::set('uid', $user->id);
        header('Location: index.php?p=main');
        exit;
    }
}
?>

<!DOCTYPE html>