<?php
require_once './sys/db.php';

if ($mysqli->connect_error) {
    die('Ошибка подключения к базе данных: ' . $mysqli->connect_error);
}

$query = "SELECT `url`, `name` 
          FROM `reklama` 
          WHERE `expire` > NOW() AND `status` = '1'
          ORDER BY RAND() 
          LIMIT 5";

$stmt = $mysqli->prepare($query);
if (!$stmt) {
    die('Ошибка подготовки запроса: ' . $mysqli->error);
}

$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    echo '<div class="seo-ads-container" itemscope itemtype="https://schema.org/ItemList">';
    
    $position = 1;
    while ($link = $result->fetch_assoc()) {
        $url = htmlspecialchars($link['url'], ENT_QUOTES, 'UTF-8');
        $name = htmlspecialchars($link['name'], ENT_QUOTES, 'UTF-8');
        $description = $name;
        
        echo <<<HTML
        <div class="seo-ad-item" itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
            <meta itemprop="position" content="{$position}">
            <div itemscope itemtype="https://schema.org/Organization">
                <a href="{$url}" 
                   rel="nofollow sponsored" 
                   itemprop="url" 
                   title="{$name}" 
                   class="seo-ad-link">
                    <span itemprop="name">{$name}</span>
                </a>
                <p itemprop="description" class="seo-ad-desc" style="display:none;">{$description}</p>
            </div>
        </div>
HTML;
        $position++;
    }
    echo '</div>';
} else {
    echo '<div class="seo-no-ads"><span>Нет активных рекламных предложений</span></div>';
}

$stmt->close();
$mysqli->close();