<?php

class core
{
    public static function ifGet(string $_string = NULL)
    {
        if($_string == NULL){
            return (empty($_GET)) ? FALSE : TRUE;
        } else {
            if (isset($_GET[$_string])) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
    }

    public static function ifPost(string $_string = NULL)
    {
        if($_string == NULL){
            return (empty($_POST)) ? FALSE : TRUE;
        } else {
            if (isset($_POST[$_string])) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
    }

    public static function ifFiles(string $_string = NULL)
    {
        if ($_string == NULL) {
            return (empty($_FILES)) ? FALSE : TRUE;
        } else {
            if (isset($_FILES[$_string]) AND $_FILES[$_string]["size"] > 0) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
    }

    public static function getGet(string $_string = NULL)
    {
        if ($_string == NULL) {
            return $_GET;
        } else {
            if (isset($_GET[$_string])) {
                return $_GET[$_string];
            } else {
                return NULL;
            }
        }
    }

    public static function getPost(string $_string = NULL)
    {
        if ($_string == NULL) {
            return $_POST;
        } else {
            if (isset($_POST[$_string])) {
                return $_POST[$_string];
            } else {
                return NULL;
            }
        }
    }

    public static function getFiles(string $_string = NULL)
    {
        if ($_string == NULL) {
            return $_FILES;
        } else {
            if (isset($_FILES[$_string])) {
                return $_FILES[$_string];
            } else {
                return NULL;
            }
        }
    }

    public static function isInArrayString(array $_array, string $_string, int $_exact = NULL)
    {
        foreach ($_array as $value) {
            if (strripos($_string, $value) !== FALSE and $_exact == NULL) {
                return TRUE;
            } elseif ($_string == $value and $_exact == 1) {
                return TRUE;
            }
        }
        return FALSE;
    }

    public static function checkboxSelecter(bool $_val, $_echo = 1)
    {
        $tmp = ($_val == TRUE) ? "checked" : "";
        if($_echo == 1){
            echo $tmp;
        } else {
            return $tmp;
        }
    }

    public static function getAllConfig()
    {
        db::query("SELECT "
            . "" . DB_T_CONFIG . ".name, "
            . "" . DB_T_CONFIG . ".value "
            . "FROM " . DB_T_CONFIG);
        return db::resultset();
    }

    public static function getConfig(string $_name)
    {
        db::query("SELECT value FROM " . DB_T_CONFIG . " WHERE name = :name");
        db::bind(':name', $_name);
        return db::single()["value"];
    }

    public static function updateConfig(string $_name, string $_value)
    {
        db::query("UPDATE " . DB_T_CONFIG . " SET "
            . "value = :value "
            . "WHERE name = :name");
        db::bind(':value', $_value);
        db::bind(':name', $_name);

        try {
            db::execute();
            return TRUE;
        } catch (Exception $ex) {
            return FALSE;
        }
    }

    public static function cleanAccent(string $_data)
    {
        $search  = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ò', 'ó', 'ô', 'õ', 'ö', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ');
        $replace = array('A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y');
        $return = str_replace($search, $replace, $_data);
        return strtoupper($return);
    }

    public static function convertDate(string $_datetime, bool $_hour = TRUE)
    {
        $pieces = explode(" ", $_datetime);
        if ($_hour == TRUE) {
            $pieces3 = explode(":", $pieces[1]);
        }
        $pieces2 = explode("-", $pieces[0]);
        if ($_hour == TRUE) {
            return $pieces2[2] . "/" . $pieces2[1] . "/" . $pieces2[0] . " à " . $pieces3[0] . ":" . $pieces3[1];
        } else {
            return $pieces2[2] . "/" . $pieces2[1] . "/" . $pieces2[0];
        }
    }

    public static function dateFr(string $_timestampMysql = NULL)
    {
        if ($_timestampMysql == NULL) {
            $Now = new DateTime('now', new DateTimeZone(TIME_ZONE));
            return $Now->format("d/m/Y H:i:s");
        } else {
            return DateTime::createFromFormat("d/m/Y H:i:s", $_timestampMysql);
        }
    }

    public static function dateFromTimestamp(int $_timestamp = NULL)
    {
        if ($_timestamp == NULL) {
            return NULL;
        } else {
            return date("Y-m-d H:i:s", $_timestamp);
        }
    }

    public static function dateWhithoutHours(string $_datetime)
    {
        return explode(" ", $_datetime)[0];
    }

    public static function formatFileSize(float $_size, int $_decimalplaces = 0)
    {
        $sizes = array('O', 'Ko', 'Mo', 'Go', 'To');
        for ($i = 0; $_size > 1024 && $i < count($sizes) - 1; $i++) {
            $_size /= 1024;
        }
        return round($_size, $_decimalplaces) . ' ' . $sizes[$i];
    }

    public static  function formatEuro($_amount) {
        $amount = (float)$_amount;
        $formattedAmount = number_format($amount, 2, ',', ' ');
        return $formattedAmount . ' €';
    }
    

    public static function checkStringOnly(string $_string)
    {
        if (!ctype_alpha($_string)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public static function elementMenu(string $_id, string $_href, string $_titre, string $_style = NULL)
    {
        if (access::ifAccesss($_id)) {
            ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
            echo '<li class="nav-item" style="margin:5px 0;"><a style="display:unset;" class="nav-link' . get::currentPage($_id) . '" aria-current="page"  href="' . $_href . '"' . $_style . '>';
            echo icon::getFont(["type" => $_id, "size" => "18px"]);
            echo ' ' . $_titre . '</a></li>';
        }
    }

    public static function elementMenuLink(string $_id, string $_href, string $_titre, string $_style = NULL, string $_target = "_blank")
    {
        if (access::ifAccesss($_id)) {
            ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
            echo '<li class="nav-item" style="margin:5px 0;"><a style="display:unset;" class="nav-link" target="' . $_target . '" href="' . $_href . '"' . $_style . '>';
            echo icon::getFont(["type" => $_id, "size" => "18px"]);
            echo ' ' . $_titre . '</a></li>';
        }
    }

    public static function elementMenuH6(string $_id, string $_titre, string $_style = NULL, string $_collapse = NULL)
    {
        if (access::ifAccesss($_id)) {
            ($_style != NULL) ? $_style = $_style : NULL;
            echo '<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
                        <a style="text-decoration: none; ' . $_style . '" href="#' . $_collapse . '" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle text-dark">' . $_titre . '</a>
                    </h6>';
        }
    }

    public static function filAriane(array $_arbo)
    {

        $return = '<nav aria-label="breadcrumb bg-300">';
        $return .= '<ol class="breadcrumb" style="padding:5px 10px; border-bottom: 1px solid #e9ecef;">';

        foreach ($_arbo["arbo"] as $label => $lien) {
            if ($_arbo["current"] == $label) {
                $return .= '<li class="breadcrumb-item active" aria-current="page">' . $label . '</li>';
            } elseif ($lien == NULL) {
                $return .= '<li class="breadcrumb-item">' . $label . '</li>';
            } else {
                $return .= '<li class="breadcrumb-item"><a href="' . $lien . '" title="' . $label . '">' . $label . '</a></li>';
            }
        }
        $return .= '</ol>';
        $return .= '</nav>';
        return $return;
    }

    public static function caculPourcentage(?int $_nombre, ?int $_total, int $_pourcentage = 100)
    {
        if ($_nombre == NULL) return 0;
        $resultat = ($_nombre / $_total) * $_pourcentage;
        return round($resultat);
    }

    public static function encodeUTF8(string $_data)
    {
        return (mb_detect_encoding($_data) != "UTF-8") ? mb_convert_encoding($_data, 'UTF-8', mb_list_encodings()) : $_data;
    }

    public static function testConnexionInternet()
    {
        $hosts = ['1.1.1.1', '1.0.0.1', '8.8.8.8', '8.8.4.4'];
        foreach ($hosts as $host) {
            if ($connected = @fsockopen($host, 443)) {
                fclose($connected);
                return TRUE;
            }
        }
        return FALSE;
    }

    public static function printDateTxt()
    {
        $date = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE);
        return $date->format(time()) . " à " . date("H:i:s");
    }

    public static function resetDatas()
    {
        db::query("TRUNCATE " . DB_T_TEMP_SALARIES);
        db::execute();
        json::delete("tmp_salaries");

        db::query("TRUNCATE " . DB_T_SALARIES);
        db::execute();
        json::delete("salaries");

        db::query("TRUNCATE " . DB_T_FILES);
        db::execute();
        file::cleanAllFiles(DIR_DATAS_FILES);

        db::query("TRUNCATE " . DB_T_EXCEL);
        db::execute();
        json::delete("excel");

        db::query("TRUNCATE " . DB_T_SALARIES_PROWEB);
        db::execute();
        json::delete("salaries-proweb");

        db::query("TRUNCATE " . DB_T_EVENTS_INSCRITS);
        db::execute();

        db::query("TRUNCATE " . DB_T_EVENTS);
        db::execute();

        json::delete("events");

        db::query("TRUNCATE " . DB_T_EXCEL_PROWEB);
        db::execute();
        json::delete("excel-proweb");
        file::cleanAllFiles(SFTP_LOCAL);
    }

    public static function base64_url_encode(string $val)
    {
        return strtr(base64_encode($val), '+/=', '-_,');
    }

    public static function base64_url_decode(string $val)
    {
        return base64_decode(strtr($val, '-_,', '+/='));
    }

    public static function convertirEnUtf8(string $_texte)
    {
        if (!mb_detect_encoding($_texte, 'UTF-8', TRUE)) {
            return mb_convert_encoding($_texte, 'UTF-8', 'auto');
        } else {
            return $_texte;
        }
    }

    public static function printFormSelectOption(string $_string = NULL, $_value)
    {
        if ($_string != NULL and $_string == $_value) {
            echo " selected";
        }
    }

    public static function getFormValue(string $_string = NULL)
    {
        if ($_string != NULL) {
            return $_string;
        }
    }

    public static function printFormValue(string $_string = NULL)
    {
        if ($_string != NULL) {
            echo $_string;
        }
    }

    public static function convertBytes(float $val, string $type_val = "o", string $type_wanted = "Mo", bool $_float = FALSE)
    {
        $tab_val = array("o", "ko", "Mo", "Go", "To", "Po", "Eo");
        if (!(in_array($type_val, $tab_val) && in_array($type_wanted, $tab_val)))
            return 0;
        $tab = array_flip($tab_val);
        $diff = $tab[$type_val] - $tab[$type_wanted];

        $type_wanted_print = $_float == FALSE ? $type_wanted : NULL;

        if ($diff > 0)
            return round(($val * pow(1024, $diff)), 2) . $type_wanted_print;
        if ($diff < 0)
            return round(($val / pow(1024, -$diff)), 2) . $type_wanted_print;
        return round(($val), 2) . $type_wanted_print;
    }

    public static function getSizeDataBase(){
        db::query("SELECT
                    table_schema AS nameDB, 
                    ROUND(SUM( data_length + index_length ) / 1024 / 1024, 2) AS moDB 
                    FROM information_schema.TABLES
                    WHERE TABLE_SCHEMA = '".DB_NAME."'");
        return db::single();
    }

    public static function progressBarWarning(float $_num, float $_max, string $_label, string $_icon){
        $changeUnit = 1073741824;
        $valueUnitNum = $_num >= $changeUnit ? "Go" : "Mo";
        $valueUnitMax = $_max >= $changeUnit ? "Go" : "Mo";

        $pourcentage = number_format(($_num / $_max) * 100, 2);
        if($pourcentage < 50){
            $infos = ["color" => "bg-success"];
        } elseif($pourcentage < 75){
            $infos = ["color" => "bg-warning"];
        } else {
            $infos = ["color" => "bg-danger"];
        }

        echo '  <div class="mb-3" style="margin:10px 0;">
                    <label class="form-label" style=""><i class="'.$_icon.'" style="font-size:18px; margin:4px;"></i> <span style="font-weight: bold;">'.$_label.'</span> [' . core::convertBytes($_num, "o", $valueUnitNum) . ' / ' . core::convertBytes($_max, "o", $valueUnitMax) . ']</label>
                    <div class="progress" role="progressbar" aria-label="Success example" aria-valuenow="'.$pourcentage.'" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar '.$infos["color"].'" style="width: '.$pourcentage.'%">'.$pourcentage.'%</div>
                    </div>
                </div>';
    }

    static public function printBadgeGeneral(bool $_alerte){
        return $_alerte == TRUE ? '<span class="position-absolute start-100 translate-middle p-1 bg-danger border border-light rounded-circle"></span>' : NULL;
    }

    static public function ifbadge()
    {
        $return = [];
        $return["DOC"] = document::badgeAlert();
        
        if ($return["DOC"] != NULL) {
            $return["ALERTE"] = TRUE;
        } else {
            $return["ALERTE"] = FALSE;
        }
        return $return;
    }

    static public function menu(array $_navInfos){
        $badge = self::ifbadge();
        echo '<a href="/" style="box-shadow: none; background-color:'. $_navInfos["color"] .';" class="navbar-brand">' . $_navInfos["title"] . '</a>' . debug::getBadges();
        echo '<div id="navbarCollapse" class="collapse navbar-collapse p-0">';
        echo '<ul class="nav navbar-nav ms-auto">';
        echo '<li class="nav-item dropdown">';
        echo '<a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">' . session::getName() . self::printBadgeGeneral($badge["ALERTE"]) . '</a>';
        echo '<div class="dropdown-menu dropdown-menu-end">';
        echo '<a href="/user.html" class="dropdown-item">Mon profil</a>';
        if((access::ifAccesss("documents") AND session::getType() == 5) OR session::getType() == 1){ // Membre du bureau ou Admin
            $nb = $badge["DOC"] > 0 ? '<span class="position-absolute badge rounded-pill bg-danger" style="right:-10px; margin-top:-10px;">' . $badge["DOC"] . '</span>' : NULL;
            echo '<a href="/documents-my-assign.html" class="dropdown-item">Vos assignations' . $nb . '</a>';
            echo '<a href="/alertes-emails.html" class="dropdown-item">Vos règles d\'alertes</a>';
        }
        echo '<div class="dropdown-divider"></div>';
        echo '<a href="/submit.php?from=logout" class="dropdown-item">Se déconnecter</a>';
        echo '</li>';
        echo '</div>';
        echo '</ul>';
        echo '</div>';
    }

    static public function getUserIP() {
        $ip = 'Inconnue';
    
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            // IP partagée par un proxy
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // IP du client derrière un proxy
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            // IP du client directement connectée au serveur
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    
        // Nettoyage des IPs multiples dans le cas de 'HTTP_X_FORWARDED_FOR'
        if (strpos($ip, ',') !== false) {
            $ip = explode(',', $ip)[0];
        }
    
        return $ip;
    }
}
