<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}

use Mnv\Core\AdminMnv;
use Mnv\Core\Test\Logger;

/**
 * Class ErrorsSysAdmin
 * @package Mnv\Admin\Controllers
 */
class ErrorsSysAdmin extends AdminMnv
{

    public function fetch()
    {

        $this->smarty->assign('activeItem', 'syserrors');
        $this->smarty->assign('title','Критические ошибки');

        if ($this->action == 'clear') {

            $result = $this->write_file(ERRORS_LOG . 'syserrors.log', "")
                ? array('status' => 200, 'message' => 'Журнал очищен', 'type' => 'success')
                : array('status' => 403, 'message' => 'Журнал НЕ очищен', 'type' => 'error');

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }


        $data = file_read(ERRORS_LOG . 'syserrors.log');

        $error = [];
        $errors = explode("\n", $data);

        foreach($errors as $e) {
            if(trim($e) != "") {
                $error[] = $e;
            }
        }

        $error = array_reverse($error);

        if ($this->permissions('syserrors')) {
            $this->smarty->assign('error', $error);
            return $this->smarty->fetch('views/errors/sys.tpl');
        }

        $this->smarty->assign('title', 'Access Denied');
        return $this->smarty->fetch('accessIsDenied.tpl');


    }


    public function clearLogErrors($logfile)
    {

    }


    public function write_file($file, $context) {
        $f = fopen($file, "w+");
        if(is_writable($file) && is_resource($f)) {
            fwrite($f, $context);
        }

        if (!fclose($f)) {
            return false;
        }

        return true;


    }

}