<?php
/*
Plugin Name: Codex SEO Bootstrap
Description: Site-specific SEO bootstrap generated by Codex.
*/
if (!defined('ABSPATH')) {
    exit;
}

function codex_seo_config() {
    static $config = null;
    if ($config === null) {
        $config = json_decode(<<<'JSON'
{
    "site_name": "Весенний Релиз",
    "home_title": "Весенний Релиз — CMS под PHP",
    "home_description": "Весенний Релиз — CMS под PHP с опубликованными сведениями о релизах, документацией и лицензией проекта.",
    "home_h1": "",
    "maintenance": false,
    "noindex_home": false,
    "publisher_name": "Весенний Релиз",
    "domain": "spring-wars.ru"
}
JSON
        , true);
    }
    return $config;
}

function codex_seo_is_home_request() {
    return is_front_page() || is_home();
}

function codex_seo_plain_text($value) {
    $value = wp_strip_all_tags((string) $value);
    $value = preg_replace('/\s+/u', ' ', $value);
    return trim((string) $value);
}

function codex_seo_description() {
    $config = codex_seo_config();
    if (codex_seo_is_home_request()) {
        return $config['home_description'];
    }
    if (is_singular()) {
        $post = get_queried_object();
        if ($post instanceof WP_Post) {
            $excerpt = has_excerpt($post) ? get_the_excerpt($post) : wp_trim_words(codex_seo_plain_text($post->post_content), 30, '');
            if ($excerpt) {
                return codex_seo_plain_text($excerpt);
            }
        }
    }
    if (is_category() || is_tag() || is_tax()) {
        $term = get_queried_object();
        if ($term && !empty($term->description)) {
            return codex_seo_plain_text($term->description);
        }
    }
    return $config['home_description'];
}

function codex_seo_canonical_url() {
    if (codex_seo_is_home_request()) {
        return home_url('/');
    }
    if (is_singular()) {
        return get_permalink();
    }
    if (is_category() || is_tag() || is_tax()) {
        $term = get_queried_object();
        $link = $term ? get_term_link($term) : '';
        if (!is_wp_error($link) && $link) {
            return $link;
        }
    }
    if (is_post_type_archive()) {
        $post_type = get_query_var('post_type');
        if (is_array($post_type)) {
            $post_type = reset($post_type);
        }
        $link = $post_type ? get_post_type_archive_link($post_type) : '';
        if ($link) {
            return $link;
        }
    }
    global $wp;
    $request = isset($wp->request) ? $wp->request : '';
    if ($request) {
        return home_url('/' . ltrim($request, '/'));
    }
    return home_url('/');
}

function codex_seo_og_image() {
    if (is_singular() && has_post_thumbnail()) {
        $img = get_the_post_thumbnail_url(get_queried_object_id(), 'full');
        if ($img) {
            return $img;
        }
    }
    return home_url('/og-image.png');
}

add_action('after_setup_theme', function () {
    remove_action('wp_head', 'rel_canonical');
    remove_action('wp_head', 'wp_generator');
    remove_action('wp_head', 'rsd_link');
    remove_action('wp_head', 'wlwmanifest_link');
});

add_filter('the_generator', '__return_empty_string');

add_filter('pre_get_document_title', function ($title) {
    $config = codex_seo_config();
    if (codex_seo_is_home_request()) {
        return $config['home_title'];
    }
    return $title;
});

add_filter('wp_robots', function ($robots) {
    $config = codex_seo_config();
    if (!is_array($robots)) {
        $robots = array();
    }
    if ($config['maintenance']) {
        return array('noindex' => true, 'nofollow' => true, 'noarchive' => true);
    }
    if ($config['noindex_home'] && codex_seo_is_home_request()) {
        return array('noindex' => true, 'nofollow' => true, 'max-image-preview' => 'large');
    }
    $robots['max-image-preview'] = 'large';
    return $robots;
});

function codex_seo_inject_home_h1($html) {
    $config = codex_seo_config();
    $text = trim((string) $config['home_h1']);
    if ($text === '' || stripos($html, 'codex-seo-home-h1') !== false || stripos($html, '<h1') !== false) {
        return $html;
    }
    $h1 = '<h1 class="codex-seo-home-h1" style="margin:0 0 1.5rem;font-size:clamp(2rem,4vw,3rem);line-height:1.1;">' . esc_html($text) . '</h1>';
    $updated = preg_replace('/(<main\b[^>]*>)/i', '$1' . $h1, $html, 1);
    if ($updated !== null && $updated !== $html) {
        return $updated;
    }
    $updated = preg_replace('/(<body\b[^>]*>)/i', '$1' . $h1, $html, 1);
    return $updated !== null ? $updated : $html;
}

function codex_seo_render_maintenance_page() {
    $config = codex_seo_config();
    status_header(503);
    header('Retry-After: 86400', true);
    header('X-Robots-Tag: noindex, nofollow, noarchive', true);
    nocache_headers();
    $title = esc_html($config['home_title']);
    $description = esc_html($config['home_description']);
    $url = esc_url(home_url('/'));
    $favicon = esc_url(home_url('/favicon.ico'));
    $image = esc_url(home_url('/og-image.png'));
    $json = wp_json_encode(array(
        '@context' => 'https://schema.org',
        '@type' => 'WebSite',
        'name' => $config['site_name'],
        'url' => home_url('/'),
        'inLanguage' => 'ru-RU',
        'description' => $config['home_description'],
    ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    echo '<!DOCTYPE html><html lang="ru-RU"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>' . $title . '</title><meta name="description" content="' . $description . '"><meta name="robots" content="noindex,nofollow,noarchive"><link rel="canonical" href="' . $url . '"><meta property="og:locale" content="ru_RU"><meta property="og:type" content="website"><meta property="og:title" content="' . $title . '"><meta property="og:description" content="' . $description . '"><meta property="og:url" content="' . $url . '"><meta property="og:image" content="' . $image . '"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' . $title . '"><meta name="twitter:description" content="' . $description . '"><meta name="twitter:image" content="' . $image . '"><link rel="icon" href="' . $favicon . '"><script type="application/ld+json">' . $json . '</script><style>body{margin:0;font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#0f172a;color:#e2e8f0;display:grid;place-items:center;min-height:100vh;padding:24px}main{max-width:720px;background:rgba(15,23,42,.72);border:1px solid rgba(148,163,184,.2);border-radius:20px;padding:40px;box-shadow:0 30px 80px rgba(2,6,23,.35)}h1{margin:0 0 16px;font-size:clamp(2rem,4vw,3rem)}p{margin:0;font-size:1.05rem;line-height:1.7;color:#cbd5e1}</style></head><body><main><h1>Идут технические работы</h1><p>Сайт временно недоступен. Мы проводим технические работы и скоро вернемся.</p></main></body></html>';
    exit;
}

add_action('template_redirect', function () {
    $config = codex_seo_config();
    $path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
    if ($config['maintenance']) {
        if (!is_user_logged_in() && !preg_match('#^/(wp-login\.php|wp-admin(?:/.*)?|robots\.txt|sitemap\.xml|favicon(?:-[0-9x]+)?\.png|favicon\.ico|favicon\.svg|apple-touch-icon\.png|site\.webmanifest|og-image\.png|wp-json(?:/.*)?|xmlrpc\.php)$#', $path)) {
            codex_seo_render_maintenance_page();
        }
    }
    if ($config['noindex_home'] && codex_seo_is_home_request()) {
        header('X-Robots-Tag: noindex, nofollow', true);
    }
    if (!empty($config['home_h1']) && codex_seo_is_home_request() && !is_paged()) {
        ob_start('codex_seo_inject_home_h1');
    }
});

add_action('wp_head', function () {
    $config = codex_seo_config();
    $title = wp_get_document_title();
    $description = codex_seo_description();
    $canonical = codex_seo_canonical_url();
    $ogImage = codex_seo_og_image();
    $ogType = is_singular('post') ? 'article' : 'website';
    echo "\n<link rel=\"canonical\" href=\"" . esc_url($canonical) . "\">\n";
    echo '<meta name="description" content="' . esc_attr($description) . '">' . "\n";
    echo '<meta property="og:locale" content="ru_RU">' . "\n";
    echo '<meta property="og:type" content="' . esc_attr($ogType) . '">' . "\n";
    echo '<meta property="og:title" content="' . esc_attr($title) . '">' . "\n";
    echo '<meta property="og:description" content="' . esc_attr($description) . '">' . "\n";
    echo '<meta property="og:url" content="' . esc_url($canonical) . '">' . "\n";
    echo '<meta property="og:image" content="' . esc_url($ogImage) . '">' . "\n";
    echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
    echo '<meta name="twitter:title" content="' . esc_attr($title) . '">' . "\n";
    echo '<meta name="twitter:description" content="' . esc_attr($description) . '">' . "\n";
    echo '<meta name="twitter:image" content="' . esc_url($ogImage) . '">' . "\n";
    echo '<link rel="icon" href="' . esc_url(home_url('/favicon.ico')) . '">' . "\n";
    echo '<link rel="apple-touch-icon" href="' . esc_url(home_url('/apple-touch-icon.png')) . '">' . "\n";
    if (codex_seo_is_home_request()) {
        $schema = array(
            '@context' => 'https://schema.org',
            '@type' => 'WebSite',
            'name' => $config['site_name'],
            'url' => home_url('/'),
            'inLanguage' => 'ru-RU',
            'description' => $config['home_description'],
        );
        echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '</script>' . "\n";
    }
    if (is_singular('post')) {
        $article = array(
            '@context' => 'https://schema.org',
            '@type' => 'Article',
            'headline' => $title,
            'description' => $description,
            'datePublished' => get_the_date('c'),
            'dateModified' => get_the_modified_date('c'),
            'mainEntityOfPage' => $canonical,
            'image' => array($ogImage),
            'publisher' => array(
                '@type' => 'Organization',
                'name' => $config['publisher_name'],
                'logo' => array(
                    '@type' => 'ImageObject',
                    'url' => home_url('/og-image.png'),
                ),
            ),
        );
        echo '<script type="application/ld+json">' . wp_json_encode($article, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '</script>' . "\n";
    }
}, 1);
