<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';

$id = (string) ($_GET['id'] ?? '');
$product = store_find('products', $id);

if (!$product || ($product['status'] ?? 'active') !== 'active') {
    flash('error', 'Ürün bulunamadı.');
    redirect('index.php');
}

$cats = categories();
$allComments = comments_for_product($id);
$roots = array_values(array_filter($allComments, static fn(array $c): bool => empty($c['parent_id'])));
$repliesByParent = [];
foreach ($allComments as $c) {
    $parent = $c['parent_id'] ?? '';
    if ($parent !== '') {
        $repliesByParent[$parent][] = $c;
    }
}

$commentCount = count($roots);
$priceLabel = number_format((float) ($product['price'] ?? 0), 0, ',', '.') . ' TL';
$gallery = product_image_urls($product);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'buy') {
        redirect('odeme.php?id=' . urlencode($id));
    }

    if ($action === 'comment') {
        flash('error', 'Yorumlar kapalı. Sadece yönetim panelinden eklenir.');
        redirect('urun.php?id=' . urlencode($id) . '#yorumlar');
    }
}

function comment_time_ago(string $iso): string
{
    $ts = strtotime($iso) ?: time();
    $diff = time() - $ts;
    if ($diff < 60) return 'az önce';
    if ($diff < 3600) return floor($diff / 60) . ' dk önce';
    if ($diff < 86400) return floor($diff / 3600) . ' saat önce';
    if ($diff < 604800) return floor($diff / 86400) . ' gün önce';
    if ($diff < 2592000) return floor($diff / 604800) . ' hafta önce';
    return date('d.m.Y', $ts);
}

function comment_display_name(array $c): string
{
    if (!empty($c['guest_name'])) {
        return (string) $c['guest_name'];
    }
    if (!empty($c['user_id'])) {
        return user_name((string) $c['user_id']);
    }
    return 'Misafir';
}

$pageTitle = $product['title'] ?? 'Ürün';
$pageClass = 'page-product';

$social = product_social_meta($product);

// WhatsApp / Facebook botu: sadece OG HTML (tam sayfa + X-Robots-Tag yok)
if (function_exists('site_control_is_social_crawler') && site_control_is_social_crawler()) {
    social_og_respond_and_exit($social);
}

$metaDescription = $social['description'];
$ogTitle = $social['title'];
$ogDescription = $social['description'];
$ogImage = $social['image'];
$ogUrl = $social['url'];
$ogType = $social['type'];
$ogImageWidth = $social['image_width'];
$ogImageHeight = $social['image_height'];
$ogImageType = $social['image_type'];
$ogImageAlt = $social['image_alt'];
$jsonLd = $social['jsonld'];
$ogPriceAmount = $social['price'];
$ogPriceCurrency = $social['currency'];

require __DIR__ . '/includes/header.php';
?>

<?php require __DIR__ . '/includes/app_header.php'; ?>

<p class="pm-breadcrumb">
    <a href="<?= e(url('index.php')) ?>">Ana Sayfa</a>
    <span>›</span>
    <?php $rootSlug = product_category_root_slug($product); ?>
    <a href="<?= e(url('index.php?cat=' . urlencode($rootSlug))) ?>"><?= e($cats[$rootSlug] ?? category_label((string) ($product['category'] ?? ''))) ?></a>
    <span>›</span>
    <span><?= e($product['title'] ?? '') ?></span>
</p>

<article class="product-layout">
    <?php
    $shareUrl = $ogUrl;
    $shareText = (string) ($product['title'] ?? 'Ürün');
    $twShare = 'https://twitter.com/intent/tweet?url=' . rawurlencode($shareUrl) . '&text=' . rawurlencode($shareText);
    $fbShare = 'https://www.facebook.com/sharer/sharer.php?u=' . rawurlencode($shareUrl);
    $multi = count($gallery) > 1;
    ?>
    <div class="pm-gallery" data-gallery>
        <div class="pm-media">
            <div class="pm-gallery-track" data-gallery-track>
                <?php foreach ($gallery as $i => $src): ?>
                    <img src="<?= e($src) ?>" alt="<?= e(($product['title'] ?? 'Ürün') . ' ' . ($i + 1)) ?>" draggable="false">
                <?php endforeach; ?>
            </div>
            <?= product_shipping_badge($product) ?>
            <?php if ($multi): ?>
                <button type="button" class="pm-gal-btn prev pm-gal-mobile" data-gallery-prev aria-label="Önceki">‹</button>
                <button type="button" class="pm-gal-btn next pm-gal-mobile" data-gallery-next aria-label="Sonraki">›</button>
                <div class="pm-gal-dots pm-gal-mobile" data-gallery-dots>
                    <?php foreach ($gallery as $i => $_): ?>
                        <button type="button" class="<?= $i === 0 ? 'on' : '' ?>" data-gallery-dot="<?= $i ?>" aria-label="Foto <?= $i + 1 ?>"></button>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <div class="pm-gal-toolbar pm-gal-desktop">
            <div class="pm-gal-share">
                <span>PAYLAŞ!</span>
                <a class="pm-share-ico" href="<?= e($twShare) ?>" target="_blank" rel="noopener noreferrer" aria-label="X ile paylaş" title="X">
                    <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.74l7.727-8.835L1.254 2.25H8.08l4.253 5.622L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
                </a>
                <a class="pm-share-ico" href="<?= e($fbShare) ?>" target="_blank" rel="noopener noreferrer" aria-label="Facebook ile paylaş" title="Facebook">
                    <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M13.5 22v-8h2.7l.4-3.1H13.5V9c0-.9.3-1.5 1.6-1.5H16.7V4.7c-.3 0-1.3-.1-2.5-.1-2.5 0-4.2 1.5-4.2 4.3v2.4H7.3V14h2.7v8h3.5z"/></svg>
                </a>
            </div>
            <?php if ($multi): ?>
                <div class="pm-gal-nav">
                    <button type="button" data-gallery-prev aria-label="Önceki">←</button>
                    <button type="button" data-gallery-next aria-label="Sonraki">→</button>
                </div>
            <?php endif; ?>
        </div>

        <?php if ($multi): ?>
            <div class="pm-thumbs pm-gal-desktop" data-gallery-thumbs>
                <?php foreach ($gallery as $i => $src): ?>
                    <button type="button" class="pm-thumb <?= $i === 0 ? 'on' : '' ?>" data-gallery-thumb="<?= $i ?>" aria-label="Fotoğraf <?= $i + 1 ?>">
                        <img src="<?= e($src) ?>" alt="" draggable="false">
                    </button>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="pm-side">
        <?php
        $sellerRow = product_seller($product);
        $sellerName = trim((string) ($product['seller_name'] ?? ''));
        if ($sellerName === '' && $sellerRow) {
            $sellerName = trim((string) ($sellerRow['name'] ?? ''));
        }
        if ($sellerName === '') {
            $sellerName = 'Satıcı';
        }
        $sellerUsername = ltrim(trim((string) ($product['seller_username'] ?? '')), '@');
        if ($sellerUsername === '') {
            $sellerUsername = seller_username($sellerRow, $sellerName);
        }
        $sellerHandle = '@' . $sellerUsername;
        $sellerShopUrl = url('magaza.php' . (!empty($product['seller_id']) ? '?s=' . rawurlencode((string) $product['seller_id']) : ''));
        $cityText = trim((string) ($product['city_text'] ?? ''));
        if ($cityText === '') {
            $cityText = implode(' / ', array_filter([
                trim((string) ($product['city'] ?? '')),
                trim((string) ($product['district'] ?? '')),
                trim((string) ($product['neighborhood'] ?? '')),
            ]));
        }
        $memberSince = trim((string) ($product['member_since'] ?? ''));
        $memberYear = trim((string) ($product['member_year'] ?? ''));
        ?>
        <div class="pm-attrs">
            <div class="pm-attrs-main">
                <h1><?= e($product['title'] ?? '') ?></h1>
                <?php if ($cityText !== ''): ?><p><?= e($cityText) ?></p><?php endif; ?>
                <p><?= e(product_shipping_line($product)) ?></p>
                <?php if (!empty($product['category_tree'])): ?>
                    <p class="pm-cat-tree"><?= e($product['category_tree']) ?></p>
                <?php endif; ?>
            </div>
            <?php $likeCount = product_likes($product); ?>
            <div class="pm-like" title="Şimdilik pasif" aria-label="<?= $likeCount ?> Beğeni">
                <?= heart_icon_svg(28) ?>
                <span><?= $likeCount ?> Beğeni</span>
            </div>
        </div>

        <div class="pm-desktop-buy">
            <div class="pm-price"><?= e($priceLabel) ?></div>
            <div class="pm-actions">
                <form method="post">
                    <input type="hidden" name="action" value="buy">
                    <button class="pm-buy" type="submit" <?= ((int) ($product['stock'] ?? 0) <= 0) ? 'disabled' : '' ?>>
                        <span>SATIN</span><span>AL</span>
                    </button>
                </form>
            </div>
        </div>

        <a class="seller-card" href="<?= e($sellerShopUrl) ?>">
            <div class="who">
                <?php
                if ($sellerRow) {
                    echo seller_avatar_html($sellerRow, 'avatar sq', $sellerHandle);
                } else {
                    $sellerAvatarFile = trim((string) ($product['seller_avatar'] ?? ''));
                    $fakeSeller = [
                        'avatar' => $sellerAvatarFile,
                        'avatar_seed' => (string) ($product['seller_avatar_seed'] ?? $sellerUsername),
                        'name' => $sellerName,
                    ];
                    echo seller_avatar_html($fakeSeller, 'avatar sq', $sellerHandle);
                }
                ?>
                <div>
                    <strong class="seller-name"><?= e($sellerHandle) ?></strong>
                    <?php
                    $sellerRating = (float) ($sellerRow['rating'] ?? ($product['seller_rating'] ?? 5));
                    $sellerReviews = (int) ($sellerRow['review_count'] ?? ($product['seller_reviews'] ?? $commentCount));
                    $starsText = seller_stars_text($sellerRating);
                    ?>
                    <div class="seller-line">
                        <span class="stars"><?= e($starsText) ?></span>
                        <span class="hint">(<?= $sellerReviews ?>)</span>
                        <?php if ($memberYear !== ''): ?>
                            <span class="hint">· <?= e($memberYear) ?>. yıl</span>
                        <?php endif; ?>
                    </div>
                    <?php if ($memberSince !== ''): ?>
                        <div class="hint">Üyelik: <?= e($memberSince) ?></div>
                    <?php endif; ?>
                </div>
            </div>
            <span class="shop-follow-icon" title="Şimdilik pasif"><?= follow_icon_svg(18) ?></span>
        </a>

        <div class="pm-body">
            <p class="desc"><?= nl2br(e($product['description'] ?? '')) ?></p>
            <?php
            $colorHtml = product_color_label_html($product);
            if ($colorHtml !== ''): ?>
                <div class="pm-color"><?= $colorHtml ?></div>
            <?php endif; ?>
        </div>

        <?php
        $securePayUrl = url('guvenli-odeme.php');
        $payOptionsUrl = url('guvenli-odeme.php#odeme-secenekleri');
        ?>
        <section class="pm-advantages" aria-label="Avantajlar">
            <h2><?= e(theme_t('adv_section_title')) ?></h2>
            <div class="pm-adv-grid">
                <a class="pm-adv-item" href="<?= e($securePayUrl) ?>">
                    <span class="pm-adv-ico pm-adv-check" aria-hidden="true">
                        <svg viewBox="0 0 24 24" width="22" height="22"><path fill="currentColor" d="M9.2 16.6 4.8 12.2l1.4-1.4 3 3 8.6-8.6 1.4 1.4z"/></svg>
                    </span>
                    <span><?= theme_t_html('adv_item_1') ?></span>
                </a>
                <a class="pm-adv-item" href="<?= e($securePayUrl) ?>">
                    <span class="pm-adv-ico pm-adv-lock" aria-hidden="true">
                        <svg viewBox="0 0 24 24" width="20" height="20"><path fill="currentColor" d="M17 9h-1V7a4 4 0 1 0-8 0v2H7a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2zm-7-2a2 2 0 1 1 4 0v2h-4V7zm7 12H7v-8h10v8z"/></svg>
                    </span>
                    <span><?= theme_t_html('adv_item_2') ?></span>
                </a>
                <a class="pm-adv-item" href="<?= e($securePayUrl) ?>">
                    <span class="pm-adv-ico pm-adv-support" aria-hidden="true">
                        <svg viewBox="0 0 24 24" width="20" height="20"><path fill="currentColor" d="M12 3a7 7 0 0 0-7 7v2.2A2.8 2.8 0 0 0 3.2 15v1.5A2.8 2.8 0 0 0 6 19.3h1.2V12H6v-.9a6 6 0 1 1 12 0v.9h-1.2v7.3H18A2.8 2.8 0 0 0 20.8 16.5V15A2.8 2.8 0 0 0 19 12.2V10a7 7 0 0 0-7-7zm-1.2 14.8c0 1.1.7 2.2 1.2 2.7.5-.5 1.2-1.6 1.2-2.7v-2.3h-2.4v2.3z"/></svg>
                    </span>
                    <span><?= theme_t_html('adv_item_3') ?></span>
                </a>
            </div>

            <a class="pm-adv-block" href="<?= e($securePayUrl) ?>#guvenli-odeme">
                <span class="pm-adv-block-ico" aria-hidden="true">
                    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="7" width="13" height="9" rx="1"/><path d="M14 10h3.5L21 13.5V16h-7v-6z"/><circle cx="5.5" cy="18.5" r="1.7"/><circle cx="16.5" cy="18.5" r="1.7"/></svg>
                </span>
                <div class="pm-adv-block-body">
                    <strong><?= e(theme_t('adv_secure_title')) ?></strong>
                    <p><?= e(theme_t('adv_secure_body')) ?></p>
                </div>
                <span class="pm-adv-chevron" aria-hidden="true">›</span>
            </a>

            <a class="pm-adv-block pm-adv-payrow" href="<?= e($payOptionsUrl) ?>">
                <span class="pm-adv-block-ico" aria-hidden="true">
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></svg>
                </span>
                <div class="pm-adv-block-body">
                    <strong><?= e(theme_t('adv_pay_title')) ?></strong>
                    <p><?= e(theme_t('adv_pay_body')) ?></p>
                </div>
                <span class="pm-adv-chevron" aria-hidden="true">›</span>
            </a>
        </section>
    </div>
</article>

<section class="comments" id="yorumlar">
    <h2>Yorumlar (<?= $commentCount ?>)</h2>

    <div class="comment-list">
        <?php if (!$roots): ?>
            <p class="empty">Henüz yorum yok.</p>
        <?php endif; ?>

        <?php foreach ($roots as $c):
            $cname = comment_display_name($c);
            $cSeed = avatar_seed_of($c, $cname);
            $replies = $repliesByParent[$c['id']] ?? [];
            usort($replies, static fn(array $a, array $b): int => strcmp((string) ($a['created_at'] ?? ''), (string) ($b['created_at'] ?? '')));
        ?>
            <article class="comment-thread">
                <div class="comment-item">
                    <?= avatar_img_html($cSeed, 'comment-avatar', $cname, 'user') ?>
                    <div class="comment-content">
                        <div class="comment-head">
                            <strong><?= e($cname) ?></strong>
                            <time><?= e(comment_time_ago($c['created_at'] ?? '')) ?></time>
                        </div>
                        <p><?= nl2br(e($c['text'] ?? '')) ?></p>
                    </div>
                </div>

                <?php if ($replies): ?>
                    <div class="comment-replies">
                        <?php foreach ($replies as $r):
                            $isSellerReply = !empty($r['is_seller']) || str_starts_with(comment_display_name($r), '@');
                            $rname = $isSellerReply ? $sellerHandle : comment_display_name($r);
                            if ($isSellerReply && !str_starts_with($rname, '@')) {
                                $rname = '@' . ltrim($rname, '@');
                            }
                        ?>
                            <div class="comment-item reply <?= $isSellerReply ? 'is-seller-reply' : '' ?>">
                                <?php if (!$isSellerReply): ?>
                                    <?= avatar_img_html(avatar_seed_of($r, $cSeed), 'comment-avatar', $rname, 'user') ?>
                                <?php endif; ?>
                                <div class="comment-content">
                                    <div class="comment-head">
                                        <strong class="<?= $isSellerReply ? 'seller-handle' : '' ?>"><?= e($rname) ?></strong>
                                        <time><?= e(comment_time_ago($r['created_at'] ?? '')) ?></time>
                                    </div>
                                    <p><?= nl2br(e($r['text'] ?? '')) ?></p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </article>
        <?php endforeach; ?>
    </div>

    <div class="comment-composer">
        <button type="button" class="btn-yorum-yaz is-disabled" id="yorum-yaz-btn" disabled title="Yorumlar yönetim panelinden eklenir">Yorum Yaz</button>
        <p class="yorum-kriter">Yorum Yayınlanma Kriterleri</p>
    </div>
</section>

<div class="pm-buybar" role="region" aria-label="Satın al">
    <div class="pm-price"><?= e($priceLabel) ?></div>
    <div class="pm-actions">
        <form method="post">
            <input type="hidden" name="action" value="buy">
            <button class="pm-buy" type="submit" <?= ((int) ($product['stock'] ?? 0) <= 0) ? 'disabled' : '' ?>>
                <span>SATIN</span><span>AL</span>
            </button>
        </form>
    </div>
</div>

<?php require __DIR__ . '/includes/footer.php'; ?>
