<?php

namespace App\Controllers;

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

use App\DataBase\DataBase;
use App\Utils\Page;
use App\Utils\ShowImg;
use Noodlehaus\Config;

class Backend {

    private $start = 0;
    private $end = 15;
    private $max = 15;
    private $runningJob = false;
    private $page = 'infos';
    private $params;
    private $conf;
    private $title = 'Settings';
    private $passwordRequired = false;

    public function index($params, $conf) {
        if (isset($params->loginPassword)) {
            if (!Login::login($params->loginPassword, $conf->password)) {
                $content = $this->showLogin();
                return $content;
            }
        }

        if (!Login::isLogin()) {
            $content = $this->showLogin();
            return $content;
        }

        if (!empty($params->page)) {
            $this->page = $params->page;
        }

        if (file_exists(__DIR__ . '/../../cache/tmp/chrome-php-socket')) {
            $this->runningJob = true;
        }

        if (!empty($params->showImg)) {
            $img = new ShowImg($params->type, $params->showImg);
            exit();
        }

        $this->conf = $conf;
        $this->params = $params;

        if ($this->page === 'settings') {
            if (isset($_SESSION['firstRun']) && $_SESSION['firstRun'] === 1) {
                $conf->webPage = false;
                $this->title = 'Install';
                $this->conf->key = bin2hex(random_bytes(12));
                $this->passwordRequired = "required";
            }

            if (isset($this->params->token) && Page::verifToken($this->params->token)) {
                $this->conf = $this->setOption($params);
            }
        }

        ob_start();
        require_once __DIR__ . '/../../tpl/nav.php';

        if ($this->page === 'infos') {
            $this->showInfos();
        } else {
            $this->showSettings();
        }
        require_once __DIR__ . '/../../tpl/footer.php';
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }

    private function showInfos() {
        if (!empty($this->params->start)) {
            $this->start = $this->params->start;
        }

        if (!empty($this->params->end)) {
            $this->end = $this->max + $this->start;
        }

        $conx = new DataBase();
        $genList = $conx->getList($this->start, $this->end);
        $total = $conx->getTotal();

        $start = $this->start;
        $max = $this->max;
        $next = $start + $max;
        $previous = $start - ($max);

        if (count($genList) < $this->max) {
            $next = $start;
        }

        if ($previous < 0) {
            $previous = 0;
        }

        require __DIR__ . '/../../tpl/infos.php';
    }

    private function showSettings() {
        if (!empty($this->params->start)) {
            $this->start = $this->params->start;
        }

        if (!empty($this->params->end)) {
            $this->end = $this->max + $this->start;
        }

        if ($this->start < 0) {
            $this->start = 0;
        }
        $conx = new DataBase();
        $genList = $conx->getList($this->start, $this->end);
        $total = $conx->getTotal();
        $start = $this->start;
        $max = $this->max;
        $token = Page::genToken();

        require __DIR__ . '/../../tpl/settings.php';
    }

    private function setOption($post) {
        if (!file_exists(__DIR__ . '/../../datas/config.json')) {
            file_put_contents(__DIR__ . '/../../datas/config.json', json_encode([]));
            unset($_SESSION['login']);
            unset($_SESSION['firstRun']);
        }

        $userConfig = __DIR__ . '/../../datas/config.json';
        $uConfig = new Config($userConfig);

        if (empty($post->onlyLocalServer)) {
            $uConfig['onlyLocalServer'] = false;
        } else {
            $uConfig['onlyLocalServer'] = true;
        }

        if (empty($post->webPage)) {
            $uConfig['webPage'] = false;
        } else {
            $uConfig['webPage'] = true;
        }

        if (empty($post->log)) {
            $uConfig['log'] = false;
        } else {
            $uConfig['log'] = true;
        }

        if (empty($post->alwaysMakePdf)) {
            $uConfig['alwaysMakePdf'] = false;
        } else {
            $uConfig['alwaysMakePdf'] = true;
        }

        if (!empty($post->icoSize)) {
            $uConfig['icoSize'] = (int)$post->icoSize;
        }

        if (!empty($post->expireCache)) {
            $uConfig['expireCache'] = (int)$post->expireCache;
        }

        if (!empty($post->maxGenPerBatch)) {
            $uConfig['maxGenPerBatch'] = (int)$post->maxGenPerBatch;
        }

        if (!empty($post->permitType)) {
            $uConfig['permitType'] = $post->permitType;
        } else {
            $uConfig['permitType'] = [];
        }

        if (!empty($post->password)) {
            $uConfig['password'] = password_hash($post->password, PASSWORD_DEFAULT);
        }

        if (!empty($post->key)) {
            $uConfig['key'] = $post->key;
        }

        if (!empty($post->chromePath)) {
            $uConfig['chromePath'] = $post->chromePath;
        }

        $uConfig->toFile($userConfig);

        $newConfig = new Config($userConfig);
        return (object)$newConfig->all();
    }

    private function showLogin() {
        ob_start();
        $token = Page::genToken();
        require_once __DIR__ . '/../../tpl/login.php';
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }
}
