<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Carbon;

use App\Models\Academique;
use App\Models\TabEtudiant;
use App\Models\User;
use App\Models\GestStudentR;
use App\Models\Etablissement;


if(!function_exists('changeEnv')) {
    function changeEnv(array $data) {
        if (count($data) > 0) {
            // purge cache of DatabaseManager
            DB::purge("tenant");

            // get current configs
            $config = config("database.connections.tenant");
            // add prefix to database name
            if (!empty($data["database"])) {
                $data["database"] = config('app.db_own_prefix').$data["database"];
            }

            // merge old and new configs
            $config = array_merge($config, $data);
            // save new configs
            config(["database.connections.tenant"=> $config]);

            return true;
        } else {
            return false;
        }
    }
}

if(!function_exists('getGlobalStats')){
    function getGlobalStats() {
        // $year = Academique::where('affiche', 'YES')->first()->annee_acad;
        $year = session('annee_acad');

        $total_boys  = DB::connection('tenant')
            ->table('tabetudiant')
            ->select('*')
            ->join('tabinscription','tabetudiant.matricule','=','tabinscription.matricule')
            ->where('tabinscription.annee_acad',$year)
            ->where('sexe', 'M')
            ->count();

        $total_girls  = DB::connection('tenant')
            ->table('tabetudiant')
            ->select('*')
            ->join('tabinscription','tabetudiant.matricule','=','tabinscription.matricule')
            ->where('tabinscription.annee_acad',$year)
            ->where('sexe', 'F')
            ->count();

        $total = [
            "total_boys" => $total_boys,
            "total_girls" => $total_girls
        ];

        return $total;
    }
}

/** Current academic year */
if(!function_exists('current_acad')){
    function current_acad(){
        $acad = DB::connection('tenant')->table('academique') // periodeinscription
        ->where('affiche', 'YES')
        ->select('annee_acad', 'periode')
        ->first();

        $acad = json_decode(json_encode($acad), true);

        return $acad;
        // return $acad->annee_acad;
    }
}

/** Current academic year */
if(!function_exists('current_period')){
    function current_period(){
        $acad = DB::connection('tenant')->table('academique') // periodeinscription
        ->where('affiche', 'YES')
        ->select('annee_acad', 'periode')
        ->first();

        $acad = json_decode(json_encode($acad), true);

        return $acad;
    }
}

/** User connected data */
if(!function_exists('user_data')){
    function user_data() {

        $username = session('username');

        $temp_infos = User::where('username',$username)
            ->select('matricule', 'username', 'type_user', 'email', 'phone')
            ->first();

        $user_infos =
            GestStudentR::where('matricule', $temp_infos->matricule)
                ->select('matricule', 'nom', 'prenom', 'country_code', 'nationalite', 'description', 'sexe')
                ->first();

        $temp_infos = json_decode(json_encode($temp_infos), true);

        $user_infos = json_decode(json_encode($user_infos), true);

        $user_infos =  array_merge($user_infos, $temp_infos);

        return $user_infos;
    }
}

/** Etablissement data */
if(!function_exists('get_school')){
    /**
     * Give Etablissment info
     *
     * @param integer $idEta - etablissement id ( if not given, current Eta is send )
     *
     * @return mixed -
     *  - table of merged info from table Etablissement witn and without tenant connection
     */
    function get_school($idEta = []) {


        if ( !(gettype ($idEta) == "integer") ) {
            $idEta = session('id_etablissement');
        }

        $infos1  = Etablissement::where('idEtablissement',$idEta)
            ->select("idEtablissement", "idUniversite", "nameimgeta", "sigle", "namebase", "descreta", "photosiege", "email")
            // ->select('*')
            ->first();

            // dd ($infos1);

        changeEnv(['database'  =>$infos1->namebase]);
        

        $infos1 = json_decode(json_encode($infos1), true);

        $infos2 =
            DB::connection('tenant')
            ->table('etablissement')
            ->where('idEtablissement',$idEta)
            ->select( "slogan", "dureeValideCarte", "choixTemp", "fonction", "signature", "signataire", "dateDepart", "message", "couleur", "couleur2", "couleur3", "ecouleur", "ecouleur2", "ecouleur3")
            // ->select( "textColor2")
            ->first();

            // dd ($infos2);
            

        // $infos2 = [];

        $infos2 = json_decode(json_encode($infos2), true);


        $etablissement = array_merge($infos1, !($infos2) ? [] : $infos2);

        // dd ($etablissement);

       

        
            $etablissement = array_merge($infos1, is_null($infos2) ? [] : $infos2);

            $a = gettype($infos1) == "array";
            $b = gettype($infos2) == "array";

            if ( $a && $b) {
                $etablissement = array_merge($infos1, $infos2);
            } else {
                $etablissement = $a ? $infos1 : $infos2;
            }
        

        // dd ($etablissement);

        return $etablissement;
    }
}

/** University data */
if(!function_exists('get_uni')){
    /**
     * Give university info
     *
     * @param integer $idEta - etablissement id ( if not given, current Eta is send )
     *
     * @return mixed -
     *  - table of University
     */
    function get_uni($idEta = "") {

        if ( !(gettype ($idEta) == "integer") ) {
            $idEta = session('id_etablissement');
        }

        $idUniversity  = Etablissement::where('idEtablissement',$idEta)
            ->selectRaw("idUniversite")
            ->value("idUniversite");

        $university =
            DB::connection('tenant')->table('universite')
            ->where('idUniversite',$idUniversity)
            ->select('idUniversite', 'sigleuni', 'descruni', 'nameimguni')
            ->first();

        $university = json_decode(json_encode($university), true);

        return $university;
    }
}

/** Local Time info */
if(!function_exists('local_time')){
    function local_time() {

        date_default_timezone_set('Africa/Porto-Novo');

        $locales =    [
            "monthNames" => ['Janvier', 'février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
            "dayNames" => ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
            "infoDate" => getdate()
        ];

        return $locales;
    }
}

/** Fermeture progiciel */
if(!function_exists('fermeture_progiciel')){
    function fermeture_progiciel($idEta) {

        if ( !(gettype ($idEta) == "integer") ) {
            //contrôle de la donnée
            $idEta = session('id_etablissement');
        }

        $femeture  = DB::table('fermeture')
            ->where('idEtablissement', $idEta)
            ->first();

        $femeture = json_decode(json_encode($femeture), true); //heures ouvrables

        if ( !(gettype($femeture) == "array") ) {
            return false;
        };

        $locales = local_time();

        $months = $locales['monthNames'];
        $days = $locales['dayNames'];
        $date = $locales['infoDate'];

        $h = $date["hours"];
        $m = $date["minutes"];
        $s = $date["seconds"];

        $minutef = ($h * 60) + $m; //minutes écoulées

        $jour = $days[$date["wday"]];

        $type_user = session('type_user');

        /*
            Récupération des paramètre de fermeture de la plateforme
        */

        //Jours ouvrables
        $jours_ouvrables = $femeture['jours_ouvrables'];
        $explode = explode(',', $jours_ouvrables);

        $heure_debut = $femeture['heure_debut'];
        $heure_fin = $femeture['heure_fin'];

        $minute_debut = (explode(':', $heure_debut)[0] * 60) + explode(':', $heure_debut)[1];
        $minute_fin   = (explode(':', $heure_fin )[0] * 60) + explode(':', $heure_fin )[1];

        //Jours semi-ouvrables
        $jours_semi_ouvrables = $femeture['jours_semi_ouvrables'];
        $explode1 = explode(',', $jours_semi_ouvrables);

        $heure_debut1 = $femeture['heure_debut1'];
        $heure_fin1   = $femeture['heure_fin1'];

        $minute_debut1 = (explode(':', $heure_debut1)[0] * 60) + explode(':', $heure_debut1)[1];
        $minute_fin1   = (explode(':', $heure_fin1 )[0] * 60) + explode(':', $heure_fin1 )[1];

        //Jours non ouvrables
        $jours_non_ouvrables = $femeture['jours_non_ouvrables'];
        $explode2 = explode(',', $jours_non_ouvrables);
        $valeur = $femeture['valeur'];

        /*
        Fin Récupération des paramètre de fermeture de la plateforme
        */

        if($type_user != 3){
            if(strcmp($valeur, 'YES') == 0) {

                if (in_array($jour, $explode2)) {
                    // On détruit la session
                    session()->flush();
                    return redirect()->back()->withErrors([
                        'error' => "Vous n'êtes pas autorisé à vous connecter sur cette plateforme !",
                    ]);
                }

                if ( in_array($jour, $explode1)  && ( ($minutef > $minute_fin1 ) || ($minutef < $minute_debut1) ) ) {
                    // On détruit la session
                    session()->flush();
                    return redirect()->back()->withErrors([
                        'error' => "Vous n'êtes pas autorisé à vous connecter sur cette plateforme !",
                    ]);
                }

                if ( in_array($jour, $explode)  && ($minutef > $minute_fin || $minutef < $minute_debut) ) {
                    // On détruit la session
                    session()->flush();
                    return redirect()->back()->withErrors([
                        'error' => "Vous n'êtes pas autorisé à vous connecter sur cette plateforme !",
                    ]);
                }

            }
        }

    }
}

/** Statistic data */
if(!function_exists('plotData')){
    function plotData(){

        $idDepartements =
            DB::connection('tenant')
            ->table('departement')
            ->where('idEtablissement', '=', session('id_etablissement'))
            // ->whereIn('departement.idEtablissement', explode(',', session('mes_etablissement')))
            ->get()
            ->pluck('idDepartement');

        $user_filieres = DB::connection('tenant')
            ->table('tabetudiant')
            ->select('*')
            ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
            ->where('tabinscription.annee_acad', session('annee_acad') )
            ->get()
            ->groupBy('idFiliere')
            ->toArray();

        $user_filieres = json_decode(json_encode($user_filieres), true);

        $effectif_filieres = array_map("count", $user_filieres);

        // asort($effectif_filieres);

        $filieres = DB::connection('tenant')
            ->table('filieres')
            ->select('idFiliere', 'intituleFilieres', 'sigleFilieres')
            // ->whereIn('idFiliere', explode(',', session('filieres')))
            ->whereIn('idDepartement', $idDepartements)
            ->get()
            ->toArray();


        foreach ($filieres as $i => $filiere) {
            $filiere->effectif =  0;
            if ( isset($effectif_filieres[$filiere->idFiliere]) ) {
                $filiere->effectif = $effectif_filieres[$filiere->idFiliere];
            }
        }

        // $filieres = json_decode(json_encode($filieres), true);

        $filiereIds = array_column($filieres, 'effectif');
        array_multisort($filiereIds, SORT_ASC, $filieres);

        $return = [
            "filieres" => $filieres,
            "user_filieres" => $user_filieres
        ];

        return $return;
    }
}

/** get user etablissement */
if(!function_exists('getUserEta')){
    function getUserEta($group = false) {
        $etablissements = $universites = [];

        $mes_eta = session('mes_etablissement');

        $mes_eta = explode(',',$mes_eta);

        if ( count($mes_eta) ) {

            if ($group) {

                $etablissements = Etablissement::whereIn('idEtablissement',$mes_eta)
                    ->select('idUniversite', 'idEtablissement', 'sigle', 'namebase', 'descreta')
                    ->get()
                    ->groupBy('idUniversite');

                $etablissements = json_decode(json_encode($etablissements), true);


                $universites = array_unique(array_column(array_merge(...$etablissements), 'idUniversite'));


                $universites = DB::connection('tenant')->table('universite')
                    ->select('idUniversite', 'sigleuni', 'descruni')
                    ->get();

                $universites = json_decode(json_encode($universites), true);
            } else {
                $etablissements = Etablissement::whereIn('idEtablissement',$mes_eta)
                    ->select('idUniversite', 'idEtablissement', 'sigle', 'namebase', 'descreta')
                    ->orderBy('descreta', 'asc')
                    ->get();

                $etablissements = json_decode(json_encode($etablissements), true);
            }
        }

        $return = [
            "etablissements" => $etablissements,
            "universites" => $universites
        ];

        return $return;
    }
}

/** get user role */
if (! function_exists('userRole')) {

    /**
     * Centralized place where user roles are !
     *
     * @param integer $typeUser - type of user (0, 1, 2, 3, 4, 5, 6, 7)
     * @param boolean $choice - add additional privilege choice for Admin and Admin Principal
     *
     * @return mixed -
     *  - the user role in array with typeUser as key
     *  - or the array with additionnal role
     *  - or the array of roles
    */
    function userRole($typeUser = "", $choice = false)
    {
        $options = [
            0 => "User",
            1 => "Validateur",
            2 => "Admin",
            3 => "Admin Principal",
            4 => "Professeur",
            5 => "Scolarité",
            6 => "Comptable",
            7 => "SuperAdmin",
        ];

        $output = NULL;

        if ( gettype ($typeUser) == "integer") {

            if (array_key_exists($typeUser, $options)) {

                $key = array_search($options[$typeUser], $options);

                $output = array_slice($options, $key, 1, true);

                if ( in_array($typeUser, [1, 2]) && $choice) {
                    $output[0] = "User";
                }
            } else {
                $output = $options;
            }

        } else {
            $output = $options;
        }

        return $output;
    }
}

/** get filieres */
if (! function_exists('getFilieres')) {

    /**
     * Centralized place where all filieres are !
     *
     * @param integer $id - filiere id
     * @return string - title of filiere
     */

    function getFilieres($idEta, $filiere_id = "")
    {
        if ( !(gettype ($idEta) == "integer")) {
            $idEta = session('id_etablissement');
        }

        $idDepartements =
            DB::connection('tenant')
            ->table('departement')
            ->where('idEtablissement', '=', $idEta)
            ->get()
            ->pluck('idDepartement');

        $filieres =
            DB::connection('tenant')
            ->table('filieres')
            ->whereIn('filieres.idDepartement',$idDepartements)
            ->select('idFiliere', 'intituleFilieres', 'sigleFilieres')
            ->get();


        $filieres = json_decode(json_encode($filieres), true);

        $output = NULL;

        if ( gettype ($filiere_id) == "integer") {

            if (array_key_exists($filiere_id, array_column($filieres, 'idFiliere'))) {

                $key = array_search($filiere_id, array_column($filieres, 'idFiliere'));

                $output = $filieres[$key]['sigleFilieres'];
            } else {
                $output = $filieres;
            }

        } else {
            $output = $filieres;
        }

        return $output;
    }
}

/** get filieres */
if (! function_exists('getUserFilieres')) {

    /**
     * Centralized place where all filieres are !
     *
     * @param integer $id - filiere id
     * @return string - title of filiere
     */

    function getUserFilieres($filiere_id = "")
    {
        $filieres =
            DB::connection('tenant')
            ->table('filieres')
            ->select('idFiliere', 'intituleFilieres', 'sigleFilieres')
            ->whereIn('idFiliere', explode(',', session('filieres')))
            ->get();


        $filieres = json_decode(json_encode($filieres), true);

        $output = NULL;

        if ( gettype ($filiere_id) == "integer") {

            if (array_key_exists($filiere_id, array_column($filieres, 'idFiliere'))) {

                $key = array_search($filiere_id, array_column($filieres, 'idFiliere'));

                $output = $filieres[$key]['sigleFilieres'];
            } else {
                $output = $filieres;
            }

        } else {
            $output = $filieres;
        }

        return $output;
    }
}

/** get statut */
if (! function_exists('getStatut')) {

    /**
     * Centralized place where all statut are !
     *
     * @param integer $id - statut id
     * @return string - title of statut
     */
    function getStatut($statut_id = [])
    {
        $statuts =
            DB::connection('tenant')
            ->table('statuts')
            ->where('idEtablissement', '=', session('id_etablissement'))
            ->get();

        $statuts = json_decode(json_encode($statuts), true);

        $output = NULL;

        if ( gettype ($statut_id) == "integer") {

            if (array_key_exists($statut_id, array_column($statuts, 'idStatut'))) {

                $key = array_search($statut_id, array_column($statuts, 'idStatut'));

                $output = $statuts[$key]['statut'];
            } else {
                $output = $statuts;
            }

        } else {
            $output = $statuts;
        }

        return $output;
    }
}


/** Check if a file exist or not in public folder */
if (!function_exists('checkFileExist')) {
    function checkFileExist($path){
        // $public_path = str_replace("/", DIRECTORY_SEPARATOR, asset(''));
        $public_path = asset('');
        $direct_path = str_replace($public_path, "", $path);
		$direct_path = str_replace("/", DIRECTORY_SEPARATOR, $direct_path);

		return file_exists($direct_path) ? true : false;
    }
}

/** Get formation level */
// if (! function_exists('findNiveau')) {
//     function findNiveau($niveau = "")
//     {
//         // $level = [ "LICENCE", "MASTER", "DOCTORAT"];
//         // $annees = [1, 2, 3];

//         $niveauFormation = DB::connection('tenant')
//         ->table('niveauformation')
//         ->get();
      
//         $level = $niveauFormation->pluck('niveauFormation');
//         $level = json_decode(json_encode($level), true);

//         $niveauFormation = json_decode(json_encode($niveauFormation), true);

//         $annees = array_column($niveauFormation, 'id');

//         // dd($niveauFormation, $annees, $level);

//         if ( gettype ($niveau) == "integer") {
//             if (in_array($niveau, $annees)) {
//                 $level = $level[$niveau - 1];
//             }
//         }

//         return $level;
//     }
// }


if (!function_exists('findNiveau')) {
    function findNiveau()
    {
        // Récupérer les données de la table niveauformation
        $niveauFormation = DB::connection('tenant')
            ->table('niveauformation')
            ->pluck('niveauFormation')
            ->toArray(); 

        return $niveauFormation;
    }
}



/** Title of formation year */
if (! function_exists('nominateYear')) {
    function nominateYear($annee = "")
    {
        // $title = [ "Première année", "Deuxième année", "Troisième année"];
        // $annees = [1, 2, 3];

        $annee_etude = DB::connection('tenant')
        ->table('anneeetude')
        ->get();

        $title = $annee_etude->pluck('annee_etude');
        $title = json_decode(json_encode($title), true);

        $annee_etude = json_decode(json_encode($annee_etude), true);
        $annees = array_column($annee_etude, 'id');

        if ( gettype ($annee) == "integer") {
            if (in_array($annee, $annees)) {
                $annee_etude = $title[$annee - 1];
            }
        }

        return $title;
    }
}

if (! function_exists('getYear')) {

    function getYear()
    {

        $annee = DB::connection('tenant')
        ->table('anneeetude')
        ->get()
        ->pluck('id');
        // $annee  = [ 1, 2, 3 ];

        return $annee;
    }
}

/** Format data */
if (! function_exists('dateFormat')) {
    function dateFormat($origDate)
    {
        $timezone = date_default_timezone_set('Africa/Porto-Novo');

        $date = Carbon::parse($origDate)->format('d/m/Y h:m');

        $result = explode(" ", $date);

        return $result[0]. ' à ' .$result[1];
    }
}

if(!function_exists('getImgPath')){
    /**
     * @param string $type - type of image we want
     * @param mixed $meta - any aditionnal data to get the path
     */


    //  function getImgPath($type, $link, $meta = null, $storage = false){

    //     if ($storage) {
    //         $baseUrl = "storage/images/";

    //         if ($type == "PROFIL") {
    //             // here $meta will be type_user
    //             switch ($meta) {
    //                 case '0': // Etudiant
    //                     $dir = "Inscription/";
    //                     break;
    //                 case '2': // Admin
    //                 case '3': // Admin Principal
    //                 case '4': // Professeur
    //                     $dir = "Admin/";
    //                     break;
    //                 default:
    //                     $dir = "";
    //                     break;
    //             }
    //         } elseif ($type == "CARD" || $type == "SCHOOL") {
    //             $dir = "Admin/";
    //         } elseif ($type == "QR_CODE") {
    //             $dir = "Inscription/qrcode/";
    //         } else {
    //             $dir = "";
    //         }

    //         $url = $baseUrl.$dir.$link;

    //         $url = asset($baseUrl.$dir.$link);
    //     } else {
    //         // $baseUrl = "https://progiciel.geststudent.net/";
    //         $baseUrl = "https://progiciel.geststudent.net/Inscription/qrcode/";
            
    //         // $baseUrl = config('app.aws_url');

    //         $url = $baseUrl.$link;
    //     }

    //     return $url;
    // }


    function getImgPath($type, $link, $meta = null, $storage = false) {
        if ($storage) {
            $baseUrl = "storage/images/";
        } else {
            $baseUrl = $type === "QR_CODE" 
                ? "https://progiciel.geststudent.net/Inscription/qrcode/"
                : config('app.aws_url');
        }
    
        if ($type === "PROFIL" && $storage) {
            switch ($meta) {
                case '0': // Étudiant
                    $dir = "Inscription/";
                    break;
                case '2': // Admin
                case '3': // Admin Principal
                case '4': // Professeur
                    $dir = "Admin/";
                    break;
                default:
                    $dir = "";
                    break;
            }
        } elseif (in_array($type, ["CARD", "SCHOOL"]) && $storage) {
            $dir = "Admin/";
        } elseif ($type === "QR_CODE" && $storage) {
            $dir = "Inscription/qrcode/";
        } else {
            $dir = "";
        }
    
        $url = $baseUrl . $dir . $link;
    
        if ($storage) {
            $url = asset($url);
        }
    
        return $url;
    }
}    

/** Get text color */
if(!function_exists('textColor')){
    function textColor($col) {

        $newCouleur = 0;
        $noir = "#";
        $blanc = "#";
        $i = 0;
        for ($i = 1; $i < strlen($col); $i++) {
            if (substr($col, $i, 1) < '8') {
                $newCouleur++;
            }
            $noir = $noir . '0';
            $blanc = $blanc . 'F';
        }
        if ($newCouleur >= (strlen($col) - 1) / 2) {
            $newCouleur = $blanc;
        } else {
            $newCouleur = $noir;
        }
        return $newCouleur;
    }
}

if(!function_exists("get_user_agent")){
    function get_user_agent(){
        return $_SERVER['HTTP_USER_AGENT'];
  }
}

if(!function_exists('get_device')){
    function get_device(){

        $tablet_browser = 0;
        $mobile_browser = 0;

        if(preg_match('/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i', strtolower($_SERVER['HTTP_USER_AGENT']))){
            $tablet_browser++;
        }

        if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile)/i', strtolower($_SERVER['HTTP_USER_AGENT']))){
            $mobile_browser++;
        }

        if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),
        'application/vnd.wap.xhtml+xml')> 0) or
            ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or
                isset($_SERVER['HTTP_PROFILE'])))){
                    $mobile_browser++;
        }

        $mobile_ua = strtolower(substr( get_user_agent(), 0, 4));
        $mobile_agents = array(
            'w3c','acs-','alav','alca','amoi','audi','avan','benq','bird','blac','blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
            'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-','maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',

            'newt','noki','palm','pana','pant','phil','play','port','prox','qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',

            'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-','tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
            'wapr','webc','winw','winw','xda','xda-');

            if(in_array($mobile_ua,$mobile_agents)){
                $mobile_browser++;
            }

            if(strpos(strtolower( get_user_agent()),'opera mini') > 0){
                $mobile_browser++;

                //Check for tables on opera mini alternative headers

                $stock_ua =
                strtolower(isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])?
                $_SERVER['HTTP_X_OPERAMINI_PHONE_UA']:
                (isset($_SERVER['HTTP_DEVICE_STOCK_UA'])?
                $_SERVER['HTTP_DEVICE_STOCK_UA']:''));

                if(preg_match('/(tablet|ipad|playbook)|(android(?!.*mobile))/i', $stock_ua)){
                    $tablet_browser++;
                }
            }

            if($tablet_browser > 0){
                //do something for tablet devices

                return 'Tablet';
            }
            else if($mobile_browser > 0){
                //do something for mobile devices

                return 'Mobile';
            }
            else{
                //do something for everything else
                    return 'Computer';
            }

    }
}

if(!function_exists('get_os')){
    function get_os(){

        $user_agent = get_user_agent();
        $os_platform = "Unknown OS Platform";
        $os_array = array(
            '/windows nt 10/i'  => 'Windows 10',
            '/windows nt 6.3/i'  => 'Windows 8.1',
            '/windows nt 6.2/i'  => 'Windows 8',
            '/windows nt 6.1/i'  => 'Windows 7',
            '/windows nt 6.0/i'  => 'Windows Vista',
            '/windows nt 5.2/i'  => 'Windows Server 2003/XP x64',
            '/windows nt 5.1/i'  => 'Windows XP',
            '/windows xp/i'  => 'Windows XP',
            '/windows nt 5.0/i'  => 'Windows 2000',
            '/windows me/i'  => 'Windows ME',
            '/win98/i'  => 'Windows 98',
            '/win95/i'  => 'Windows 95',
            '/win16/i'  => 'Windows 3.11',
            '/macintosh|mac os x/i' => 'Mac OS X',
            '/mac_powerpc/i'  => 'Mac OS 9',
            '/linux/i'  => 'Linux',
            '/ubuntu/i'  => 'Ubuntu',
            '/iphone/i'  => 'iPhone',
            '/ipod/i'  => 'iPod',
            '/ipad/i'  => 'iPad',
            '/android/i'  => 'Android',
            '/blackberry/i'  => 'BlackBerry',
            '/webos/i'  => 'Mobile',
        );

        foreach ($os_array as $regex => $value){
            if(preg_match($regex, $user_agent)){
                $os_platform = $value;
            }
        }
        return $os_platform;
    }
}

if(!function_exists("get_ip")) {
    function get_ip(){

        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if(isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;

    }
}

if(!function_exists('get_browsers')){
    function get_browsers(){

        $user_agent= get_user_agent();

        $browser = "Unknown Browser";

        $browser_array = array(
            '/msie/i'  => 'Internet Explorer',
            '/Trident/i'  => 'Internet Explorer',
            '/firefox/i'  => 'Firefox',
            '/safari/i'  => 'Safari',
            '/chrome/i'  => 'Chrome',
            '/edge/i'  => 'Edge',
            '/opera/i'  => 'Opera',
            '/netscape/'  => 'Netscape',
            '/maxthon/i'  => 'Maxthon',
            '/knoqueror/i'  => 'Konqueror',
            '/ubrowser/i'  => 'UC Browser',
            '/mobile/i'  => 'Safari Browser',
        );

        foreach($browser_array as $regex => $value){
            if(preg_match($regex, $user_agent)){
                $browser = $value;
            }
        }
        return $browser;
    }
}
