<?php
$logFile = 'error-log.txt';
$handle = fopen($logFile, 'a') or die('Cannot open file:  '.$logFile);
$result = array();
$_POST = json_decode(file_get_contents("php://input"), true);
if(isset($_POST['operation']) && $_POST['operation'] == 'write')
{
    $content = date('Y-m-d H:i:s')." ".$_POST['content']."\n";
    
    fwrite($handle, $content);
    $result = array(
        'message' => 'File Successfully write'
    );
}
elseif(isset($_REQUEST['operation']) && $_REQUEST['operation'] == 'download')
{
    $result = array(
        'message' => 'File Successfully download'
    );
    $fileLocation = './'.$logFile;
    echo '<a style="display: none" id="download-file" href="'.$fileLocation.'" download>Download</a>';
    echo '<script type="text/javascript">document.getElementById("download-file").click();</script>';
}
else
{
    $deleteDateReceord = strtotime(date('Y-m-d') . " -5 days");
    $deleteDateReceord = date('Y-m-d', $deleteDateReceord);

    $data = file("./".$logFile);

    $output = array();

    $dataDeleted = 'Nothing find old data for delete';
    foreach($data as $line) 
    {   
        $position = strpos($line, $deleteDateReceord);
        if(is_numeric($position)) 
        {
            $dataDeleted = 'Data successfully deleted on file';
        }
        else
        {
            $output[] = $line;
        }
    }

    $fp = fopen("./".$logFile, "w+");
    flock($fp, LOCK_EX);
    foreach($output as $line) 
    {
        fwrite($fp, $line);
    }
    flock($fp, LOCK_UN);
    fclose($fp);  

    $result = array(
        'message' => $dataDeleted
    );
}
echo json_encode($result);
 