<?php
    function set_message(string $message,string $type='e'):void{
        switch($type){
            case 'e':
                $messages=[1,$message];
            case 's':
                $messages=[2,$message];
            default:
            $messages=[3,$message];
        }
        $_SESSION['msg'][] = $messages;
    }
    function set_message_with_code(int $code){
        $_SESSION['msg'][] = [$code];
    }
    function set_error_line_message($error_line){
        set_message("Error code $error_line");
    }
    function get_array_message(array &$jArray=[]):void{
        $jArray['m']=show_msg('y');
    }
    function m(int $messageId):string{
        $w=[];
        $w[1]     = "e|@1@.";//
        $w[2]     = 's|@1@';
        $w[3]     = 'i|@1@';
        $w[66]    = 'e|Some problem there. Please try again';
        if(isset($w[$messageId])){
            return $w[$messageId];
        }
        return '';
    }
    
    function show_msg($jsonShow='No'){
        if($jsonShow=='y'){$rt=[];}
        if(isset($_SESSION['msg'])){
            $sc = count($_SESSION['msg']);
            for($i=0; $i<$sc; $i++){
                $mCode = $_SESSION['msg'][$i];
                if(!is_array($mCode)){
                    $ms = m($mCode);
                    $m = explode('|',$ms);get_message($m[1],$m[0]);
                }
                else{
                    $co = count($mCode);
                    $ms = m($mCode[0]);
                    $m = explode('|',$ms);
                    $mainMessage = $m[1];
                    for($j=1; $j<$co; $j++){$mainMessage = str_ireplace('@'.$j.'@',$mCode[$j],$mainMessage);}
                    if($jsonShow!='y'){get_message($mainMessage,$m[0]);}
                    else{$rt[]=[$m[0],$mainMessage];}
                }
            }
            unset($_SESSION['msg']);
        }
        if($jsonShow=='y'){return $rt;}
    }
    
    function get_message($msg, $cat,$no=''){
        if ($cat == 'w'){
            $type='warning';
            $t = "Warning";
        }
        elseif ($cat == 's'){
            $type='success';
            $t = 'Success';
        }
        elseif ($cat == 'e'){
            $type='danger';
            $t = 'Error';
        }
        else{
            $type='info';
            $t = 'Information';
        }
        if($no){$msgNo = $t.' No '.$no.': ';}else{$msgNo = '';}
        echo "<div class='alert alert-$type'>$msgNo.$msg</div>";
    }
    function fl():string{//file line
		$details=debug_backtrace();
		$file=basename($details[0]['file'],'.php');
		return 'EL-'.$details[0]['line'].'_'.$file;
	}
    $_POST = sanitize($_POST);
    $_GET = sanitize($_GET);
    if (isset($SFU)) {
        $SFU = sanitize($SFU);
    }
    function cleanInput($input){
        $search = [
            '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
            '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
            '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
        ];
        $output='';
        if(!empty($input)){
            $output = preg_replace($search, '', $input);
        }
        return $output;
    }
    function sanitize($input){
        $output =[];
        if (is_array($input)) {
            foreach ($input as $var => $val) {
                $output[$var] = sanitize($val);
            }
        } else {
            $input  = cleanInput($input);
            $output = mysqli_real_escape_string($GLOBALS['connection'], trim(@$input));
            $output = preg_replace('/\s+/', ' ', $output);
        }
        return $output;
    }
    
	function text_file_write($data,$fileName){
		$handle = fopen($fileName, 'a');
		if(is_array($data)){
            $data['log_create_time']=TIME;
			$data=json_encode($data);
		}
		//echo $fileName;echo '<br>';
		fwrite($handle, $data."\n");
		fclose($handle);
		return true;
	}
    
    function create_log($type,$data){
        $textFileName=ROOT_DIR.'/log/';
        if(!is_dir($textFileName)){mkdir($textFileName);}
        $textFileName.=date('Y').'/';
        if(!is_dir($textFileName)){mkdir($textFileName);}
        $textFileName.=date('m').'/';
        if(!is_dir($textFileName)){mkdir($textFileName);}
        $textFileName.=date('d').'/';
        if(!is_dir($textFileName)){mkdir($textFileName);}
        $textFileName.=$type.'/';
        if(!is_dir($textFileName)){mkdir($textFileName);}
        $textFileName.=date('H',TIME).'.txt';
        text_file_write(json_encode($data),$textFileName);
    }

    function json_response($jArray=[]){header('Content-Type: application/json');if(!empty($jArray)){echo json_encode($jArray);exit();}}
    function print_array($a){echo '<pre>';print_r($a);echo '</pre>';}
    function redirect($url){
        header("location:$url");exit();
    }
