<file_sep><h1>Редактировать задачу</h1>
<form method='post' action='#'>
    <div class="form-group">
        <label for="description">Описание</label>
        <textarea rows = "5" cols = "50" class="form-control" id="description" placeholder="Введите описание" name="description" >
            <?php if (isset($task["description"])) echo $task["description"];?>
        </textarea>
    </div>
    <button type="submit" class="btn btn-primary">Сохранить</button>
</form><file_sep><h1>Создать задачу</h1>
<form method='post' action='#'>
    <div class="form-group row">
        <label for="title" class="col-sm-2 col-form-label">Имя пользователя</label>
        <div class="col-sm-7">
        <input type="text" class="form-control" id="username" placeholder="Введите имя" name="username" value="<?= $username?>"  >
        </div>
        <?if(!empty($errors["username_error"])):?>
        <div class="col-sm-3">
            <small class="text-danger">
                <?= $errors["username_error"]?>
            </small>
        </div>
        <?endif;?>
    </div>
    <div class="form-group row">
        <label for="title" class="col-sm-2 col-form-label">Email</label>
        <div class="col-sm-7">
        <input type="email" class="form-control" id="email" placeholder="Введите ваш email" name="email" value="<?=$email?>" >
        </div>
        <?if(!empty($errors["email_error"])):?>
            <div class="col-sm-3">
                <small class="text-danger">
                    <?= $errors["email_error"]?>
                </small>
            </div>
        <?endif;?>
    </div>


    <div class="form-group row">
        <label for="description" class="col-sm-2 col-form-label">Описание</label>
        <div class="col-sm-7">
        <textarea rows = "5" cols = "50" class="form-control" id="description" placeholder="Введите описание" name="description" ><?=$description?></textarea>
        </div>
        <?if(!empty($errors["description_error"])):?>
            <div class="col-sm-3">
                <small class="text-danger">
                    <?= $errors["description_error"]?>
                </small>
            </div>
        <?endif;?>
    </div>
    <button type="submit" class="btn btn-primary">Отправить</button>
</form><file_sep><?php

class Router
{

    static public function parse($url, $request)
    {
        $url = trim($url);


            $explode_url = explode('/', $url);

            $explode_url = array_slice($explode_url, 1);

            $request->controller = $explode_url[0];

            $action = explode("?",$explode_url[1]);
            $request->action = $action[0];
            $request->params = $_REQUEST;

        if(!isset($request->controller) || empty($request->controller)){
            header("Location: /tasks/index");
        }

    }
}
?><file_sep><h1>Вход</h1>
<form method='post' action='#'>
    <div class="form-group row">
        <label for="login" class="col-sm-2 col-form-label">Логин</label>
        <div class="col-sm-7">
            <input type="text" class="form-control" id="login" placeholder="Введите логин" name="login" value="<?= $login?>"  >
        </div>
        <?if(!empty($errors["username_error"])):?>
            <div class="col-sm-3">
                <small class="text-danger">
                    <?= $errors["username_error"]?>
                </small>
            </div>
        <?endif;?>
    </div>
    <div class="form-group row">
        <label for="password" class="col-sm-2 col-form-label">Пароль</label>
        <div class="col-sm-7">
            <input type="password" class="form-control" id="password" placeholder="Введите пароль" name="password" value="<?=$password?>" >
        </div>
        <?if(!empty($errors["password_error"])):?>
            <div class="col-sm-3">
                <small class="text-danger">
                    <?= $errors["password_error"]?>
                </small>
            </div>
        <?endif;?>
    </div>
    <button type="submit" class="btn btn-primary">Отправить</button>
</form><file_sep><?php

class Task extends Model
{
    public function create($username, $email, $description)
    {
        $sql = "INSERT INTO tasks (username,email, description, created_at, updated_at) VALUES (:username,:email, :description, :created_at, :updated_at)";

        $req = Database::getBdd()->prepare($sql);

        return $req->execute([
            'username' => $username,
            'email' => $email,
            'description' => $description,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')

        ]);
    }

    public function showTask($id)
    {
        $sql = "SELECT * FROM tasks WHERE id =" . $id;
        $req = Database::getBdd()->prepare($sql);
        $req->execute();
        return $req->fetch();
    }

    public function showAllTasks($offset, $limit, $column, $sort)
    {
        $sql = "SELECT * FROM tasks" . " ORDER BY " . "$column $sort" . " LIMIT " . $limit . " OFFSET " . $offset;

        $req = Database::getBdd()->prepare($sql);
        $req->execute();
        return $req->fetchAll();
    }

    public function edit($id, $description)
    {
        $sql = "UPDATE tasks SET description = :description, updated_at = :updated_at WHERE id = :id";
        $req = Database::getBdd()->prepare($sql);

        return $req->execute([
            'id' => $id,
            'description' => $description,
            'updated_at' => date('Y-m-d H:i:s')

        ]);
    }

    public function setStatus($id)
    {
        $sql = 'UPDATE tasks SET status = 1 WHERE id = :id';
        $req = Database::getBdd()->prepare($sql);
        return $req->execute(["id" => $id]);
    }

    public function getTotalCount()
    {
        $sql = 'SELECT count(*) FROM tasks';
        $req = Database::getBdd()->query($sql)->fetchColumn();
        return $req;
    }
}

?><file_sep><?php
/**
 * Created by PhpStorm.
 * User: Lexz
 * Date: 02.06.2019
 * Time: 10:06
 */

class User
{
    public function login($login, $password){
        $sql = "SELECT access_token FROM admin WHERE login =\"" . $login . "\" AND password=\"" . $password . "\"";
        $req = Database::getBdd()->prepare($sql);
        $req->execute();

        return $req->fetchColumn();
    }

    public function logout(){

    }

    public function authentificated($access_token){
        $sql = "SELECT access_token FROM admin WHERE access_token =\"" . $access_token . "\"";
        $req = Database::getBdd()->prepare($sql);
        $req->execute();

        return $req->fetchColumn();
    }
}<file_sep><!doctype html>
<head>
    <meta charset="utf-8">

    <title>Tracker Ara</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://pagination.js.org/dist/2.1.4/pagination.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <style>
        body {
            padding-top: 5rem;
        }

        .starter-template {
            padding: 3rem 1.5rem;
            text-align: center;
        }
    </style>
</head>

<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
    <a class="navbar-brand" href="#">Tracker Ara</a>
    <? if (!$isAdmin): ?>
        <a class="navbar-brand" href="/auth/login">Вход</a>
    <? else: ?>
        <a class="navbar-brand" href="/auth/logout">Выход</a>
    <? endif; ?>

</nav>

<main role="main" class="container">
    <div>
        <?php
        echo $content_for_layout;
        ?>
    </div>

</main>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://kit.fontawesome.com/afa0f3ed32.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
<file_sep><?php
/**
 * Created by PhpStorm.
 * User: Lexz
 * Date: 02.06.2019
 * Time: 10:06
 */

class AuthController extends Controller
{
    public function login(){
        if(!$this->isAdmin()) {
            require_once(ROOT . 'Models/User.php');
            if (!empty($_POST["login"] && !empty($_POST["password"]))) {
                $user = new User();
                $login = $_POST["login"];
                $password = hash("<PASSWORD>", $_POST["password"]);
                if ($access = $user->login($login, $password)) {
                    $_SESSION["access_token"] = $access;

                    header("Location: /tasks/index");
                } else {
                    $data["error"] = "Пользователь с таким логином\паролем не найден";
                    $this->set($data);
                    $this->render("login");
                }
            }

            $this->render("login");
        }else{
            header("Location: /tasks/index");
        }
    }

    public function logout(){
        unset($_SESSION['access_token']);
        header("Location: /tasks/index");
    }
}<file_sep><?php
/**
 * Created by PhpStorm.
 * User: Lexz
 * Date: 26.05.2019
 * Time: 14:31
 */

class errorsController extends Controller
{
    function index()
    {
        $this->render("404");
    }
}<file_sep><?php

class tasksController extends Controller
{
    private $limit = 3;

    public function index()
    {
        $this->render("index");
    }

    public function getAllTasks($page = 1, $column = "id", $sort = "asc")
    {
        require(ROOT . 'Models/Task.php');

        $tasks = new Task();
        $offset = ($page - 1) * $this->limit;

        $res_tasks = $tasks->showAllTasks($offset, $this->limit, $column, $sort);
        $res_count = $tasks->getTotalCount();


        $res = "";
        foreach ($res_tasks as $task) {
            $res .= '<tr>';
            $res .= "<td>" . $task['id'] . "</td>";
            $res .= "<td>" . $task['username'] . "</td>";
            $res .= "<td>" . $task['email'] . "</td>";
            if($task["status"] == 1){
                $res .= "<td><i class=\"far fa-check-circle\"></i></td>";
            }else{
                $res .= "<td><i class=\"fas fa-star-of-life\"></i></td>";
            }
            $res .= "<td>";
            if($this->isAdmin()) {
                $res .= "<a class='btn btn-info btn-xs' href='/tasks/edit/?id=" . $task["id"] . "' > Редактировать</a>";
                if ($task["status"] != 1) {
                    $res .= "<a href='/tasks/agree/?id=" . $task["id"] . "' class='btn btn-info btn-xs'></span>Завершить задачу</a>";
                }
            }
            $res .= "</td>";
            $res .= "</tr>";
        }
        $data["tasks"] = $res;
        $data["count"] = $res_count;
        $data["limit"] = $this->limit;
        echo json_encode($data);
    }

    public function create()
    {
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $data = $this->validate($_POST);

            if (empty($data["errors"])) {
                require(ROOT . 'Models/Task.php');

                $task = new Task();

                if ($task->create($data["username"], $data["email"], $data["description"])) {
                    header("Location: /tasks/index");
                }


                $this->render("create");
            } else {
                $this->set($data);
                $this->render("create");
            }
        } else {
            $this->render("create");
        }
    }

    public function edit($id)
    {
        if($this->isAdmin()) {
            require(ROOT . 'Models/Task.php');
            $task = new Task();

            $d["task"] = $task->showTask($id);

            if (isset($_POST["description"])) {
                if ($task->edit($id, $_POST["description"])) {
                    header("Location: /tasks/index");
                }
            }
            $this->set($d);
            $this->render("edit");
        }else{
            header("Location: /tasks/index");
        }
    }

    public function agree($id)
    {
        if($this->isAdmin()) {
            require(ROOT . 'Models/Task.php');

            $task = new Task();
            if ($task->setStatus($id)) {
                header("Location: tasks/index");
            }
        }else{
            header("Location: /tasks/index");
        }
    }

    private function validate($post)
    {
        $username = $post["username"];
        $email = $post["email"];
        $description = $post["description"];


        $username = $this->clean($username);
        $email = $this->clean($email);
        $description = $this->clean($description);

        $data = [];
        $data["username"] = $username;
        $data["email"] = $email;
        $data["description"] = $description;
        if (empty($username)) {
            $data["errors"]["username_error"] = "Заполните имя";
        }
        if (empty($email)) {
            $data["errors"]["email_error"] = "Заполните email";
        }
        if (empty($description)) {
            $data["errors"]["description_error"] = "Заполните описание задачи";
        }

        if (!empty($data["errors"])) {
            return $data;
        }

        $email_validate = filter_var($email, FILTER_VALIDATE_EMAIL);
        if (!$email_validate) {
            $data["errors"]["email_error"] = "Неправильно заполнен email";
        }

        return $data;

    }

    private function clean($value = "")
    {
        $value = trim($value);
        $value = stripslashes($value);
        $value = strip_tags($value);
        $value = htmlspecialchars($value);

        return $value;
    }
}

?><file_sep>var current_page = 1;
var total_count = 0;
var records_per_page = 0;
var sort = "asc";
var field = 'id';
$(document).ready(function () {
    load_data(current_page,field,sort);
});

function load_data(page,field,sort) {
    $.ajax({
        url: "/tasks/getAllTasks",
        method: "POST",
        data: {page: page,field:field,sort:sort},
        dataType: 'json',
        success: function (data) {
            total_count = data.count;
            records_per_page = data.limit;
            $("#tasks tbody").html('');
            $("#tasks tbody").append(data.tasks);
        }
    })
};

$("#btn_prev").on("click", function () {
    if (current_page > 1) {
        current_page--;
        load_data(current_page,field,sort);
    }

});
$("#btn_next").on("click", function () {
    if (current_page < numPages()) {
        current_page++;
        load_data(current_page,field,sort);
    }
});

$("#tasks thead th").on("click", function(){
    if(typeof $(this).attr("id") == "undefined"){
        return;
    }
    field = $(this).attr("id");
    if(sort === "asc"){
        sort = "desc";
    }else{
        sort = "asc";
    }
    load_data(current_page,field,sort);
});

function numPages() {
    return Math.ceil(total_count / records_per_page);
}
