<?php

namespace Diamond\Modules\SystemHealthWidget;

use Diamond\Helpers\Form;
use Core\Template\Template;
use Diamond\Helpers\SystemHelper;
use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Diamond\Application\Notification\NotificationService;

/**
 * Class SystemHealthWidget
 */
class SystemHealthWidget extends \Core\ModuleController
{
    private $notificationService;

    public int $height = 106;

    public function __construct(
        NotificationService $notificationService, private Template $template
    )
    {
        $this->notificationService = $notificationService;
    }

    public function process(): string
    {

        try {
            $dotenv = Dotenv::createImmutable(BASEPATH, '.system');
            $data = SystemHelper::prepareData($dotenv->load());

        } catch (InvalidPathException $ex) {
            return 'нет данных';
        }

        $this->template->addScriptLink('/_diamond/diamond-cms/assets/nifty/plugins/gauge-js/gauge.min.js');

        //блок с получением инфы
        $post_size = $data['POST_SIZE']??0;
        $db_size = $data['DB_SIZE'];
        $site_size = $data['SITE_SIZE'];
        $kh_size = $data['KH_SIZE'];
        $free = $data['DISK_FREE'];

        $all = $data['DISK_LIMIT'];

        $cur = $all - $free;
        //---------

        $per = $all > 0 ?round(($cur / $all) * 100) : 0;

        $per = $per > 100 ? 100 : $per;
        $this->template->addScript($this->render('javascript',[
            'persent' => $per
        ]));

        if($per > 90){
            $style = 'redbar';
        }
        elseif($per > 60){
            $style = 'orangebar';
        }
        else{
            $style = 'greenbar';
        }

        if($per > 95){
            $message = Form::buildErrorMessage('Внимание! Вы исчерпали свободное место на диске, сайт может работать со сбоями');
        }
        else{
            $message = '';
        }

        return $this->render([
            'message' => $message,
            'disk_current' => $cur,
            'disk_all' => $all,
            'disk_percent' => $per,
            'disk_style' => $style,
            'db_size'   => $db_size,
            'site_size' => $site_size,
            'post_size' => $post_size,
            'height' => $this->height,
            'sms_balance' => $this->notificationService->getSmsBalance()
        ]);
    }
}
