<?php
/**
 * Besucherzähler API für SPA-Landing
 * Zählt Unique Visitors (Session-basiert) und Page Views (jeden Aufruf)
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$visitorsFile = __DIR__ . '/visitors.txt';
$pageviewsFile = __DIR__ . '/pageviews.txt';

// Zähler lesen oder initialisieren
$visitors = file_exists($visitorsFile) ? (int) file_get_contents($visitorsFile) : 0;
$pageviews = file_exists($pageviewsFile) ? (int) file_get_contents($pageviewsFile) : 0;

// Page Views immer erhöhen
$pageviews++;
file_put_contents($pageviewsFile, $pageviews);

// Session starten für Unique Visitors
session_start();

// Unique Visitors nur bei neuer Session zählen
if (!isset($_SESSION['spa_counted'])) {
    $visitors++;
    file_put_contents($visitorsFile, $visitors);
    $_SESSION['spa_counted'] = true;
}

// JSON-Antwort
echo json_encode([
    'visitors' => $visitors,
    'visitors_formatted' => number_format($visitors, 0, ',', '.'),
    'pageviews' => $pageviews,
    'pageviews_formatted' => number_format($pageviews, 0, ',', '.')
]);
