<?php
namespace App\Controllers;

use Core\View;
use App\Models\Access;
use Core\Token;
use Core\Session;
use Core\Redirect;
use Core\Hash;
use Core\XSS;

class Home
{
    public $model;

    public function __construct()
    {
        $this->model = new Access();
    }

    /* Routes */
    public function index()
    {
        $posts = new Posts();
        $posts->index();
    }

    public function login($args = [])
    {
        if (Session::exists('userid')) {
            Session::flash('info', 'Anda telah masuk');
            Redirect::to('/');
            die();
        }

        // Login
        if ($args) {
            // Avoid XSS
            $args['exclude'] = [
                'password'
            ];
            $args = XSS::avoid($args);

            $username = $args['username'];
            $password = $args['password'];

            $user = $this->model->showAll([
                ['username', '=', $username]
            ]);

            if ($user == false) {
                $info = "Username/password salah";
            } else {
                $hash = Hash::compare($password, $user['salt'], $user['password']);

                if ($hash == true) {
                    if ($user['max_user'] <= 0) {
                        $info = "Telah mencapai maksimal user yang diizinkan - Silahkan logout pada perangkat lain terlebih dahulu";
                    } else {
                        $max_user = $user['max_user'] - 1;
                        if ($this->model->update(['max_user' => $max_user], $user['id']) == true) {
                            Session::put('userid', $user['id']);
                            Session::put('username', $user['username']);
                            Session::put('full_name', $user['full_name']);
                            Session::put('privilege', $user['privilege']);

                            $info = "Berhasil masuk";
                        }
                    }
                }
            }
            Session::flash('info', $info);
            Redirect::to('/');
            die();
        } else {
            View::render('Access/login.html', [
                'token' => Token::generate()
            ]);
        }
    }

    public function logout() {
        if ($this->delete() != true) {
            $info = "Terjadi kesalahan. Silahkan coba lagi dalam beberapa saat";
        } else {
            Session::delete('userid');
            Session::delete('username');
            Session::delete('full_name');
            Session::delete('privilege');

            $info = "Berhasil keluar";
        }
        Session::flash('info', $info);
        Redirect::to('/');
    }

    public function register()
    {
        if (Session::exists('userid') && Session::get('privilege') == 1) {
            View::render('Access/registrasi.html', [
                'token' => Token::generate()
            ]);
        } else {
            throw new \Exception("Bad Request", 400);
        }
    }

    /* Methods */
    public function post($args = [])
    {
        foreach ($args as $value) {
            if ($value == '') {
                Session::flash('info', 'Semua data harus diisi');
                Redirect::to('./register');
                die();
            }
        }

        $date = new \DateTime();
        $now = $date->format('Y-m-d');
        $args['registered_at'] = $now;

        $salt = Hash::salt();
        $password = Hash::make($args['password'], $salt);
        $args['salt'] = $salt;
        $args['password'] = $password;

        // Avoid XSS attack
        // Exclude password and salt
        $args['exclude'] = [
            'salt',
            'password'
        ];
        $args = XSS::avoid($args);

        $data = $this->model->showAll();
        foreach ($data as $users) {
            if (is_array($users)) {
                $known_uname = $users['username'];
            } else {
                $known_uname = $data['username'];
            }
            if ($args['username'] == $known_uname) {
                Session::flash('info', 'Username telah digunakan. Silahkan gunakan username lain');
                Redirect::to('./register');
                die();
            }
        }

        $this->model->entry($args);
        Session::flash('info', 'Registrasi berhasil');
        Redirect::to('/');
        die();
    }

    public function delete()
    {
        if (Session::exists('userid') == false) {
            throw new \Exception("Bad request but thrown as 404", 404);
        }
        $userid = Session::get('userid');

        $user = $this->model->showAll([
            ['id', '=', $userid]
        ]);
        $max_user = $user['max_user'] + 1;

        if ($this->model->update(
            [
                'max_user' => $max_user
            ],
            $userid
            ) != true) {
            throw new \Exception("Bad request", 400);
        }
        return true;
    }
}
