<?php
// get_log_stats.php
ini_set('display_errors', 0); // In Prod keine Text-Fehler ausgeben
error_reporting(E_ALL);

session_start();
header('Content-Type: application/json');

$debugLogFile = __DIR__ . '/get_log_stats_debug.log';
require_once __DIR__ . '/logging_functions.php';
require_once __DIR__ . '/validation_functions.php';

// --- UID LOGIK: MINIMAL-INVASIV GEÄNDERT ---
// Wir setzen die UID auf 1, falls keine Session existiert (Gast)
$uid = (isset($_SESSION['uid'])) ? (int)$_SESSION['uid'] : 1;

// 1. Türsteher
enforceValidRequest($debugLogFile);

// 2. Config & Tabelle
$config = require __DIR__ . '/config.php';
$logTable = $config['logTable'];

// 4. DB Verbindung
try {
    $db_conf = require __DIR__ . '/db-connection.php';
    
    $pdo = new PDO(
        "pgsql:host={$db_conf['host']};port={$db_conf['port']};dbname={$db_conf['dbname']}",
        $db_conf['user'],
        $db_conf['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // 5. Die Query (UID 1 sieht alles, andere nur ihre eigene UID)
    $whereClause = ($uid === 1) ? "1=1" : "uid = :uid";
    $sql = "
        SELECT 
            COUNT(*) FILTER (WHERE changed_at::date = CURRENT_DATE) as today,
            COUNT(*) FILTER (WHERE date_trunc('month', changed_at) = date_trunc('month', CURRENT_DATE)) as month,
            COUNT(*) FILTER (WHERE date_trunc('year', changed_at) = date_trunc('year', CURRENT_DATE)) as year
        FROM public.{$logTable}
        WHERE $whereClause
    ";

    $stmt = $pdo->prepare($sql);
    if ($uid !== 1) {
        $stmt->bindValue(':uid', $uid, PDO::PARAM_INT);
    }
    $stmt->execute();
    
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);

    // Erfolg: JSON wird IMMER gesendet, auch für Gast
    echo json_encode([
        'success' => true,
        'uid'     => (int)$uid,
        'isAdmin' => ($uid === 1),
        'env'     => $config['env'] ?? 'prod',
        'data'    => [
            'today' => (int)($stats['today'] ?? 0),
            'month' => (int)($stats['month'] ?? 0),
            'year'  => (int)($stats['year'] ?? 0)
        ]
    ]);

} catch (Throwable $e) {
    internal_debug_log("FEHLER: " . $e->getMessage(), $debugLogFile);
    // Im Fehlerfall trotzdem ein sauberes JSON mit der aktuellen UID schicken
    echo json_encode([
        'success' => false, 
        'uid' => (int)$uid, 
        'error' => 'Datenbankfehler'
    ]);
}