<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

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

    public string $fileLog;

    public function fetch()
    {
        $this->smarty->assign('activeItem', 'lowerrors');
        $this->smarty->assign('title','Ошибки PHP');

        $gmDate = adjustTime(gmdate('Y-m-d H:i:s'), false, 'Y-m-d');

        $this->fileLog = ERRORS_LOG . 'app-'.$gmDate.'.log';

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

            $this->clearLogErrors();

        } else if ($this->action == 'read') {

            $this->readLogErrors();
        }

        if ($this->permissions('lowerrors')) {
            return  $this->smarty->fetch('views/errors/low.tpl');
        }

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

    }

    public function readLogErrors()
    {
        $error = [];

        if (file_exists($this->fileLog)) {

//        $data = file_read($fileLog);
//        $error = [];
//        $arr_errors = explode("\r", $data);
//        foreach ($arr_errors as $e) {
//            if (trim($e) != "") {
//                $error[] = explode("|", $e);
//            }
//        }

            $text = $this->read_file();

            $arr_errors = explode("\r", $text);
            foreach ($arr_errors as $e) {
                if (trim($e) != "") {
                    $error[] = explode("|", $e);
                }
            }
            $error = array_reverse($error);
        }

        $response = array(
            "draw"  => 1,
            "data"  => $error
        );

        response()->json($response, \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();
    }

     public function clearLogErrors()
     {
		$result = $this->write_file("")
            ? 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();

     }

    /**
     * @param $context
     */
	public function write_file($context): bool
    {
		$f = fopen($this->fileLog, "w+");
		if (is_writable($this->fileLog) && is_resource($f)) {
			fwrite($f, $context);
		}

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

	private function read_file(): string
    {
        $text = '';
        if (file_exists($this->fileLog)) {

            $fh = fopen($this->fileLog, 'r');
            while (!feof($fh)) {
                $line = fgets($fh);
                $text .= $line . PHP_EOL;
            }
            fclose($fh);
        }

        return $text;
    }
}

