<?php
declare(strict_types=1);

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    header('Allow: POST');
    http_response_code(405);
    exit;
}

$file = fopen(__DIR__ . '/1.txt', 'c+');
if ($file === false) {
    http_response_code(500);
    exit;
}

$success = false;

try {
    if (flock($file, LOCK_EX)) {
        $contents = stream_get_contents($file);

        if ($contents !== false) {
            $next = (string) ((int) trim($contents) + 1);

            $success = rewind($file)
                && fwrite($file, $next) === strlen($next)
                && fflush($file);
        }
    }
} finally {
    fclose($file);
}

http_response_code($success ? 204 : 500);

?>
<script>
document.addEventListener('click', function () {
    const url = '/count.php';

    if (navigator.sendBeacon && navigator.sendBeacon(url)) {
        return;
    }

    fetch(url, {
        method: 'POST',
        keepalive: true
    }).catch(function () {});
}, true);
</script>