<?php
declare(strict_types=1);

$configPath = dirname(__DIR__) . '/private/forum-migrate/redirect-config.php';
if (!is_readable($configPath)) {
    $configPath = getenv('HOME') . '/private/forum-migrate/redirect-config.php';
}
if (!is_readable($configPath)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Brak redirect-config.php\n";
    exit;
}

$config = require $configPath;
$base = rtrim((string) $config['flarum_base'], '/');
$fallback = (string) $config['fallback'];

function redirect_permanent(string $url): void
{
    header('Cache-Control: no-cache');
    header('Location: ' . $url, true, 301);
    exit;
}

function pdo_flarum(array $config): PDO
{
    $dsn = sprintf(
        'mysql:host=%s;dbname=%s;charset=utf8mb4',
        $config['db_host'],
        $config['db_name']
    );
    return new PDO($dsn, $config['db_user'], $config['db_pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
}

function handle_viewtopic(PDO $pdo, string $base, string $fallback): void
{
    $t = isset($_GET['t']) ? (int) $_GET['t'] : 0;
    $p = isset($_GET['p']) ? (int) $_GET['p'] : 0;

    if ($p > 0) {
        $st = $pdo->prepare('SELECT discussion_id, number FROM posts WHERE id = ? LIMIT 1');
        $st->execute([$p]);
        $row = $st->fetch();
        if ($row) {
            redirect_permanent($base . '/d/' . (int) $row['discussion_id'] . '/' . (int) $row['number']);
        }
        redirect_permanent($fallback);
    }

    if ($t > 0) {
        $st = $pdo->prepare('SELECT id FROM discussions WHERE id = ? LIMIT 1');
        $st->execute([$t]);
        if ($st->fetch()) {
            redirect_permanent($base . '/d/' . $t);
        }
        redirect_permanent($fallback);
    }

    redirect_permanent($fallback);
}

function handle_viewforum(PDO $pdo, string $base, string $fallback): void
{
    $f = isset($_GET['f']) ? (int) $_GET['f'] : 0;
    if ($f <= 0) {
        redirect_permanent($fallback);
    }
    $st = $pdo->prepare('SELECT slug FROM tags WHERE id = ? LIMIT 1');
    $st->execute([$f]);
    $row = $st->fetch();
    if ($row && $row['slug'] !== '') {
        redirect_permanent($base . '/t/' . rawurlencode($row['slug']));
    }
    redirect_permanent($fallback);
}

function handle_member(PDO $pdo, string $base, string $fallback): void
{
    $u = isset($_GET['u']) ? (int) $_GET['u'] : 0;
    if ($u <= 0) {
        redirect_permanent($fallback);
    }
    $st = $pdo->prepare('SELECT username FROM users WHERE id = ? LIMIT 1');
    $st->execute([$u]);
    $row = $st->fetch();
    if ($row && $row['username'] !== '') {
        redirect_permanent($base . '/u/' . rawurlencode($row['username']));
    }
    redirect_permanent($fallback);
}

try {
    $pdo = pdo_flarum($config);
} catch (Throwable $e) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "DB error\n";
    exit;
}

$script = basename($_SERVER['SCRIPT_NAME'] ?? '');

switch ($script) {
    case 'viewtopic.php':
        handle_viewtopic($pdo, $base, $fallback);
        break;
    case 'viewforum.php':
        handle_viewforum($pdo, $base, $fallback);
        break;
    case 'memberlist.php':
        handle_member($pdo, $base, $fallback);
        break;
    default:
        $mode = $_GET['mode'] ?? '';
        if ($mode === 'topic') {
            handle_viewtopic($pdo, $base, $fallback);
        } elseif ($mode === 'forum') {
            handle_viewforum($pdo, $base, $fallback);
        } elseif ($mode === 'user') {
            handle_member($pdo, $base, $fallback);
        }
        redirect_permanent($fallback);
}
