<?php
ini_set("display_errors", "on");

echo "<h1>AUFGABE 3</h1>";

// file names
$error = "error.log";
$access = "access.log";
$debug = "debug.log";

// read function
function read($file){
    $fileName = $file.".log";
    $fp = fopen($fileName, 'r') or die ("Cannot open file"); // open file
    $fileLineCount = count(file($fileName)); // count lines
    // if file is empty
    if ($fileLineCount == 0) {
        echo "Datei '".$file.".log' ist leer <br>";
    } else {
        //echo "TIMESTAMP | LOG-LEVEL | NACHRICHT<br>";
        foreach(file($fileName) as $line){
            echo "$line<br>";
        }
    }
    fclose($fp);
}

function writeLog($level, $message){
    $fileName = $level.".log";
    $fp = fopen($fileName, 'a') or die ("Cannot open file");
    // get current time
    $now = date(DATE_RFC2822, time()); 

    $fileLineCount = count(file($fileName)); // count lines
    // if file is empty
    if ($fileLineCount == 0) {
        fwrite($fp, "TIMESTAMP | LOG-LEVEL | NACHRICHT\n");
    }
    $data = "$now | $level | $message\n";
    fwrite($fp, $data);
    echo "Wurde geloggt <br>";
    fclose($fp);
}

echo "<h2>READ LOGS BEFORE WRITE</h2>";

echo "<h3>Error Log</h3>";
read("error");
echo "<h3>Access Log</h3>";
read("access");
echo "<h3>Debug Log</h3>";
read("debug");
// ------------------------------------------
echo "<h2>WRITE LOGS</h2>";

writeLog("error", "Es gab kein Fehler");
writeLog("access", "Es wurde nicht auf die Datei zugegriffen");
writeLog("debug","Das ka.php wurde gedebugt");
// ------------------------------------------
echo "<h2>READ LOGS AFTER WRITE</h2>";

echo "<h3>Error Log</h3>";
read("error");
echo "<h3>Access Log</h3>";
read("access");
echo "<h3>Debug Log</h3>";
read("debug");
