<?php
declare(strict_types=1);

if (defined('VM_SEO_RUNTIME_LOADED')) {
    return;
}
define('VM_SEO_RUNTIME_LOADED', true);

function seo_rt_db(): ?PDO
{
    try {
        if (function_exists('db')) return db();
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) return $GLOBALS['pdo'];
    } catch (Throwable $e) {
    }
    return null;
}

function seo_rt_ident_ok(string $name): bool
{
    return (bool)preg_match('/^[a-zA-Z0-9_]+$/', $name);
}

function seo_rt_table_exists(PDO $pdo, string $table): bool
{
    static $cache = [];
    if (!seo_rt_ident_ok($table)) return false;
    if (array_key_exists($table, $cache)) return (bool)$cache[$table];

    if (function_exists('db_has_table')) {
        try {
            $cache[$table] = (bool)db_has_table($pdo, $table);
            return (bool)$cache[$table];
        } catch (Throwable $e) {
        }
    }

    try {
        $st = $pdo->prepare('SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ? LIMIT 1');
        $st->execute([$table]);
        $cache[$table] = (bool)$st->fetchColumn();
    } catch (Throwable $e) {
        $cache[$table] = false;
    }

    return (bool)$cache[$table];
}

function seo_rt_load_settings(PDO $pdo): array
{
    static $settings = null;
    if (is_array($settings)) return $settings;

    $defaults = [
        'seo_enabled' => '1',
        'seo_enable_canonical' => '1',
        'seo_enable_og' => '1',
        'seo_enable_twitter' => '1',
        'seo_enable_hreflang' => '1',
        'seo_enable_schema' => '1',
        'seo_default_title' => 'VMEREGI',
        'seo_title_suffix' => '— VMEREGI',
        'seo_default_description' => 'Соціальна мережа VMEREGI.',
        'seo_default_og_image' => '',
    ];

    if (!seo_rt_table_exists($pdo, 'app_settings')) {
        $settings = $defaults;
        return $settings;
    }

    try {
        $keys = array_keys($defaults);
        $in = implode(',', array_fill(0, count($keys), '?'));
        $st = $pdo->prepare("SELECT key_name, value_text FROM app_settings WHERE key_name IN ($in)");
        $st->execute($keys);
        $settings = $defaults;
        foreach (($st->fetchAll(PDO::FETCH_ASSOC) ?: []) as $row) {
            $k = (string)($row['key_name'] ?? '');
            if ($k !== '' && array_key_exists($k, $settings)) {
                $settings[$k] = (string)($row['value_text'] ?? '');
            }
        }
    } catch (Throwable $e) {
        $settings = $defaults;
    }

    return $settings;
}

function seo_rt_get_page_override(PDO $pdo, string $path): ?array
{
    if (!seo_rt_table_exists($pdo, 'seo_pages')) return null;

    $path = '/' . ltrim(strtok($path, '?') ?: '/', '/');

    try {
        $st = $pdo->prepare('SELECT * FROM seo_pages WHERE is_active = 1 AND page_path = ? LIMIT 1');
        $st->execute([$path]);
        $row = $st->fetch(PDO::FETCH_ASSOC);
        return is_array($row) ? $row : null;
    } catch (Throwable $e) {
        return null;
    }
}

function seo_rt_apply_redirect(PDO $pdo): void
{
    if (!seo_rt_table_exists($pdo, 'seo_redirects')) return;
    if (PHP_SAPI === 'cli') return;

    $uri = (string)($_SERVER['REQUEST_URI'] ?? '/');
    $path = '/' . ltrim(strtok($uri, '?') ?: '/', '/');

    if (str_starts_with($path, '/admin/')) return;

    try {
        $st = $pdo->prepare('SELECT * FROM seo_redirects WHERE is_active = 1 AND old_path = ? LIMIT 1');
        $st->execute([$path]);
        $row = $st->fetch(PDO::FETCH_ASSOC);
        if (!is_array($row)) return;

        $target = trim((string)($row['target_url'] ?? ''));
        if ($target === '') return;

        $code = (int)($row['http_code'] ?? 301);
        if (!in_array($code, [301, 302], true)) $code = 301;

        try {
            $up = $pdo->prepare('UPDATE seo_redirects SET hit_count = hit_count + 1, last_hit_at = NOW() WHERE id = ?');
            $up->execute([(int)$row['id']]);
        } catch (Throwable $e) {
        }

        header('Location: ' . $target, true, $code);
        exit;
    } catch (Throwable $e) {
        return;
    }
}

function seo_rt_boot(): void
{
    $pdo = seo_rt_db();
    if (!$pdo) return;
    seo_rt_apply_redirect($pdo);
}
