<?php
/**
 * Detail produktu s price comparison
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/seo.php';
require_once __DIR__ . '/../includes/relations.php';

$slug = $_GET['slug'] ?? '';

// Produkt
$product = db()->queryOne("SELECT * FROM products WHERE slug = ? AND visible = 1", [$slug]);

if (!$product) {
    include __DIR__ . '/404.php';
    exit;
}

// Zvýšit počet zobrazení
db()->query("UPDATE products SET view_count = view_count + 1, last_viewed_at = NOW() WHERE id = ?", [$product['id']]);

// Nabídky (ceny z eshopů) — nejprve ty, které jsou na sklad, pak ostatní
$offers = db()->query(
    "SELECT po.*, f.name as feed_name
     FROM product_offers po
     JOIN feeds f ON po.feed_id = f.id
     WHERE po.product_id = ?
     ORDER BY po.in_stock DESC, po.price_vat ASC",
    [$product['id']]
);

// Kolik je na sklad?
$inStockOffers = array_filter($offers ?: [], fn($o) => $o['in_stock']);

// Recenze produktu
$review = RelationManager::getProductReview($product['id']);

// Srovnávací články
$comparisons = RelationManager::getProductComparisons($product['id']);

// Parametry
$parameters = json_decode($product['parameters'], true) ?? [];
$images = json_decode($product['images'], true) ?? [];

// Všechny kategorie produktu (primární + dodatečné)
$productCategories = [];
if ($product['category_id']) {
    $catRow = db()->queryOne("SELECT id, slug, name FROM categories WHERE id = ? AND visible = 1", [$product['category_id']]);
    if ($catRow) {
        $productCategories[$catRow['id']] = $catRow;
    }
}
$extraCats = db()->query(
    "SELECT c.id, c.slug, c.name FROM product_categories pc
     JOIN categories c ON c.id = pc.category_id AND c.visible = 1
     WHERE pc.product_id = ?",
    [$product['id']]
) ?: [];
foreach ($extraCats as $ec) {
    $productCategories[$ec['id']] = $ec;
}

// Parametry z product_parameter_values
$ppvRows = db()->query(
    "SELECT DISTINCT ppv.param_slug, ppv.value_slug, ppv.param_name, ppv.param_value
     FROM product_parameter_values ppv
     WHERE ppv.product_id = ?",
    [$product['id']]
) ?: [];

// SEO linky — doplňkové informace pro interní prolinkování
$seoLinks = [];

// 1. Kategorie
if (!empty($productCategories)) {
    $seoLinks[] = [
        'label' => t('categories'),
        'links' => array_values(array_map(fn($c) => ['text' => applyShortcodes($c['name']), 'url' => urlKategorie($c['slug'])], $productCategories)),
    ];
}

// 2. Výrobce v kategoriích
if ($product['manufacturer']) {
    $mfrSlug = generateSlug($product['manufacturer']);
    $mfrLinks = [];
    foreach ($productCategories as $cat) {
        $mfrLinks[] = ['text' => $product['manufacturer'] . ' — ' . applyShortcodes($cat['name']), 'url' => urlKategorie($cat['slug']) . '/' . t('url_brand') . '-' . $mfrSlug];
    }
    $seoLinks[] = ['label' => t('manufacturer_label') . ' ' . $product['manufacturer'], 'links' => $mfrLinks];
}

// 3. Parametry (jen smysluplné — přeskočit numerické a příliš dlouhé hodnoty)
foreach ($ppvRows as $ppv) {
    if (preg_match('/^\d+([.,]\d+)?$/', $ppv['param_value'])) continue;
    if (mb_strlen($ppv['param_value']) > 40) continue;
    $links = [];
    foreach ($productCategories as $cat) {
        $links[] = ['text' => $ppv['param_value'] . ' — ' . applyShortcodes($cat['name']), 'url' => urlKategorie($cat['slug']) . '/' . t('url_param') . '-' . $ppv['param_slug'] . '-' . $ppv['value_slug']];
    }
    $seoLinks[] = ['label' => $ppv['param_name'] . ': ' . $ppv['param_value'], 'links' => $links];
}

// Související produkty — ze stejných kategorií, na sklad, mimo aktuální.
// Jede přes category_product_index: má has_stock i view_count a index
// (category_id, view_count), takže se nečte celá tabulka products. Původní
// dotaz s JOIN product_offers + OR-subquery + ORDER BY view_count byl na
// velkém katalogu nejpomalejší dotaz detailu (>15 s → 503).
$relatedProducts = [];
$catIds = array_map('intval', array_keys($productCategories));

$relatedFromIndex = function (array $categoryIds, array $excludeIds, int $limit): array {
    $categoryIds = array_values(array_unique(array_filter(array_map('intval', $categoryIds))));
    $excludeIds = array_values(array_unique(array_filter(array_map('intval', $excludeIds))));
    if (empty($categoryIds) || $limit <= 0) {
        return [];
    }
    $catList = implode(',', $categoryIds);
    $exList = empty($excludeIds) ? '0' : implode(',', $excludeIds);

    $rows = db()->query(
        "SELECT p.id, p.name, p.slug, p.images, p.manufacturer, p.currency, p.is_service
         FROM (
            SELECT cpi.product_id, MAX(cpi.view_count) AS vc
            FROM category_product_index cpi
            WHERE cpi.category_id IN ({$catList})
              AND cpi.has_stock = 1
              AND cpi.product_id NOT IN ({$exList})
            GROUP BY cpi.product_id
            ORDER BY vc DESC
            LIMIT {$limit}
         ) r
         INNER JOIN products p ON p.id = r.product_id AND p.visible = 1
         ORDER BY r.vc DESC"
    ) ?: [];
    return $rows;
};

if (!empty($catIds) && runtimeTableExists('category_product_index')) {
    $relatedProducts = $relatedFromIndex($catIds, [$product['id']], 6);

    // Fallback: doplnit z rodičovských kategorií (s předky v indexu pokryje
    // rodičovské id celý podstrom jedním dotazem)
    if (count($relatedProducts) < 6) {
        $parentRows = db()->query(
            "SELECT DISTINCT parent_id FROM categories WHERE id IN (" . implode(',', $catIds) . ") AND parent_id IS NOT NULL"
        ) ?: [];
        $parentIds = array_map('intval', array_column($parentRows, 'parent_id'));
        if (!empty($parentIds)) {
            $exclude = array_merge(array_column($relatedProducts, 'id'), [$product['id']]);
            $extraRelated = $relatedFromIndex($parentIds, $exclude, 6 - count($relatedProducts));
            $relatedProducts = array_merge($relatedProducts, $extraRelated);
        }
    }
} elseif (!empty($catIds)) {
    // Fallback bez materializovaného indexu (čerstvá instalace před update-db)
    $placeholders = implode(',', array_fill(0, count($catIds), '?'));
    $relParams = array_merge($catIds, [$product['id']]);
    $relatedProducts = db()->query(
        "SELECT DISTINCT p.id, p.name, p.slug, p.images, p.manufacturer, p.currency, p.is_service
         FROM products p
         JOIN product_offers po ON po.product_id = p.id AND po.in_stock = 1
         WHERE (p.category_id IN ($placeholders)
                OR p.id IN (SELECT pc.product_id FROM product_categories pc WHERE pc.category_id IN ($placeholders)))
           AND p.id != ?
           AND p.visible = 1
         ORDER BY p.view_count DESC
         LIMIT 6",
        array_merge($catIds, $relParams)
    ) ?: [];
}

// Nejlevnější cena + počet nabídek pro související produkty — jedním dotazem
$relatedPrices = [];
$relatedOfferCounts = [];
if (!empty($relatedProducts)) {
    $rpIds = array_column($relatedProducts, 'id');
    $rpPlaceholders = implode(',', array_fill(0, count($rpIds), '?'));
    $rpPrices = db()->query("SELECT product_id, min_price, offers_count FROM product_prices WHERE product_id IN ({$rpPlaceholders})", $rpIds) ?: [];
    foreach ($rpPrices as $rpp) {
        $relatedPrices[$rpp['product_id']] = $rpp['min_price'];
        $relatedOfferCounts[$rpp['product_id']] = (int)($rpp['offers_count'] ?? 0);
    }
}

// Výrobce row (pro link na stránku výrobce)
$manufacturer = $product['manufacturer_id']
    ? db()->queryOne("SELECT * FROM manufacturers WHERE id = ? AND visible = 1", [$product['manufacturer_id']])
    : null;

// SEO — title s nejnižší cenou: "Název od X Kč"
$breadcrumbs = RelationManager::getProductBreadcrumbs($product);
$seoTitle = null;
$baseTitle = !empty($product['meta_title']) ? $product['meta_title'] : (!empty($product['h1_title']) ? $product['h1_title'] : $product['name']);
// Nejlevnější nabídka na sklad (jinak vůbec nejlevnější)
$minOffer = !empty($inStockOffers) ? reset($inStockOffers) : (!empty($offers) ? reset($offers) : null);
$manualAffiliateUrl = trim((string)($product['affiliate_url'] ?? ''));
$safeProductDescription = '';
if (!empty($product['description'])) {
    $safeProductDescription = ($product['description_source'] ?? '') === 'feed'
        ? sanitizeTrustedHtml((string)$product['description'])
        : (string)$product['description'];
}
$productCurrency = !empty($product['currency']) ? $product['currency'] : null;
$bestOffer = !empty($inStockOffers) ? reset($inStockOffers) : null;
$hasPrimaryAffiliateTarget = $manualAffiliateUrl !== '' || ($bestOffer && !empty($bestOffer['affiliate_url'] ?: $bestOffer['url']));
$primaryProductClickUrl = $hasPrimaryAffiliateTarget ? urlProduktRedirect((int)$product['id']) : '';
if ($minOffer) {
    $seoTitle = $baseTitle . ' ' . t('from_price') . ' ' . formatPrice($minOffer['price_vat'], $productCurrency);
}

// ============================================================
// PODKLADY PRO POROVNÁVAČ (redesign 2026)
// ============================================================
$offersCount = count($offers ?: []);
$inStockCount = count($inStockOffers);
$isService = !empty($product['is_service']);

// Nejvyšší cena mezi nabídkami → o kolik nejlepší nabídka ušetří
$maxOfferPrice = null;
$pricesUpdatedAt = null;
foreach ($offers ?: [] as $o) {
    $maxOfferPrice = $maxOfferPrice === null ? (float)$o['price_vat'] : max($maxOfferPrice, (float)$o['price_vat']);
    if (!empty($o['updated_at'])) {
        $ts = strtotime($o['updated_at']);
        if ($ts && ($pricesUpdatedAt === null || $ts > $pricesUpdatedAt)) {
            $pricesUpdatedAt = $ts;
        }
    }
}
$bestSaving = ($bestOffer && $maxOfferPrice !== null)
    ? max(0, $maxOfferPrice - (float)$bestOffer['price_vat'])
    : 0;
$pricesUpdatedLabel = $pricesUpdatedAt
    ? t('prices_updated', ['date' => date('j. n. Y H:i', $pricesUpdatedAt)])
    : '';

// Klíčové parametry vedle titulku (max 4)
// Feedy posílají i technické klíče (#paircode, #FLAG#…) — ty vedle H1 nemají co dělat.
$displayParameters = [];
foreach ($parameters as $paramKey => $paramValue) {
    $paramKey = trim((string)$paramKey);
    if ($paramKey === '' || $paramKey[0] === '#' || trim((string)$paramValue) === '') {
        continue;
    }
    $displayParameters[$paramKey] = $paramValue;
}
$keyFacts = array_slice($displayParameters, 0, 4, true);

// Kolik nabídek zobrazit hned, zbytek za tlačítkem
$offersVisibleLimit = 4;

// Tenký produkt (bez nabídek nebo bez popisu) do indexu nepatří — u feedového
// katalogu je to hlavní zdroj thin contentu. Odkazy z něj ale následovat chceme.
$isIndexable = isProductIndexable($product, $offersCount);

$seoData = [
    'title' => $seoTitle,
    'entity' => $product,
    'og_type' => 'product',
    'canonical' => urlProdukt($product['slug']),
    'robots' => $isIndexable ? 'index, follow' : 'noindex, follow',
];

// Schema.org
$schemaOrg = generateProductSchema($product, $offers);
if (!empty($breadcrumbs)) {
    $schemaOrg .= generateBreadcrumbsSchema($breadcrumbs);
}

$pageType = 'product';

include __DIR__ . '/../templates/header.php';
?>

<div class="pd-top">
    <!-- Galerie -->
    <div class="pd-gallery" data-gallery>
        <div class="pd-gallery__main">
            <?php $mainImage = $images[0] ?? null; ?>
            <img src="<?= $mainImage ? imgSrc($mainImage) : noImageUrl() ?>"
                 alt="<?= e($product['name']) ?>"
                 width="800" height="800"
                 fetchpriority="high"
                 data-gallery-main>
            <?php if (!$isService): ?>
                <div class="pd-gallery__badges">
                    <?php if ($bestOffer && $bestSaving > 0): ?>
                        <span class="badge-pill badge-deal">
                            <i class="bi bi-fire" aria-hidden="true"></i>
                            <?= e(t('you_save', ['amount' => formatPrice($bestSaving, $productCurrency)])) ?>
                        </span>
                    <?php endif; ?>
                    <?php if ($offersCount > 1): ?>
                        <span class="badge-pill badge-info"><?= e(offersCountLabel($offersCount)) ?></span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            <?php if ($mainImage): ?>
                <button type="button" class="pd-gallery__zoom" data-gallery-zoom aria-label="<?= e(t('zoom_image')) ?>">
                    <i class="bi bi-arrows-fullscreen" aria-hidden="true"></i>
                </button>
            <?php endif; ?>
        </div>

        <?php if (count($images) > 1): ?>
            <div class="pd-gallery__thumbs">
                <?php foreach ($images as $i => $image): ?>
                    <button type="button"
                            class="pd-gallery__thumb <?= $i === 0 ? 'is-active' : '' ?>"
                            data-gallery-thumb
                            data-full="<?= e(imgSrc($image)) ?>"
                            aria-label="<?= e($product['name']) ?> <?= $i + 1 ?>">
                        <img src="<?= imgSrc($image) ?>" alt="" width="120" height="120" loading="lazy">
                    </button>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Titulek a základní info -->
    <div class="pd-info">
        <h1 class="pd-title"><?= e(getH1Title($product)) ?></h1>

        <div class="pd-meta">
            <?php if ($product['manufacturer']): ?>
                <?php if ($manufacturer): ?>
                    <a href="<?= urlVyrobce($manufacturer['slug']) ?>" class="pd-meta__brand"><?= e($product['manufacturer']) ?></a>
                <?php else: ?>
                    <span class="pd-meta__brand"><?= e($product['manufacturer']) ?></span>
                <?php endif; ?>
                <span class="pd-meta__dot">·</span>
            <?php endif; ?>

            <?php if (!$isService && $offersCount > 0): ?>
                <span class="pd-meta__shops"><?= e(shopsCountLabel($offersCount)) ?></span>
                <span class="pd-meta__dot">·</span>
            <?php endif; ?>

            <?php if ($isService): ?>
                <span class="pd-meta__stock"><?= e(t('service_available')) ?></span>
            <?php elseif ($inStockCount > 0): ?>
                <span class="pd-meta__stock"><?= e(t('in_stock_badge')) ?></span>
            <?php else: ?>
                <span class="pd-meta__stock is-out"><?= e(t('unavailable_badge')) ?></span>
            <?php endif; ?>
        </div>

        <?php if ($product['description']): ?>
            <?php $descPlain = htmlToPlainText($product['description']); ?>
            <p class="pd-shortdesc">
                <?= e(mb_strlen($descPlain) > 260 ? truncateText($descPlain, 260) : $descPlain) ?>
                <?php if (mb_strlen($descPlain) > 260): ?>
                    <a href="#popis-produktu"><?= e(t('read_more')) ?></a>
                <?php endif; ?>
            </p>
        <?php endif; ?>

        <?php if (!empty($keyFacts)): ?>
            <div class="pd-keyfacts">
                <?php foreach ($keyFacts as $key => $value): ?>
                    <div class="pd-keyfacts__row">
                        <span class="pd-keyfacts__key"><?= e($key) ?></span>
                        <span class="pd-keyfacts__val"><?= e($value) ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Buy box -->
    <?php if ($primaryProductClickUrl !== '' && ($bestOffer || $manualAffiliateUrl !== '')): ?>
        <div class="buy-box<?= (!$isService && $offersCount > 0) ? ' buy-box--desktop-only' : '' ?>">
            <?php if (!$isService && $offersCount > 1): ?>
                <span class="buy-box__flag">
                    <i class="bi bi-patch-check-fill" aria-hidden="true"></i>
                    <?= e(t('best_price_of_n', ['count' => $offersCount])) ?>
                </span>
            <?php endif; ?>

            <?php if ($bestOffer): ?>
                <div class="buy-box__price-row">
                    <span class="buy-box__price"><?= formatPrice($bestOffer['price_vat'], $productCurrency) ?></span>
                    <?php if ($bestSaving > 0): ?>
                        <span class="buy-box__save">−<?= formatPrice($bestSaving, $productCurrency) ?></span>
                    <?php endif; ?>
                </div>

                <div class="buy-box__shop-row">
                    <span class="shop-logo"><?= e($bestOffer['feed_name']) ?></span>
                    <span class="buy-box__avail">
                        <i class="bi bi-check-circle-fill" aria-hidden="true"></i>
                        <?= e(t('in_stock_badge')) ?>
                    </span>
                </div>
            <?php endif; ?>

            <a href="<?= e($primaryProductClickUrl) ?>"
               class="btn-cta btn-cta--block"
               target="_blank" rel="nofollow noopener sponsored"
               data-sticky-cta-anchor
               <?= ctaTrackingAttrs((int)$product['id'], $bestOffer ? (int)$bestOffer['id'] : null, 'buybox') ?>>
                <?= $isService ? e(t('try_service')) : e(t('go_to_shop')) ?>
                <i class="bi bi-arrow-right" aria-hidden="true"></i>
            </a>

            <?php if (!$isService && $offersCount > 1): ?>
                <a href="#kde-koupit" class="buy-box__secondary">
                    <?= e(t('compare_all_offers', ['count' => $offersCount])) ?>
                </a>
            <?php endif; ?>

            <?php if ($pricesUpdatedLabel): ?>
                <div class="buy-box__updated">
                    <i class="bi bi-arrow-repeat" aria-hidden="true"></i>
                    <span><?= e($pricesUpdatedLabel) ?></span>
                </div>
            <?php endif; ?>

            <div class="buy-box__disclosure">
                <i class="bi bi-info-circle" aria-hidden="true"></i>
                <span><?= e(t('affiliate_disclosure')) ?></span>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Kde koupit -->
<?php if (!$isService): ?>
    <?php if (empty($offers)): ?>
        <div class="empty-state" style="margin-bottom: 24px;">
            <i class="bi bi-inbox" aria-hidden="true"></i>
            <p class="empty-state__title"><?= e(t('no_offers')) ?></p>
        </div>
    <?php else: ?>
        <?php if ($inStockCount === 0): ?>
            <div class="empty-state" style="margin-bottom: 24px;">
                <i class="bi bi-box-seam" aria-hidden="true"></i>
                <p class="empty-state__title"><?= e(t('sold_out_title')) ?></p>
                <p class="empty-state__sub"><?= e(t('sold_out_text')) ?></p>
                <?php if (!empty($relatedProducts)): ?>
                    <a href="#podobne-produkty" class="btn-dark"><?= e(t('show_alternatives')) ?></a>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <section class="offers" id="kde-koupit">
            <div class="offers__head">
                <h2 class="offers__title">
                    <?= $inStockCount > 0 ? e(t('where_to_buy')) : e(t('historical_offers')) ?>
                    <span class="badge-pill badge-info"><?= e(offersCountLabel($offersCount)) ?></span>
                </h2>
                <?php if ($pricesUpdatedLabel): ?>
                    <span class="offers__updated">
                        <i class="bi bi-arrow-repeat" aria-hidden="true"></i>
                        <?= e($pricesUpdatedLabel) ?>
                    </span>
                <?php endif; ?>
            </div>

            <div class="offers__colhead" aria-hidden="true">
                <span><?= e(t('shop')) ?></span>
                <span><?= e(t('availability')) ?></span>
                <span><?= e(t('price')) ?></span>
                <span></span>
            </div>

            <div data-toggle-scope>
                <?php $bestShown = false; foreach ($offers as $idx => $offer): ?>
                    <?php
                    $isBest = $offer['in_stock'] && !$bestShown;
                    if ($isBest) $bestShown = true;
                    $rowClasses = 'offer-row';
                    if ($isBest) $rowClasses .= ' is-best';
                    if (!$offer['in_stock']) $rowClasses .= ' is-out';
                    if ($idx >= $offersVisibleLimit) $rowClasses .= ' offer-hidden';
                    $offerSaving = ($isBest && $bestSaving > 0) ? $bestSaving : 0;
                    ?>
                    <div class="<?= $rowClasses ?>">
                        <div class="offer-row__shop">
                            <span class="shop-logo"><?= e($offer['feed_name']) ?></span>
                            <?php if ($isBest): ?>
                                <span class="offer-row__flag">
                                    <i class="bi bi-patch-check-fill" aria-hidden="true"></i>
                                    <?= e(t('best_price')) ?>
                                </span>
                            <?php endif; ?>
                        </div>

                        <div class="offer-row__avail <?= $offer['in_stock'] ? '' : 'is-out' ?>">
                            <?php if ($offer['in_stock']): ?>
                                <i class="bi bi-check-circle-fill" aria-hidden="true"></i>
                                <?= e(t('in_stock_badge')) ?>
                            <?php else: ?>
                                <i class="bi bi-dash-circle" aria-hidden="true"></i>
                                <?= e(t('unavailable_badge')) ?>
                            <?php endif; ?>
                        </div>

                        <div class="offer-row__price">
                            <span class="offer-row__price-value"><?= formatPrice($offer['price_vat'], $productCurrency) ?></span>
                            <?php if ($offerSaving > 0): ?>
                                <span class="offer-row__save"><?= e(t('you_save', ['amount' => formatPrice($offerSaving, $productCurrency)])) ?></span>
                            <?php endif; ?>
                        </div>

                        <div class="offer-row__cta">
                            <a href="<?= e(urlOfferRedirect((int)$offer['id'])) ?>"
                               class="btn-cta btn-cta--sm btn-cta--block"
                               target="_blank" rel="nofollow noopener sponsored"
                               <?= $isBest ? 'data-sticky-cta-anchor' : '' ?>
                               <?= ctaTrackingAttrs((int)$product['id'], (int)$offer['id'], 'table') ?>>
                                <?= e(t('go_to_shop')) ?>
                                <i class="bi bi-arrow-right" aria-hidden="true"></i>
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <?php if ($offersCount > $offersVisibleLimit): ?>
                <button type="button" class="offers__more" data-toggle-hidden>
                    <?= e(t('show_more_offers')) ?>
                    <i class="bi bi-chevron-down" aria-hidden="true"></i>
                </button>
            <?php endif; ?>

            <p class="offers__disclosure">
                <i class="bi bi-info-circle" aria-hidden="true"></i>
                <span><?= e(t('affiliate_disclosure_long')) ?></span>
            </p>
        </section>
    <?php endif; ?>
<?php endif; ?>

<!-- Proč porovnávat u nás -->
<?php $trustStats = getCatalogStats(); ?>
<div class="trust-strip">
    <div class="trust-strip__item">
        <i class="bi bi-arrow-repeat" aria-hidden="true"></i>
        <span class="trust-strip__l1"><?= e(t('trust_prices_title')) ?></span>
        <span class="trust-strip__l2"><?= e(t('trust_prices_sub')) ?></span>
    </div>
    <?php if ((int)$trustStats['shops'] > 0): ?>
    <div class="trust-strip__item">
        <i class="bi bi-shop" aria-hidden="true"></i>
        <span class="trust-strip__l1"><?= e(t('trust_shops_title', ['count' => formatCount($trustStats['shops'])])) ?></span>
        <span class="trust-strip__l2"><?= e(t('trust_shops_sub')) ?></span>
    </div>
    <?php endif; ?>
    <div class="trust-strip__item">
        <i class="bi bi-shield-check" aria-hidden="true"></i>
        <span class="trust-strip__l1"><?= e(t('trust_free_title')) ?></span>
        <span class="trust-strip__l2"><?= e(t('trust_free_sub')) ?></span>
    </div>
</div>

<!-- Tarify / Plány (pro služby) -->
<?php
$serviceOffers = array_filter($offers ?: [], fn($o) => str_starts_with($o['feed_item_id'] ?? '', 'service-'));
?>
<?php if (!empty($serviceOffers)): ?>
    <section class="pd-section">
        <h2 class="pd-section__title"><?= e(t('pricing_plans')) ?></h2>
        <div class="row justify-content-center">
            <?php foreach ($serviceOffers as $idx => $sOffer):
                $planName = $sOffer['name'];
                if (str_contains($planName, ' – ')) {
                    $planName = substr($planName, strpos($planName, ' – ') + 5);
                } elseif (str_contains($planName, ' - ')) {
                    $planName = substr($planName, strpos($planName, ' - ') + 3);
                }
                $offerUrl = urlOfferRedirect((int)$sOffer['id']);
                $colSize = count($serviceOffers) <= 3 ? 4 : (count($serviceOffers) === 4 ? 3 : 4);
            ?>
                <div class="col-sm-6 col-lg-<?= $colSize ?> mb-3">
                    <div class="card h-100 text-center">
                        <div class="card-body d-flex flex-column">
                            <?php if ($idx === 0): ?>
                                <span class="badge-pill badge-stock mb-2 align-self-center"><?= e(t('best_price')) ?></span>
                            <?php endif; ?>
                            <h3 class="h6 fw-bold mb-3"><?= e($planName) ?></h3>
                            <div class="buy-box__price mb-3"><?= formatPrice($sOffer['price_vat'], $productCurrency) ?></div>
                            <div class="mt-auto">
                                <?php if ($offerUrl): ?>
                                    <a href="<?= e($offerUrl) ?>"
                                       class="btn-cta btn-cta--sm btn-cta--block"
                                       target="_blank" rel="nofollow noopener sponsored"
                                       <?= ctaTrackingAttrs((int)$product['id'], (int)$sOffer['id'], 'table') ?>>
                                        <?= e(t('go_to_shop')) ?>
                                        <i class="bi bi-arrow-right" aria-hidden="true"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </section>
<?php endif; ?>

<div class="pd-lower">
    <div>
        <!-- Popis produktu -->
        <?php if ($safeProductDescription): ?>
            <section class="pd-section" id="popis-produktu">
                <h2 class="pd-section__title"><?= e(t('product_description')) ?></h2>
                <div class="pd-section__body"><?= $safeProductDescription ?></div>
            </section>
        <?php endif; ?>

        <!-- Parametry -->
        <?php if (!empty($displayParameters)): ?>
            <section class="pd-section">
                <h2 class="pd-section__title"><?= e(t('product_parameters')) ?></h2>
                <table class="param-table">
                    <tbody>
                        <?php foreach ($displayParameters as $key => $value): ?>
                            <tr>
                                <th scope="row"><?= e($key) ?></th>
                                <td><?= e($value) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </section>
        <?php endif; ?>

        <!-- Recenze a srovnání -->
        <?php if ($review || !empty($comparisons)): ?>
            <section class="pd-section">
                <h2 class="pd-section__title"><?= e(t('reviews_and_comparisons')) ?></h2>
                <?php if ($review): ?>
                    <p class="mb-2">
                        <i class="bi bi-star-fill" style="color: var(--warn);" aria-hidden="true"></i>
                        <strong><?= e(t('review_of_product')) ?></strong>
                        <a href="<?= urlRecenze($review['slug']) ?>" style="color: var(--info); font-weight: 600;">
                            <?= e($review['title']) ?>
                        </a>
                        <?php if ($review['rating_overall']): ?>
                            <span class="badge-pill badge-stock"><?= number_format($review['rating_overall'], 1) ?><?= e(t('of_10')) ?></span>
                        <?php endif; ?>
                    </p>
                <?php endif; ?>
                <?php if (!empty($comparisons)): ?>
                    <p class="fw-semibold mb-2"><?= e(t('in_comparisons')) ?></p>
                    <ul class="mb-0">
                        <?php foreach ($comparisons as $comp): ?>
                            <li><a href="<?= urlSrovnani($comp['slug']) ?>" style="color: var(--info);"><?= e($comp['title']) ?></a></li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </section>
        <?php endif; ?>

        <!-- Doplňkové informace (SEO linky) -->
        <?php if (!empty($seoLinks)): ?>
            <section class="pd-section">
                <h2 class="pd-section__title"><?= e(t('supplementary_info')) ?></h2>
                <table class="param-table">
                    <tbody>
                        <?php foreach ($seoLinks as $seoRow): ?>
                            <tr>
                                <th scope="row"><?= e($seoRow['label']) ?></th>
                                <td><?php foreach ($seoRow['links'] as $i => $link): ?><?php if ($i > 0): ?>, <?php endif; ?><a href="<?= e($link['url']) ?>" style="color: var(--info);"><?= e($link['text']) ?></a><?php endforeach; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </section>
        <?php endif; ?>
    </div>

    <!-- Podobné produkty -->
    <?php if (!empty($relatedProducts)): ?>
        <aside class="pd-section" id="podobne-produkty">
            <h2 class="pd-section__title" style="font-size: 16px;"><?= e(t('similar_in_stock')) ?></h2>
            <div class="similar-list">
                <?php foreach ($relatedProducts as $rp): ?>
                    <?php
                    $rpImages = json_decode($rp['images'], true) ?? [];
                    $rpImg = $rpImages[0] ?? null;
                    $rpOffers = $relatedOfferCounts[$rp['id']] ?? 0;
                    ?>
                    <a href="<?= urlProdukt($rp['slug']) ?>" class="similar-item">
                        <img src="<?= $rpImg ? imgSrc($rpImg) : noImageUrl() ?>" alt="<?= e($rp['name']) ?>"
                             width="60" height="60" loading="lazy">
                        <span class="similar-item__col">
                            <span class="similar-item__name"><?= e($rp['name']) ?></span>
                            <?php if ($rpOffers > 0): ?>
                                <span class="similar-item__shops"><?= e(productOffersMetaLabel($rp, $rpOffers)) ?></span>
                            <?php endif; ?>
                        </span>
                        <?php if (!empty($relatedPrices[$rp['id']])): ?>
                            <span class="similar-item__price">
                                <span class="similar-item__from"><?= e(t('from_price')) ?></span>
                                <span class="similar-item__value"><?= formatPrice($relatedPrices[$rp['id']], $rp['currency'] ?? null) ?></span>
                            </span>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </aside>
    <?php endif; ?>
</div>

<!-- Sticky CTA (mobil) -->
<?php if ($primaryProductClickUrl !== '' && $bestOffer): ?>
    <div class="sticky-cta" id="stickyCta">
        <div class="sticky-cta__left">
            <span class="sticky-cta__label">
                <i class="bi bi-patch-check-fill" aria-hidden="true"></i>
                <?= e(t('best_price')) ?> · <?= e($bestOffer['feed_name']) ?>
            </span>
            <span class="sticky-cta__price"><?= formatPrice($bestOffer['price_vat'], $productCurrency) ?></span>
        </div>
        <a href="<?= e($primaryProductClickUrl) ?>"
           class="btn-cta"
           target="_blank" rel="nofollow noopener sponsored"
           <?= ctaTrackingAttrs((int)$product['id'], (int)$bestOffer['id'], 'sticky') ?>>
            <?= e(t('go_to_shop')) ?>
            <i class="bi bi-arrow-right" aria-hidden="true"></i>
        </a>
    </div>
<?php endif; ?>

<!-- Lightbox galerie -->
<?php if (!empty($images)): ?>
    <dialog class="pd-lightbox" id="galleryLightbox">
        <button type="button" class="pd-lightbox__close" data-lightbox-close aria-label="<?= e(t('close')) ?>">
            <i class="bi bi-x-lg" aria-hidden="true"></i>
        </button>
        <img src="<?= imgSrc($images[0]) ?>" alt="<?= e($product['name']) ?>">
    </dialog>
<?php endif; ?>

<?php include __DIR__ . '/../templates/footer.php'; ?>
