<?php
    session_start();

    // if (isset($_POST["lang"])){
    //     $_SESSION["lang"] = $_POST["lang"];
    // }

    // if (isset($_SESSION["lang"])){
    //     $_SESSION["lang"] = $_SESSION["lang"];
    // } else {
    //     $_SESSION["lang"] = "en";
    // }

    function get_action($url) { 
        return basename(parse_url($url, PHP_URL_PATH));
    }

    function redirect($location) {
        header ("Location: " . $location);
    }

    function redirectIfNotLoggedIn($page){
        if ($page != "Login") {
            if(!isset($_SESSION['username'])){
                $_SESSION["message"] = "You must login first!";
                $_SESSION["messageType"] = "warning";
                redirect("../admin/login");
            }
        }
    }

    function notAccessibleToUser() {
        if(isset($_SESSION['username'])){
            if($_SESSION['access_level'] > 1) {
                $_SESSION["message"] = "You are not authorized to view this page!";
                $_SESSION["messageType"] = "warning";
                redirect("../login");
            }
        }
    }

    function getAccessLevel() {
        return $_SESSION['access_level'];
    }
    
    function getFormattedName($string) {

        $string = strtolower($string);
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        $string = preg_replace("/[\s-]+/", " ", $string);
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }

    function set_notification($message, $type) {
        $_SESSION['message'] = $message;
        $_SESSION['messageType'] = $type;
        $_SESSION['displayed'] = "false";
    }

    function upload_file($file, $target_dir) {
        
        $upload_dir = "../../../assets/" . $target_dir . "/";
        
        if ($file['fileToUpload']['size']  ==  0)  {
            set_notification("No file selected.", "error");
            return false;
        }

        $fileName = $file["fileToUpload"]["name"];
        
        if (!is_uploaded_file($file['fileToUpload']['tmp_name']))   {
            set_notification("File upload failed.", "error");
            return false;
        }
        
        if (move_uploaded_file($file['fileToUpload']['tmp_name'],  $upload_dir . $fileName)) {
            set_notification("File upload successful.", "success");
            return true;
        }
    }
?>