<?php
declare(strict_types=1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$title = 'Блог';
require_once 'sys/sys.php';
require_once 'sys/db.php';

echo '<!DOCTYPE html>
<html lang="ru" itemscope itemtype="http://schema.org/WebPage">
<head>
    <meta charset="UTF-8">
    <meta name="description" content="Последние записи в блоге на ' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_QUOTES, 'UTF-8') . '">
    <link rel="canonical" href="https://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_QUOTES, 'UTF-8') . htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, 'UTF-8') . '">
    <meta name="robots" content="index, follow">';

require_once 'sys/head.php';

function parseBBCode(string $text): string {
    $patterns = [
        '/\[b\](.*?)\[\/b\]/is' => '<strong>$1</strong>',
        '/\[i\](.*?)\[\/i\]/is' => '<em>$1</em>',
        '/\[u\](.*?)\[\/u\]/is' => '<u>$1</u>',
        '/\[s\](.*?)\[\/s\]/is' => '<s>$1</s>',
        '/\[sup\](.*?)\[\/sup\]/is' => '<sup>$1</sup>',
        '/\[sub\](.*?)\[\/sub\]/is' => '<sub>$1</sub>',
        '/\[url=(.*?)\](.*?)\[\/url\]/is' => '<a href="$1" target="_blank" rel="nofollow noopener noreferrer">$2</a>',
        '/\[url\](.*?)\[\/url\]/is' => '<a href="$1" target="_blank" rel="nofollow noopener noreferrer">$1</a>',
        '/\[img\](.*?)\[\/img\]/is' => '<img src="$1" alt="" class="img-fluid bb-img">',
        '/\[img=(.*?)x(.*?)\](.*?)\[\/img\]/is' => '<img src="$3" width="$1" height="$2" alt="" class="img-fluid bb-img">',
        '/\[color=(.*?)\](.*?)\[\/color\]/is' => '<span style="color:$1">$2</span>',
        '/\[size=(\d+)\](.*?)\[\/size\]/is' => '<span style="font-size:$1px">$2</span>',
        '/\[font=(.*?)\](.*?)\[\/font\]/is' => '<span style="font-family:$1">$2</span>',
        '/\[highlight\](.*?)\[\/highlight\]/is' => '<span class="bb-highlight">$1</span>',
        '/\[quote\](.*?)\[\/quote\]/is' => '<blockquote class="bb-quote">$1</blockquote>',
        '/\[quote=(.*?)\](.*?)\[\/quote\]/is' => '<blockquote class="bb-quote"><cite>$1</cite>$2</blockquote>',
        '/\[code\](.*?)\[\/code\]/is' => '<pre class="bb-code"><code>$1</code></pre>',
        '/\[code=(.*?)\](.*?)\[\/code\]/is' => '<pre class="bb-code"><code class="language-$1">$2</code></pre>',
        '/\[list\](.*?)\[\/list\]/is' => '<ul class="bb-list">$1</ul>',
        '/\[list=1\](.*?)\[\/list\]/is' => '<ol class="bb-list">$1</ol>',
        '/\[\*\](.*?)(\n|$)/is' => '<li>$1</li>',
        '/\[center\](.*?)\[\/center\]/is' => '<div style="text-align:center">$1</div>',
        '/\[right\](.*?)\[\/right\]/is' => '<div style="text-align:right">$1</div>',
        '/\[left\](.*?)\[\/left\]/is' => '<div style="text-align:left">$1</div>',
        '/\[justify\](.*?)\[\/justify\]/is' => '<div style="text-align:justify">$1</div>',
        '/\[youtube\](.*?)\[\/youtube\]/is' => '<div class="bb-video-container"><iframe src="https://www.youtube.com/embed/$1" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen class="bb-video" loading="lazy" title="YouTube видео"></iframe></div>',
        '/\[video\](.*?)\[\/video\]/is' => '<div class="bb-video-container"><video src="$1" controls class="bb-video" loading="lazy"></video></div>',
        '/\[audio\](.*?)\[\/audio\]/is' => '<div class="bb-audio-container"><audio src="$1" controls class="bb-audio"></audio></div>',
        '/\[table\](.*?)\[\/table\]/is' => '<table class="bb-table">$1</table>',
        '/\[tr\](.*?)\[\/tr\]/is' => '<tr>$1</tr>',
        '/\[td\](.*?)\[\/td\]/is' => '<td>$1</td>',
        '/\[th\](.*?)\[\/th\]/is' => '<th>$1</th>',
        '/\[spoiler\](.*?)\[\/spoiler\]/is' => '<div class="bb-spoiler"><button class="bb-spoiler-btn" onclick="toggleSpoiler(this)">Спойлер ▼</button><div class="bb-spoiler-content">$1</div></div>',
        '/\[spoiler=(.*?)\](.*?)\[\/spoiler\]/is' => '<div class="bb-spoiler"><button class="bb-spoiler-btn" onclick="toggleSpoiler(this)">$1 ▼</button><div class="bb-spoiler-content">$2</div></div>',
        '/\[accordion=(.*?)\](.*?)\[\/accordion\]/is' => '<div class="bb-accordion"><button class="bb-accordion-btn" onclick="toggleAccordion(this)">$1 ▼</button><div class="bb-accordion-content">$2</div></div>',
        '/\[hr\]/is' => '<hr class="bb-hr">',
        '/\[br\]/is' => '<br>',
        '/\[pagebreak\]/is' => '<div class="bb-pagebreak"></div>',
        '/\[tag\](.*?)\[\/tag\]/is' => '<span class="badge badge-info mr-1 mb-1">$1</span>'
    ];
    
    $text = htmlspecialchars($text);
    
    foreach ($patterns as $pattern => $replacement) {
        $text = preg_replace($pattern, $replacement, $text);
    }
    
    $text = nl2br($text);
    $blockElements = ['table', 'tr', 'td', 'th', 'ul', 'ol', 'li', 'blockquote', 'pre', 'div', 'hr'];
    foreach ($blockElements as $tag) {
        $text = preg_replace('/<br\s?\/?>\s*<(\\/' . $tag . '|' . $tag . ')/i', '<$1', $text);
    }
    
    return $text;
}

$max = 5;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$countQuery = $pdo->query('SELECT COUNT(*) FROM `blog` WHERE `published` = 1');
$totalPosts = $countQuery->fetchColumn();
$pages = ceil($totalPosts / $max);

if ($page < 1) $page = 1;
if ($pages > 0 && $page > $pages) $page = $pages;

$start = ($page - 1) * $max;
$posts = [];

if ($totalPosts > 0) {
    $sql = "SELECT * FROM `blog` WHERE `published` = 1 ORDER BY `created_at` DESC LIMIT :limit OFFSET :offset";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':limit', $max, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $start, PDO::PARAM_INT);
    $stmt->execute();
    $posts = $stmt->fetchAll();
}

echo '<div class="bg-index"><br/>
    <div class="title-page">
        <h2 style="color: #fff;">Блог</h2>
    </div>
    <div class="container">
        <center>
            <p class="text-light" style="position: relative; z-index: 99; font-size: 120%;">
                Последние записи в блоге <b>' . htmlspecialchars($_SERVER['HTTP_HOST']) . '</b>
            </p>
        </center>
    </div><br/>
</div><br/>';

if (!empty($posts)) {
    echo '<div class="container">
        <div class="row" itemscope itemtype="https://schema.org/ItemList">
            <div class="col-md-12">';

    $position = 1;
    foreach ($posts as $post) {
        $tagsHtml = '';
        if (!empty($post['tags'])) {
            $tags = explode(',', $post['tags']);
            $tagsHtml = '<div class="mb-2"><small class="text-muted"></i> Теги: ';
            $tagLinks = [];
            foreach ($tags as $tag) {
                $tag = trim($tag);
                if (!empty($tag)) {
                    $tagLinks[] = '<span class="badge badge-info">' . htmlspecialchars($tag) . '</span>';
                }
            }
            $tagsHtml .= implode(' ', $tagLinks) . '</small></div>';
        }
        
        echo '<div class="card mb-4" itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
                <meta itemprop="position" content="' . $position . '" />
                <div class="card-body" itemscope itemtype="https://schema.org/BlogPosting">
                    <h3 class="card-title" itemprop="headline">' . htmlspecialchars($post['title']) . '</h3>
                    <div class="card-text bb-content" itemprop="articleBody">' . parseBBCode($post['content']) . '</div>
                    ' . $tagsHtml . '
                    <div class="text-muted small mt-2" itemprop="datePublished" content="' . date('c', strtotime($post['created_at'])) . '">
                         Опубликовано: ' . htmlspecialchars($post['created_at']) . '
                    </div>
                </div>
              </div>';
        $position++;
    }

    echo '</div></div></div>';
    
    if ($totalPosts > 0) {
        echo '<div class="container mt-4">
                <div class="row">
                    <div class="col-md-12 text-center">
                        <nav aria-label="Page navigation">
                            <ul class="pagination justify-content-center">';
        
        if ($page > 1) {
            echo '<li class="page-item"><a class="page-link" href="/blog?page='.($page-1).'" rel="prev">&laquo;</a></li>';
        } else {
            echo '<li class="page-item disabled"><span class="page-link">&laquo;</span></li>';
        }
        
        for ($i = 1; $i <= $pages; $i++) {
            if ($i == $page) {
                echo '<li class="page-item active"><span class="page-link">'.$i.'</span></li>';
            } else {
                echo '<li class="page-item"><a class="page-link" href="/blog?page='.$i.'" rel="nofollow">'.$i.'</a></li>';
            }
        }
        
        if ($page < $pages) {
            echo '<li class="page-item"><a class="page-link" href="/blog?page='.($page+1).'" rel="next">&raquo;</a></li>';
        } else {
            echo '<li class="page-item disabled"><span class="page-link">&raquo;</span></li>';
        }
        
        echo '</ul>
                        </nav>
                    </div>
                </div>
            </div>';
    }
} else {
    echo '<div class="container">
        <div class="alert alert-info">
            <i class="fas fa-info-circle"></i> В блоге пока нет опубликованных записей. Зайдите позже!
        </div>
    </div>';
}

echo '<script>
function toggleSpoiler(btn) {
    const content = btn.nextElementSibling;
    content.style.display = content.style.display === "none" ? "block" : "none";
    btn.innerHTML = btn.innerHTML.includes("▲") ? btn.innerHTML.replace("▲", "▼") : btn.innerHTML.replace("▼", "▲");
}

function toggleAccordion(btn) {
    const content = btn.nextElementSibling;
    content.style.display = content.style.display === "none" ? "block" : "none";
    btn.innerHTML = btn.innerHTML.includes("▲") ? btn.innerHTML.replace("▲", "▼") : btn.innerHTML.replace("▼", "▲");
}

document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll(".bb-spoiler-content").forEach(el => {
        el.style.display = "none";
    });
    document.querySelectorAll(".bb-accordion-content").forEach(el => {
        el.style.display = "none";
    });
});
</script>';

require_once 'sys/foot.php';