<?php
require_once 'config.php';

if (!function_exists('auth_logs_table_exists')) {
    function auth_logs_table_exists(mysqli $mysqli): bool {
        $res = $mysqli->query("SHOW TABLES LIKE 'auth_logs'");
        return $res && $res->num_rows > 0;
    }
}

if (!function_exists('client_ip_address')) {
    function client_ip_address(): string {
        $keys = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
        foreach ($keys as $key) {
            if (!empty($_SERVER[$key])) {
                $value = trim(explode(',', (string)$_SERVER[$key])[0]);
                if (filter_var($value, FILTER_VALIDATE_IP)) {
                    return $value;
                }
            }
        }
        return '';
    }
}

if (!function_exists('write_auth_log')) {
    function write_auth_log(mysqli $mysqli, string $eventType, ?int $userId, ?string $username, ?string $details = null): void {
        static $checked = null;
        if ($checked === null) {
            $checked = auth_logs_table_exists($mysqli);
        }
        if (!$checked) return;

        $ip = client_ip_address();
        $userAgent = substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);
        $sessionId = substr(session_id(), 0, 128);

        $stmt = $mysqli->prepare(
            'INSERT INTO auth_logs (event_type, user_id, username_attempted, ip_address, user_agent, session_id, details) VALUES (?, ?, ?, ?, ?, ?, ?)'
        );
        if (!$stmt) return;
        $stmt->bind_param('sisssss', $eventType, $userId, $username, $ip, $userAgent, $sessionId, $details);
        $stmt->execute();
        $stmt->close();
    }
}

$userId = null;
$username = null;
if (!empty($_SESSION['user']['id'])) {
    $userId = (int)$_SESSION['user']['id'];
    $username = (string)($_SESSION['user']['username'] ?? '');
} elseif (!empty($_SESSION['user_id'])) {
    $userId = (int)$_SESSION['user_id'];
    $username = (string)($_SESSION['username'] ?? '');
}

write_auth_log($mysqli, 'logout', $userId, $username ?: null, 'Odjava korisnika');

$_SESSION = [];
if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params['path'],
        $params['domain'],
        $params['secure'],
        $params['httponly']
    );
}
session_destroy();

header('Location: login.php');
exit;
