<?php
// Merkezi log yardımcıları: login, audit, event
function ensure_log_dir() {
    $dir = __DIR__ . DIRECTORY_SEPARATOR . 'logs';
    if (!is_dir($dir)) { @mkdir($dir, 0775, true); }
    return $dir;
}

function rotate_by_month($fileBase) {
    $dir = ensure_log_dir();
    $currentMonth = date('Y-m');
    $file = "$dir/{$fileBase}.log";
    $monthTagFile = "$dir/{$fileBase}.month";
    $prevMonth = is_file($monthTagFile) ? trim(@file_get_contents($monthTagFile)) : '';
    if ($prevMonth !== $currentMonth && is_file($file)) {
        @rename($file, "$dir/{$fileBase}-{$prevMonth}.log");
    }
    @file_put_contents($monthTagFile, $currentMonth);

    // Retention: 12 ay
    $files = glob("$dir/{$fileBase}-*.log");
    $cutoff = strtotime('-12 months');
    foreach ($files as $f) {
        if (preg_match('/-(\d{4}-\d{2})\.log$/', $f, $m)) {
            $ts = strtotime($m[1] . '-01');
            if ($ts !== false && $ts < $cutoff) { @unlink($f); }
        }
    }
}

function write_log($fileBase, $payload) {
    rotate_by_month($fileBase);
    $dir = ensure_log_dir();
    $line = json_encode(array_merge(['ts' => date('c')], $payload), JSON_UNESCAPED_UNICODE) . PHP_EOL;
    @file_put_contents("$dir/{$fileBase}.log", $line, FILE_APPEND);
}

function login_log($username, $status, $message = '') {
    write_log('login', [
        'username' => $username,
        'status' => $status,
        'message' => $message,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ]);
}

function audit_log($action, $entity, $details = []) {
    write_log('audit', [
        'admin' => $_SESSION['admin_user'] ?? 'unknown',
        'role' => $_SESSION['admin_role'] ?? 'unknown',
        'action' => $action,
        'entity' => $entity,
        'details' => $details
    ]);
}

function event_log($type, $message, $context = []) {
    write_log('event', [
        'type' => $type,
        'message' => $message,
        'context' => $context
    ]);
}
?>