<html>
<body>
<form action="" method="GET" enctype="multipart/form-data">
  <input type="file" name="in" onchange="this.form.submit();">
</form>
<button onclick="downloadFile()">Get CSV</button>

<?php
if (isset($_GET["in"])) {
    $File = $_GET["in"];
    
    function format($filePath) {
        $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $data = implode("\n", $lines);
        $data = preg_replace('/\s+/', ' ', $data);
        $data = str_replace(':D;;', "\n:D;;", $data);
        $data = trim($data);
        file_put_contents($filePath, $data);
    }
    format($File);

    $pattern = "/:D;;\d{3};(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})(\d{2})\s(?:([A-Z-0-9]*):\s?)".
                "?([A-z-.=_0-9]*)\s?((?:D[0-9]|CPU|AP|PB|CP|XP|FORCE|MAX|PUSH|V4|Im[0-9])[A-z-.=_0-9\/]*|)\s?([A-Z.=_0-9-\s]*)?\s/";
	$rows = "<th>Datums</th><th>Laiks</th><th>Kods</th><th>Kļūda</th><th>Iekārta</th><th>Status</th><th>Objekts</th>";
    $fileContent = "Datums;Laiks;Kludas kods;Kluda;Iekarta;Status;Objekts\n";

    if (preg_match_all($pattern, file_get_contents($File), $X)) {
        echo "<table border='1'><tr>".$rows."</tr>";
        foreach ($X[0] as $Y => $match) { 
            $last = "";
            if (strpos($X[9][$Y],'V4')!==false) {
				if (strlen($X[9][$Y]) >= 4) {
					$last = substr($X[9][$Y], 3, 1);
					$X[9][$Y]=substr($X[9][$Y],0,2).substr($X[9][$Y],4);
				}
			}
            echo"<tr><td>{$X[3][$Y]}.{$X[2][$Y]}.{$X[1][$Y]}</td><td>{$X[4][$Y]}:{$X[5][$Y]}:{$X[6][$Y]}</td><td>{$X[7][$Y]}</td><td>{$X[8][$Y]}</td><td>{$X[9][$Y]}</td><td>{$X[10][$Y]}</td><td>{$last}</td></tr>";
			$fileContent .= "{$X[3][$Y]}-{$X[2][$Y]}-{$X[1][$Y]};{$X[4][$Y]}:{$X[5][$Y]}:{$X[6][$Y]};{$X[7][$Y]};{$X[8][$Y]};{$X[9][$Y]};{$X[10][$Y]};{$last}\n";
        } 
		echo "</table>";
    }

    echo "
    <script>
    function downloadFile() {
        var fileContent = " . json_encode($fileContent) . ";
        var blob = new Blob([fileContent],{type:'text/csv'});
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'output.csv';
        link.click();
    }
    </script>
    ";

	$nonMatchingText=preg_replace($pattern,'',file_get_contents($File)); 
	if(!empty($nonMatchingText)){echo"<pre>Text that doesn't match the regex:\n$nonMatchingText</pre>";}}else{echo"<p>Please upload a file to process.</p>";
}
?>
</body>
</html>



