<?php
declare(strict_types=1);

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

$tab = (string) ($_GET['tab'] ?? 'urunler');
if (!in_array($tab, ['urunler', 'sattiklari'], true)) {
    $tab = 'urunler';
}

$sort = (string) ($_GET['sort'] ?? 'yeni');
$cat = trim((string) ($_GET['cat'] ?? ''));
$sellerId = trim((string) ($_GET['s'] ?? ''));
$seller = $sellerId !== '' ? seller_find($sellerId) : null;
$cats = categories();
$all = store_read('products');

if ($seller) {
    $all = array_values(array_filter($all, static fn(array $p): bool => (string) ($p['seller_id'] ?? '') === $sellerId));
}

$active = array_values(array_filter($all, static fn(array $p): bool => ($p['status'] ?? '') === 'active'));
$sold = array_values(array_filter($all, static fn(array $p): bool => ($p['status'] ?? '') === 'sold'));

$list = $tab === 'sattiklari' ? $sold : $active;

if ($cat !== '') {
    $list = array_values(array_filter($list, static fn(array $p): bool => product_category_root_slug($p) === $cat));
}

if ($sort === 'ucuz') {
    usort($list, static fn(array $a, array $b): int => ((float) ($a['price'] ?? 0)) <=> ((float) ($b['price'] ?? 0)));
} elseif ($sort === 'pahali') {
    usort($list, static fn(array $a, array $b): int => ((float) ($b['price'] ?? 0)) <=> ((float) ($a['price'] ?? 0)));
} else {
    usort($list, static fn(array $a, array $b): int => strcmp(
        $b['sold_at'] ?? $b['created_at'] ?? '',
        $a['sold_at'] ?? $a['created_at'] ?? ''
    ));
}

if ($seller) {
    $handle = seller_handle($seller);
    $shopReviews = (int) ($seller['review_count'] ?? 0);
    $shopRating = (float) ($seller['rating'] ?? 5);
    $followers = seller_followers($seller);
    $following = seller_following($seller);
    $successSales = seller_successful_sales($seller, count($sold));
    $memberLabel = seller_member_label($seller);
} else {
    $handle = '@' . mb_strtolower(preg_replace('/\s+/u', '', APP_NAME) ?: 'magaza');
    $shopReviews = count(store_read('comments'));
    $shopRating = 5.0;
    $followers = max(50, count($active) * 40);
    $following = 0;
    $successSales = seller_successful_sales(null, count($sold));
    $memberLabel = 'Bölgesel satış';
}
$showFilter = isset($_GET['filtre']);
$sQuery = $sellerId !== '' ? '&s=' . rawurlencode($sellerId) : '';
$starsText = str_repeat('★', (int) round(max(1, min(5, $shopRating))));
$followSvg = '<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>';
$clockSvg = '<svg class="shop-clock" viewBox="0 0 24 24" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>';
$checkSvg = '<svg class="shop-sales-check" viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><circle cx="12" cy="12" r="11" fill="#1da1f2"/><path d="M7.2 12.4l2.8 2.8 6.8-6.8" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>';

$metaDescription = $handle . ' — ' . APP_NAME . ' satıcı profili.';
$ogTitle = $handle . ' · ' . APP_NAME;
$ogDescription = $metaDescription;
$ogUrl = app_base_url() . '/magaza.php' . ($sellerId !== '' ? '?s=' . rawurlencode($sellerId) : '');
$ogType = 'profile';

$pageTitle = $handle;
$pageClass = 'page-shop';
require __DIR__ . '/includes/header.php';
?>

<div class="shop-app">
    <?php require __DIR__ . '/includes/app_header.php'; ?>

    <p class="shop-crumb">
        <a href="<?= e(url('index.php')) ?>">Ana Sayfa</a>
        <span>›</span>
        <span><?= e($handle) ?></span>
    </p>

    <section class="shop-profile">
        <div class="shop-hero">
            <div class="shop-hero-left">
                <?php if ($seller): ?>
                    <?= seller_avatar_html($seller, 'avatar sq shop-diamond', $handle) ?>
                <?php else: ?>
                    <div class="shop-diamond" aria-hidden="true">
                        <span><?= e(mb_strtoupper(mb_substr(APP_NAME, 0, 1))) ?></span>
                    </div>
                <?php endif; ?>
                <div class="shop-hero-info">
                    <div class="shop-handle-row">
                        <h1 class="shop-handle"><?= e($handle) ?></h1>
                        <p class="shop-online"><?= $clockSvg ?> <?= e($memberLabel) ?></p>
                        <button type="button" class="shop-follow-icon" disabled title="Şimdilik pasif" aria-label="Takip et"><?= $followSvg ?></button>
                    </div>
                    <div class="shop-follow-stats">
                        <div><strong><?= number_format($followers, 0, ',', '.') ?></strong> <span>Takipçi</span></div>
                        <div><strong><?= number_format($following, 0, ',', '.') ?></strong> <span>Takip Ettiği</span></div>
                        <div class="shop-sales-stat">
                            <strong><?= number_format($successSales, 0, ',', '.') ?></strong>
                            <span><?= $checkSvg ?> başarılı satış</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <nav class="shop-tabs-mobile" aria-label="Profil sekmeleri">
            <a class="<?= $tab === 'urunler' ? 'active' : '' ?>" href="<?= e(url('magaza.php?tab=urunler' . $sQuery . ($cat ? '&cat=' . urlencode($cat) : '') . ($sort !== 'yeni' ? '&sort=' . urlencode($sort) : ''))) ?>">
                ÜRÜNLERİ <span>(<?= count($active) ?>)</span>
            </a>
            <a class="<?= $tab === 'sattiklari' ? 'active' : '' ?>" href="<?= e(url('magaza.php?tab=sattiklari' . $sQuery . ($cat ? '&cat=' . urlencode($cat) : '') . ($sort !== 'yeni' ? '&sort=' . urlencode($sort) : ''))) ?>">
                SATTIKLARI <span>(<?= count($sold) ?>)</span>
            </a>
            <span class="passive">FAVORİLERİ <span>(0)</span></span>
        </nav>
    </section>

    <div class="shop-body">
        <aside class="shop-side">
            <h3>KATEGORİ</h3>
            <a class="filter-clear" href="<?= e(url('magaza.php?tab=' . urlencode($tab) . $sQuery . '&sort=' . urlencode($sort))) ?>">Tüm filtreleri temizle</a>
            <ul>
                <?php
                $sourceForCats = $tab === 'sattiklari' ? $sold : $active;
                $catCounts = [];
                foreach ($sourceForCats as $p) {
                    $key = product_category_root_slug($p) ?: 'diger';
                    $catCounts[$key] = ($catCounts[$key] ?? 0) + 1;
                }
                foreach ($cats as $key => $label):
                    $count = $catCounts[$key] ?? 0;
                    if ($count === 0) continue;
                ?>
                    <li>
                        <a class="<?= $cat === $key ? 'on' : '' ?>" href="<?= e(url('magaza.php?tab=' . urlencode($tab) . $sQuery . '&cat=' . urlencode($key) . '&sort=' . urlencode($sort))) ?>">
                            <?= e($label) ?> <span>(<?= $count ?>)</span>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </aside>

        <div class="shop-main">
            <div class="shop-toolbar">
                <strong><?= count($list) ?> Ürün</strong>
                <div class="shop-tools">
                    <details class="shop-tool">
                        <summary>⇅ Akıllı Sıralama</summary>
                        <div class="shop-tool-menu">
                            <a href="<?= e(url('magaza.php?tab=' . urlencode($tab) . $sQuery . ($cat ? '&cat=' . urlencode($cat) : '') . '&sort=yeni')) ?>">En yeni</a>
                            <a href="<?= e(url('magaza.php?tab=' . urlencode($tab) . $sQuery . ($cat ? '&cat=' . urlencode($cat) : '') . '&sort=ucuz')) ?>">En ucuz</a>
                            <a href="<?= e(url('magaza.php?tab=' . urlencode($tab) . $sQuery . ($cat ? '&cat=' . urlencode($cat) : '') . '&sort=pahali')) ?>">En pahalı</a>
                        </div>
                    </details>
                    <details class="shop-tool shop-filter-mobile" <?= $showFilter || $cat !== '' ? 'open' : '' ?>>
                        <summary>⚙ Filtrele</summary>
                        <div class="shop-tool-menu">
                            <a href="<?= e(url('magaza.php?tab=' . urlencode($tab) . $sQuery . '&sort=' . urlencode($sort))) ?>">Tümü</a>
                            <?php foreach ($cats as $key => $label): ?>
                                <a class="<?= $cat === $key ? 'on' : '' ?>" href="<?= e(url('magaza.php?tab=' . urlencode($tab) . $sQuery . '&cat=' . urlencode($key) . '&sort=' . urlencode($sort))) ?>">
                                    <?= e($label) ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </details>
                </div>
            </div>

            <div class="shop-grid">
                <?php if (!$list): ?>
                    <div class="empty"><?= $tab === 'sattiklari' ? 'Henüz satılan ürün yok.' : 'Henüz ürün yok.' ?></div>
                <?php endif; ?>

                <?php foreach ($list as $p):
                    $href = url('urun.php?id=' . urlencode($p['id']));
                    $isSold = $tab === 'sattiklari';
                ?>
                    <article class="shop-card <?= $isSold ? 'is-sold' : '' ?>">
                        <div class="shop-card-head">
                            <?php if ($seller): ?>
                                <?= seller_avatar_html($seller, 'avatar sq tiny', $handle) ?>
                            <?php else: ?>
                                <div class="avatar sq tiny"><?= e(mb_strtoupper(mb_substr($handle, 1, 1))) ?></div>
                            <?php endif; ?>
                            <div class="shop-card-meta">
                                <strong><?= e($handle) ?></strong>
                                <div class="seller-line">
                                    <span class="stars"><?= e($starsText) ?></span>
                                    <span class="hint">(<?= (int) $shopReviews ?>)</span>
                                </div>
                            </div>
                            <span class="shop-follow-icon tiny" title="Şimdilik pasif">＋</span>
                        </div>
                        <?php if ($isSold): ?>
                            <div class="shop-card-media">
                                <span class="sold-badge">Satıldı</span>
                                <img src="<?= e(product_image_url($p)) ?>" alt="<?= e($p['title'] ?? '') ?>">
                            </div>
                        <?php else: ?>
                            <a class="shop-card-media" href="<?= e($href) ?>">
                                <img src="<?= e(product_image_url($p)) ?>" alt="<?= e($p['title'] ?? '') ?>">
                                <?= product_shipping_badge($p) ?>
                            </a>
                        <?php endif; ?>
                        <div class="shop-card-body">
                            <?php if ($isSold): ?>
                                <h2><?= e($p['title'] ?? '') ?></h2>
                            <?php else: ?>
                                <h2><a href="<?= e($href) ?>"><?= e($p['title'] ?? '') ?></a></h2>
                            <?php endif; ?>
                            <strong><?= e(money($p['price'] ?? 0)) ?></strong>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

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