<?php

namespace WHMCS\Module\Widget;

require_once(ROOTDIR . '/includes/functions.php');
require_once(ROOTDIR . '/includes/registrarfunctions.php');
require_once(ROOTDIR . '/modules/registrars/netim/lib/Core.php');
require_once(ROOTDIR . '/modules/registrars/netim/netim.php');
require_once(ROOTDIR . '/modules/registrars/netim/lib/Monitoring.php');

use WHMCS\Carbon;
use WHMCS\Module\AbstractWidget;
use WHMCS\Database\Capsule;
use Netim\Core;
use Netim\Monitoring;

/**
 * NetimMonitoring Widget
 *
 * Show a monitoring panel
 *  
 * @package	NETIM registrar module for WHMCS
 * @author	NETIM
 * @date	2022-04-14
 */

class NetimMonitoring extends AbstractWidget
{
    protected $title = '';
    protected $description = '';
    protected $weight = 500;
    protected $columns = 1;
    protected $cache = true;
    protected $requiredPermission = 'Perform Registrar Operations';

    private $lang = '';
    private $link = '';

    function __construct()
    {
        # Language management
        global $_ADMINLANG;
        $this->lang = \Netim\Core\getLoadTranslate('locale');
        $this->title =  \Netim\Core\getLoadTranslate('netim.widget.monitoring_title');
        $this->description = \Netim\Core\getLoadTranslate('netim.widget.monitoring_description');
    }

    public function getData()
    {
        // $data = [];

        // try {
        //     \Netim\Monitoring\updateVersion();
        //     \Netim\Monitoring\updateTLDNotSupported();
        //     \Netim\Monitoring\updateMarginErrors();
        //     \Netim\Monitoring\insertData("0", 'error');
        // } catch (\Exception $e) {
        //     \Netim\Monitoring\insertData($e->getMessage(), 'error');
        // }
        // return $data;
    }


    public function generateOutput($data)
    {
        require ROOTDIR . '/configuration.php';
        if (isset($customadminpath)) {
            $link = "/" . $customadminpath;
        } else {
            $link = '/admin';
        }

        $protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
        $baseurl = \WHMCS\Utility\Environment\WebHelper::getBaseUrl();
        $url = $protocol . '://' . $_SERVER['HTTP_HOST'] . $baseurl;

        $link = $url . $link;
        $output = "";
        $var = \Netim\Monitoring\getData('error')->info;
        # Build output
        if (Capsule::schema()->hasTable('mod_netim_monitoring') && Capsule::schema()->hasTable('mod_netim_tld_manager')) {
            if ($var == '0' ||  empty(str_replace(' ', '', $var))) {
                try {
                    $version = \Netim\Monitoring\getData('version')->info;
                    if ($version == "") {
                    } else if ($version == 0) {
                        $output .= "<h1 class='text-success'><font color='green'><i class='far fa-smile'></i> " . \Netim\Core\getLoadTranslate('netim.widget.monitoring_up_to_date') . "</font></h1>";
                    } else {
                        $output .= "<h1 class='text-danger'><i class='far fa-angry'></i> " . \Netim\Core\getLoadTranslate('netim.widget.monitoring_update') . "</h1>";

                        $output .= "<div class='row'>";
                        $output .= "<div class='col-sm-6'>";
                        $output .= "<i class='fas fa-exclamation-triangle'></i> Registrar module " . NETIM_WHMCS_MODULE . ' → ' . $version;
                        $output .= "</div>";
                        $output .= "<div class='col-sm-6 text-right'>
                                <a href='https://support.netim.com/en/docs/whmcs/download' target='_blank' class='btn btn-default btn-sm'>" . \Netim\Core\getLoadTranslate('netim.widget.monitoring_download') . "</a>
                                </div>";
                        $output .= "</div>";
                    }
                    $tldErrors = \Netim\Monitoring\getData('TLD not supported');
                    $tldConfigErrors = \Netim\Monitoring\getData('TLD configuration errors');
                    $priceErrors = \Netim\Monitoring\getData('Margin price errors');
                    if ($version != '' && ($tldErrors->info != '' || $tldConfigErrors->info > 0 || $priceErrors->info > 0)) {
                        $output .= "<hr>";
                    }

                    if (!empty($tldErrors->info) || $tldConfigErrors->info > 0 || $priceErrors->info > 0) {

                        $output .= "<h1 class='text-danger'><i class='far fa-angry'></i></i> " . \Netim\Core\getLoadTranslate('netim.widget.monitoring_configuration_errors') . "</h1>";

                        $tldErrorsArray = explode(',', $tldErrors->info);
                        if ($tldErrorsArray[0] != '0' && $tldErrors != '-1') {
                            $output .= "<div class='row'>";
                            $output .= "<div class='col-sm-6 text-danger'>";
                            $output .= "<i class='fas fa-times'></i> " . count($tldErrorsArray) . " " . $tldErrors->dataType . " : ";
                            foreach ($tldErrorsArray as $tldError) {
                                $tldError = str_replace('"', '', $tldError);
                                $tldError = str_replace('[', '', $tldError);
                                $tldError = str_replace(']', '', $tldError);
                                $output .= "<font color='gray'>." . $tldError . "</font> ";
                            }

                            $output .= "</div>";
                            $output .= "<div class='col-sm-6 text-right'>
                                    <a href='" . $link . "/configdomains.php' target='_blank' class='btn btn-default btn-sm'>" . \Netim\Core\getLoadTranslate('netim.widget.monitoring_open_settings') . "</a>
                                </div>";
                            $output .= "</div>";
                        }

                        if ($tldConfigErrors->info > 0) {
                            $output .= "<div class='row'>";
                            $output .= "<div class='col-sm-6 text-danger'><i class='fas fa-times'></i> " . $tldConfigErrors->info . " " . $tldConfigErrors->dataType . "</div>";
                            $output .= "<div class='col-sm-6 text-right'>
                                        <a href='" . $link . "/addonmodules.php?module=netim_tld_manager&action=check' target='_blank' class='btn btn-default btn-sm'>" . \Netim\Core\getLoadTranslate('netim.widget.monitoring_view_issues') . "</a>
                                    </div>";
                            $output .= "</div>";
                        }

                        if ($priceErrors->info > 0) {
                            $output .= "<div class='row'>";
                            $output .= "<div class='col-sm-6 text-danger'><i class='fas fa-times'></i> " . $priceErrors->info . " " . $priceErrors->dataType . "</div>";
                            $output .= "<div class='col-sm-6 text-right'>
                                        <a href='" . $link . "/addonmodules.php?module=netim_tld_manager' target='_blank' class='btn btn-default btn-sm'>" . \Netim\Core\getLoadTranslate('netim.widget.monitoring_view_issues') . "</a>
                                    </div>";
                            $output .= "</div>";
                        }
                    } else {
                        if ($tldErrors->info == '' && $tldConfigErrors->info == 0 && $priceErrors->info == 0) {
                        } else {
                            $output .= "<h1 class='text-success'><font color='green'><i class='far fa-smile'></i> " . \Netim\Core\getLoadTranslate('netim.widget.monitoring_no_error') . " </font></h1>";
                        }
                    }
                } catch (\Exception $e) {
                    $output .= '<div id="alertGeneralError" class="alert alert-danger" style="">' . $e->getMessage() . '</div>';
                }
            } else {
                $output .= '<div id="alertGeneralError" class="alert alert-danger" style="">' . \Netim\Monitoring\getData("error")->info . '</div>';
            }
        } else {
            $output .= "<h2 class='text-danger'>" . \Netim\Core\getLoadTranslate('netim.widget.monitoring_disable') . "</h2>";
        }

        # return display
        return <<<EOF
<div class="widget-content-padded">
    {$output}
    </div>
EOF;
    }
}
