<?php
declare(strict_types=1);

/** @return list<array{name:string,text:string,reply_name:string,reply_text:string,followup_text:string,followup_reply:string}> */
function parse_seed_comments(array $post): array
{
    $names = $post['comment_name'] ?? [];
    $texts = $post['comment_text'] ?? [];
    $rNames = $post['reply_name'] ?? [];
    $rTexts = $post['reply_text'] ?? [];
    $fuTexts = $post['followup_text'] ?? [];
    $fuReplies = $post['followup_reply'] ?? [];
    if (!is_array($names) || !is_array($texts)) {
        return [];
    }
    $out = [];
    $n = max(count($names), count($texts));
    for ($i = 0; $i < $n; $i++) {
        $name = trim((string) ($names[$i] ?? ''));
        $text = trim((string) ($texts[$i] ?? ''));
        if ($text === '') {
            continue;
        }
        $fuText = trim((string) ($fuTexts[$i] ?? ''));
        $fuReply = trim((string) ($fuReplies[$i] ?? ''));
        if ($fuText === '' || $fuReply === '') {
            $fuText = '';
            $fuReply = '';
        }
        $out[] = [
            'name' => $name !== '' ? $name : 'Misafir',
            'text' => $text,
            'reply_name' => trim((string) ($rNames[$i] ?? '')) ?: 'Satıcı',
            'reply_text' => trim((string) ($rTexts[$i] ?? '')),
            'followup_text' => $fuText,
            'followup_reply' => $fuReply,
        ];
    }
    return $out;
}

function save_seed_comments(string $productId, array $comments): int
{
    $added = 0;
    $base = time();
    $product = store_find('products', $productId) ?? [];
    $sellerSeed = trim((string) ($product['seller_avatar_seed'] ?? ''));

    foreach ($comments as $i => $c) {
        $text = trim((string) ($c['text'] ?? ''));
        if ($text === '') {
            continue;
        }
        $guest = trim((string) ($c['name'] ?? '')) ?: 'Misafir';
        $sellerName = trim((string) ($c['reply_name'] ?? '')) ?: 'Satıcı';
        $sellerHandle = $sellerName;
        if (!str_starts_with($sellerHandle, '@')) {
            // Üründeki satıcı kullanıcı adı
            $su = ltrim(trim((string) ($product['seller_username'] ?? '')), '@');
            if ($su !== '') {
                $sellerHandle = '@' . $su;
            } elseif (!empty($product['seller_id'])) {
                $sRow = seller_find((string) $product['seller_id']);
                $sellerHandle = seller_handle($sRow, (string) ($product['seller_name'] ?? $sellerName));
            } else {
                $sellerHandle = seller_handle(null, $sellerName);
            }
        }
        if ($sellerSeed === '') {
            $sellerSeed = avatar_seed_of(['name' => $sellerHandle]);
        }
        $parentId = new_id('c_');
        $commenterSeed = trim((string) ($c['avatar_seed'] ?? '')) ?: avatar_random_seed();
        $t0 = $base - (($i + 1) * 3600 * 10);

        store_upsert('comments', [
            'id' => $parentId,
            'product_id' => $productId,
            'user_id' => '',
            'guest_name' => $guest,
            'avatar_seed' => $commenterSeed,
            'parent_id' => '',
            'rating' => 0,
            'text' => $text,
            'created_at' => date('c', $t0),
            'seed' => true,
        ]);
        $added++;

        $replyText = trim((string) ($c['reply_text'] ?? ''));
        if ($replyText !== '') {
            if (!str_contains($replyText, '@')) {
                $replyText = '@' . $guest . ' ' . $replyText;
            }
            store_upsert('comments', [
                'id' => new_id('c_'),
                'product_id' => $productId,
                'user_id' => '',
                'guest_name' => $sellerHandle,
                'avatar_seed' => '',
                'parent_id' => $parentId,
                'rating' => 0,
                'text' => $replyText,
                'created_at' => date('c', $t0 + 1800),
                'seed' => true,
                'is_seller' => true,
            ]);
            $added++;
        }

        $fuText = trim((string) ($c['followup_text'] ?? ''));
        $fuReply = trim((string) ($c['followup_reply'] ?? ''));
        if ($fuText !== '' && $fuReply !== '') {
            store_upsert('comments', [
                'id' => new_id('c_'),
                'product_id' => $productId,
                'user_id' => '',
                'guest_name' => $guest,
                'avatar_seed' => $commenterSeed,
                'parent_id' => $parentId,
                'rating' => 0,
                'text' => $fuText,
                'created_at' => date('c', $t0 + 7200),
                'seed' => true,
            ]);
            $added++;

            if (!str_contains($fuReply, '@')) {
                $fuReply = '@' . $guest . ' ' . $fuReply;
            }
            store_upsert('comments', [
                'id' => new_id('c_'),
                'product_id' => $productId,
                'user_id' => '',
                'guest_name' => $sellerHandle,
                'avatar_seed' => '',
                'parent_id' => $parentId,
                'rating' => 0,
                'text' => $fuReply,
                'created_at' => date('c', $t0 + 9000),
                'seed' => true,
                'is_seller' => true,
            ]);
            $added++;
        }
    }
    return $added;
}

function parse_money_int(string $raw): int
{
    $digits = preg_replace('/\D+/', '', $raw) ?? '';
    return (int) $digits;
}

function product_from_admin_post(array $post, array $admin, array $existing = []): array|string
{
    $title = trim((string) ($post['title'] ?? ''));
    $description = trim((string) ($post['description'] ?? ''));
    $price = parse_money_int((string) ($post['price'] ?? '0'));
    $categoryParentId = trim((string) ($post['category_parent_id'] ?? ''));
    $categoryChildId = trim((string) ($post['category_child_id'] ?? ''));
    $parentCat = $categoryParentId !== '' ? category_find($categoryParentId) : null;
    $childCat = $categoryChildId !== '' ? category_find($categoryChildId) : null;
    if ($childCat && $parentCat && ($childCat['parent_id'] ?? '') !== ($parentCat['id'] ?? '')) {
        $childCat = null;
        $categoryChildId = '';
    }
    if (!$parentCat && $childCat && !empty($childCat['parent_id'])) {
        $parentCat = category_find((string) $childCat['parent_id']);
        $categoryParentId = (string) ($parentCat['id'] ?? '');
    }
    $category = (string) (($childCat['slug'] ?? '') !== '' ? $childCat['slug'] : ($parentCat['slug'] ?? ($post['category'] ?? 'diger')));
    $categoryTree = category_tree_text($parentCat, $childCat);
    if ($categoryTree === '') {
        $categoryTree = trim((string) ($post['category_tree'] ?? ''));
    }
    $stock = max(0, (int) ($post['stock'] ?? 1));
    $brand = trim((string) ($post['brand'] ?? ''));
    $color = trim((string) ($post['color'] ?? ''));
    if ($color !== '' && !isset(product_colors()[$color])) {
        $color = '';
    }
    $shipping = trim((string) ($post['shipping'] ?? 'free')) === 'buyer' ? 'buyer' : 'free';
    $siteIban = iban_site();
    $ibanId = (string) ($siteIban['id'] ?? '');

    $sellerId = trim((string) ($post['seller_id'] ?? ''));
    $seller = $sellerId !== '' ? seller_find($sellerId) : null;
    $sellerName = trim((string) ($post['seller_name'] ?? ''));
    $sellerPhone = settings_phone_display();
    $memberYear = trim((string) ($post['member_year'] ?? '1'));
    $memberSince = trim((string) ($post['member_since'] ?? ''));
    $sellerRating = (float) str_replace(',', '.', (string) ($post['seller_rating'] ?? '5'));
    $sellerReviews = max(0, (int) ($post['seller_reviews'] ?? 0));
    $sellerAvatarSeed = trim((string) ($post['seller_avatar_seed'] ?? ''));
    $sellerAvatar = trim((string) ($post['seller_avatar'] ?? ''));
    $sellerUsername = ltrim(trim((string) ($post['seller_username'] ?? '')), '@');
    if ($seller) {
        $sellerName = trim((string) ($seller['name'] ?? $sellerName));
        $sellerPhone = seller_phone($seller);
        $memberYear = (string) ($seller['member_year'] ?? $memberYear);
        $memberSince = (string) ($seller['member_since'] ?? $memberSince);
        $sellerRating = (float) ($seller['rating'] ?? $sellerRating);
        $sellerReviews = (int) ($seller['review_count'] ?? $sellerReviews);
        $likes = seller_likes($seller);
        $sellerAvatarSeed = avatar_seed_of($seller);
        $sellerAvatar = trim((string) ($seller['avatar'] ?? ''));
        $sellerUsername = seller_username($seller, $sellerName);
        // Eski satıcılara kullanıcı adı yaz
        if (empty($seller['username'])) {
            $seller['username'] = $sellerUsername;
            store_upsert('sellers', $seller);
        }
    }
    if ($sellerAvatarSeed === '') {
        $sellerAvatarSeed = avatar_random_seed();
    }
    if ($sellerUsername === '') {
        $sellerUsername = seller_username(null, $sellerName !== '' ? $sellerName : 'satici');
    }
    $sellerRating = max(1, min(5, round($sellerRating, 1)));
    // Konum ürün formundan kaldırıldı; eski kayıtlarda varsa korunur
    $city = trim((string) ($existing['city'] ?? ''));
    $district = trim((string) ($existing['district'] ?? ''));
    $neighborhood = trim((string) ($existing['neighborhood'] ?? ''));
    $cityText = trim((string) ($existing['city_text'] ?? ''));
    if ($cityText === '' && ($city !== '' || $district !== '')) {
        $cityParts = array_filter([
            $city,
            $district,
            $neighborhood !== '' ? $neighborhood . (str_contains(mb_strtolower($neighborhood), 'mah') ? '' : ' Mah.') : '',
        ]);
        $cityText = implode(' / ', $cityParts);
    }
    $listingDate = trim((string) ($post['listing_date'] ?? ''));
    if (!isset($likes)) {
        $likes = max(0, (int) ($existing['likes'] ?? 0));
    }

    if ($title === '' || $description === '' || $price <= 0) {
        return 'Ürün adı, açıklama ve fiyat zorunlu.';
    }
    if ($ibanId === '' || !$siteIban) {
        return 'Önce IBAN ekle (Admin → IBAN). Tüm ürünler otomatik o IBAN’a bağlanır.';
    }
    if ($sellerId === '' || !$seller) {
        return 'Satıcı seçmelisin. Önce Satıcılar sayfasından ekle veya otomatik üret.';
    }
    if (!$parentCat) {
        return 'Ana kategori seçmelisin. Kategoriler sayfasından ekleyebilirsin.';
    }

    $images = product_images($existing);
    $replace = !empty($post['replace_images']);
    if (!empty($_FILES['images']['name'])) {
        $newImages = save_uploaded_images($_FILES['images']);
        if ($newImages) {
            $images = $replace ? $newImages : array_values(array_merge($images, $newImages));
        }
    }
    $images = array_slice($images, 0, 6);

    $product = $existing ?: [
        'id' => new_id('p_'),
        'user_id' => $admin['id'],
        'created_at' => date('c'),
    ];

    $product['title'] = $title;
    $product['description'] = $description;
    $product['price'] = $price;
    $product['category'] = $category;
    $product['category_parent_id'] = $categoryParentId;
    $product['category_child_id'] = $categoryChildId;
    $product['category_tree'] = $categoryTree;
    $product['stock'] = $stock;
    $product['likes'] = $likes;
    $product['brand'] = $brand;
    $product['color'] = $color;
    $product['shipping'] = $shipping;
    $product['iban_id'] = $ibanId;
    if (empty($existing)) {
        $product['status'] = 'active';
    } else {
        $product['status'] = $existing['status'] ?? 'active';
    }
    $product['order_no_in_iban'] = true;
    $product['seller_id'] = $sellerId;
    $product['member_year'] = $memberYear;
    $product['member_since'] = $memberSince;
    $product['seller_name'] = $sellerName;
    $product['seller_username'] = $sellerUsername;
    $product['seller_phone'] = $sellerPhone;
    $product['seller_rating'] = $sellerRating;
    $product['seller_reviews'] = $sellerReviews;
    $product['seller_avatar_seed'] = $sellerAvatarSeed;
    $product['seller_avatar'] = $sellerAvatar;
    $product['city'] = $city;
    $product['district'] = $district;
    $product['neighborhood'] = $neighborhood;
    $product['city_text'] = $cityText;
    $product['listing_no'] = (string) ($product['listing_no'] ?? $product['id']);
    $product['listing_date'] = $listingDate !== '' ? $listingDate : ($product['listing_date'] ?? date('d.m.Y'));
    $product['images'] = $images;
    $product['image'] = $images[0] ?? ($product['image'] ?? '');
    $product['updated_at'] = date('c');

    if ($product['stock'] <= 0 && $product['status'] === 'active') {
        $product['status'] = 'sold';
    }

    return $product;
}

function product_form_render(array $product, array $cats, array $ibans, string $error = '', bool $isEdit = false): void
{
    $sellers = sellers_all();
    $sitePhone = settings_phone_display();
    $siteIban = iban_site();
    $selectedSellerId = (string) ($product['seller_id'] ?? '');
    $selectedSeller = $selectedSellerId !== '' ? seller_find($selectedSellerId) : null;
    $seedComments = $product['_seed_comments'] ?? [['name' => '', 'text' => '', 'reply_name' => 'Satıcı', 'reply_text' => '', 'followup_text' => '', 'followup_reply' => '']];
    if (!is_array($seedComments) || !$seedComments) {
        $seedComments = [['name' => '', 'text' => '', 'reply_name' => 'Satıcı', 'reply_text' => '', 'followup_text' => '', 'followup_reply' => '']];
    }
    $currentImages = $isEdit ? product_image_urls($product) : [];
    $existingCommentCount = $isEdit ? count(comments_for_product((string) ($product['id'] ?? ''))) : 0;
    ?>
    <?php if ($error): ?><div class="admin-alert error"><?= e($error) ?></div><?php endif; ?>
    <?php if (!$siteIban): ?>
        <div class="admin-alert error">
            Önce site IBAN’ı ekle. <a href="<?= e(url('admin/ibanlar.php')) ?>">IBAN →</a>
        </div>
    <?php endif; ?>
    <?php if (!$sellers): ?>
        <div class="admin-alert error">
            Önce satıcı ekle veya otomatik üret. <a href="<?= e(url('admin/saticilar.php')) ?>">Satıcılar →</a>
        </div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data" class="admin-form admin-product-form" id="product-form">
        <?php if ($isEdit): ?>
            <input type="hidden" name="id" value="<?= e((string) ($product['id'] ?? '')) ?>">
        <?php endif; ?>

        <label>Ürün Adı
            <input type="text" name="title" required value="<?= e($product['title'] ?? '') ?>" placeholder="Ürün İsim">
        </label>
        <label>Marka <span class="hint" style="font-weight:500">(vitrin kartında üstte görünür)</span>
            <input type="text" name="brand" value="<?= e($product['brand'] ?? '') ?>" placeholder="Boş = kategori adı / Diğer">
        </label>

        <?php
        $selColor = (string) ($product['color'] ?? '');
        $selShipping = product_shipping($product);
        ?>
        <fieldset class="admin-color-field">
            <legend>Renk</legend>
            <p class="hint" style="margin-top:0">İlanda yuvarlak renk olarak görünür. Yoksa “Renk yok” seç.</p>
            <div class="admin-color-grid">
                <label class="admin-color-opt <?= $selColor === '' ? 'is-on' : '' ?>">
                    <input type="radio" name="color" value="" <?= $selColor === '' ? 'checked' : '' ?>>
                    <span class="admin-color-dot is-none" aria-hidden="true"></span>
                    <span>Renk yok</span>
                </label>
                <?php foreach (product_colors() as $slug => $c):
                    $dotStyle = str_starts_with($c['hex'], 'linear')
                        ? 'background:' . $c['hex']
                        : 'background-color:' . $c['hex'];
                    $needBorder = in_array($slug, ['beyaz', 'krem', 'bej', 'gumus'], true);
                    ?>
                    <label class="admin-color-opt <?= $selColor === $slug ? 'is-on' : '' ?>">
                        <input type="radio" name="color" value="<?= e($slug) ?>" <?= $selColor === $slug ? 'checked' : '' ?>>
                        <span class="admin-color-dot" style="<?= e($dotStyle) ?><?= $needBorder ? ';box-shadow:inset 0 0 0 1px rgba(0,0,0,.15)' : '' ?>" aria-hidden="true"></span>
                        <span><?= e($c['label']) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
        </fieldset>

        <fieldset class="admin-ship-field">
            <legend>Kargo</legend>
            <div class="admin-ship-grid">
                <label class="admin-ship-opt <?= $selShipping === 'free' ? 'is-on' : '' ?>">
                    <input type="radio" name="shipping" value="free" <?= $selShipping === 'free' ? 'checked' : '' ?>>
                    <strong>Ücretsiz Kargo</strong>
                    <span>Satıcı öder — ilanda sarı rozet</span>
                </label>
                <label class="admin-ship-opt <?= $selShipping === 'buyer' ? 'is-on' : '' ?>">
                    <input type="radio" name="shipping" value="buyer" <?= $selShipping === 'buyer' ? 'checked' : '' ?>>
                    <strong>Alıcı Öder</strong>
                    <span>Kargo ücreti alıcıya ait</span>
                </label>
            </div>
        </fieldset>

        <label>Satıcı
            <select name="seller_id" id="product-seller" required data-seller-select <?= !$sellers ? 'disabled' : '' ?>>
                <option value="">Satıcı seçiniz</option>
                <?php foreach ($sellers as $s): ?>
                    <option value="<?= e((string) $s['id']) ?>"
                        data-name="<?= e($s['name'] ?? '') ?>"
                        data-phone="<?= e(seller_phone($s)) ?>"
                        data-year="<?= e((string) ($s['member_year'] ?? '1')) ?>"
                        data-since="<?= e($s['member_since'] ?? '') ?>"
                        data-rating="<?= e((string) ($s['rating'] ?? '5')) ?>"
                        data-reviews="<?= (int) ($s['review_count'] ?? 0) ?>"
                        data-likes="<?= seller_likes($s) ?>"
                        data-avatar="<?= e(avatar_seed_of($s)) ?>"
                        data-avatar-file="<?= e((string) ($s['avatar'] ?? '')) ?>"
                        data-username="<?= e(seller_username($s)) ?>"
                        <?= $selectedSellerId === ($s['id'] ?? '') ? 'selected' : '' ?>>
                        <?= e(seller_label($s)) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <p class="hint"><a href="<?= e(url('admin/saticilar.php')) ?>">Satıcı yönet / otomatik üret</a> — beğeni, yıldız ve üyelik satıcıdan gelir.</p>
        </label>

        <div class="admin-iban-auto" data-seller-preview data-site-phone="<?= e($sitePhone) ?>">
            <div><span>Satıcı</span><strong data-seller-name><?php
                $prevName = $selectedSeller['name'] ?? $product['seller_name'] ?? '—';
                $prevUser = $selectedSeller ? seller_handle($selectedSeller) : (!empty($product['seller_username']) ? '@' . ltrim((string) $product['seller_username'], '@') : '');
                echo e($prevName . ($prevUser !== '' ? ' · ' . $prevUser : ''));
            ?></strong></div>
            <div><span>Telefon</span><strong data-seller-phone><?php
                $prevPhone = $selectedSeller ? seller_phone($selectedSeller) : $sitePhone;
                echo e($prevPhone !== '' ? $prevPhone : '—');
            ?></strong></div>
            <div><span>Yıldız / Beğeni / Üyelik</span><strong data-seller-meta><?php
                $r = $selectedSeller['rating'] ?? $product['seller_rating'] ?? '';
                $likesPrev = $selectedSeller ? seller_likes($selectedSeller) : (int) ($product['likes'] ?? 0);
                $y = $selectedSeller['member_year'] ?? $product['member_year'] ?? '';
                $since = $selectedSeller['member_since'] ?? $product['member_since'] ?? '';
                echo e(($r !== '' ? '★ ' . $r : '—') . ' · ♡ ' . $likesPrev . ($y !== '' ? ' · ' . $y . '. yıl' : '') . ($since !== '' ? ' · ' . $since : ''));
            ?></strong></div>
        </div>
        <input type="hidden" name="seller_name" data-seller-name-input value="<?= e($product['seller_name'] ?? '') ?>">
        <input type="hidden" name="seller_phone" data-seller-phone-input value="<?= e($selectedSeller ? seller_phone($selectedSeller) : $sitePhone) ?>">
        <input type="hidden" name="member_year" data-seller-year-input value="<?= e((string) ($product['member_year'] ?? '1')) ?>">
        <input type="hidden" name="member_since" data-seller-since-input value="<?= e($product['member_since'] ?? '') ?>">
        <input type="hidden" name="seller_rating" data-seller-rating-input value="<?= e((string) ($product['seller_rating'] ?? '5')) ?>">
        <input type="hidden" name="seller_reviews" data-seller-reviews-input value="<?= (int) ($product['seller_reviews'] ?? 0) ?>">
        <input type="hidden" name="seller_avatar_seed" data-seller-avatar-input value="<?= e((string) ($product['seller_avatar_seed'] ?? ($selectedSeller ? avatar_seed_of($selectedSeller) : ''))) ?>">
        <input type="hidden" name="seller_avatar" data-seller-avatar-file-input value="<?= e((string) ($product['seller_avatar'] ?? ($selectedSeller['avatar'] ?? '') ?? '')) ?>">
        <input type="hidden" name="seller_username" data-seller-username-input value="<?= e((string) ($product['seller_username'] ?? ($selectedSeller ? seller_username($selectedSeller) : ''))) ?>">

        <label>Resimler (Max 6 adet seçin)
            <input type="file" name="images[]" accept="image/*" multiple data-max-files="6">
            <p class="hint">En fazla 6 fotoğraf. İlk fotoğraf kapak olur.</p>
        </label>
        <?php if ($isEdit && $currentImages && ($currentImages[0] ?? '') !== 'assets/img/placeholder.svg'): ?>
            <div class="admin-thumbs-preview">
                <?php foreach ($currentImages as $src): ?>
                    <img src="<?= e($src) ?>" alt="">
                <?php endforeach; ?>
            </div>
            <label style="display:flex;align-items:center;gap:0.5rem;font-weight:600">
                <input type="checkbox" name="replace_images" value="1" style="width:auto">
                Yüklenenlerle tüm fotoğrafları değiştir
            </label>
        <?php endif; ?>

        <label>İlan Tarihi
            <input type="text" name="listing_date" value="<?= e($product['listing_date'] ?? date('d.m.Y')) ?>" placeholder="gg.aa.yyyy">
        </label>

        <?php
        $catRoots = categories_roots();
        $selParentId = (string) ($product['category_parent_id'] ?? '');
        $selChildId = (string) ($product['category_child_id'] ?? '');
        if ($selParentId === '' && !empty($product['category'])) {
            $bySlug = category_find_by_slug((string) $product['category']);
            if ($bySlug) {
                if (!empty($bySlug['parent_id'])) {
                    $selParentId = (string) $bySlug['parent_id'];
                    $selChildId = (string) ($bySlug['id'] ?? '');
                } else {
                    $selParentId = (string) ($bySlug['id'] ?? '');
                }
            }
        }
        $catTreeJson = [];
        foreach ($catRoots as $r) {
            $kids = [];
            foreach (categories_children((string) $r['id']) as $k) {
                $kids[] = ['id' => $k['id'], 'name' => $k['name'], 'slug' => $k['slug']];
            }
            $catTreeJson[] = [
                'id' => $r['id'],
                'name' => $r['name'],
                'slug' => $r['slug'],
                'children' => $kids,
            ];
        }
        ?>
        <?php if (!$catRoots): ?>
            <div class="admin-alert error">
                Önce kategori ekle. <a href="<?= e(url('admin/kategoriler.php')) ?>">Kategoriler →</a>
            </div>
        <?php endif; ?>
        <div class="admin-form-row" data-category-picker
             data-cat-tree="<?= e(json_encode($catTreeJson, JSON_UNESCAPED_UNICODE) ?: '[]') ?>"
             data-selected-child="<?= e($selChildId) ?>">
            <label>Ana kategori
                <select name="category_parent_id" id="category-parent" required data-cat-parent <?= !$catRoots ? 'disabled' : '' ?>>
                    <option value="">Seçiniz</option>
                    <?php foreach ($catRoots as $r): ?>
                        <option value="<?= e((string) $r['id']) ?>"
                            data-name="<?= e($r['name'] ?? '') ?>"
                            <?= $selParentId === ($r['id'] ?? '') ? 'selected' : '' ?>>
                            <?= e($r['name'] ?? '') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>
            <label>Alt kategori
                <select name="category_child_id" id="category-child" data-cat-child data-selected="<?= e($selChildId) ?>">
                    <option value="">Önce ana kategori</option>
                </select>
            </label>
        </div>
        <input type="hidden" name="category" data-cat-slug value="<?= e((string) ($product['category'] ?? '')) ?>">
        <label>Kategori yolu
            <input type="text" name="category_tree" data-cat-tree-text readonly
                   value="<?= e($product['category_tree'] ?? '') ?>"
                   placeholder="Ana > Alt (otomatik)">
            <p class="hint"><a href="<?= e(url('admin/kategoriler.php')) ?>">Kategorileri düzenle</a></p>
        </label>

        <label>Ürün Fiyat
            <input type="text" name="price" required inputmode="numeric" pattern="[0-9]*"
                   value="<?= e(isset($product['price']) ? (string) (int) $product['price'] : '') ?>"
                   placeholder="5000 (nokta falan olmasın)">
        </label>

        <label>Stok
            <input type="number" min="0" name="stock" value="<?= (int) ($product['stock'] ?? 1) ?>">
        </label>

        <?php if ($siteIban): ?>
            <div class="admin-iban-auto">
                <div>
                    <span>Ödeme IBAN</span>
                    <strong><?= e(iban_label($siteIban)) ?> · <?= e((string) ($siteIban['account_name'] ?? '')) ?></strong>
                </div>
                <p class="hint" style="margin:0.35rem 0 0">Tüm ürünler aynı IBAN’ı kullanır. <a href="<?= e(url('admin/ibanlar.php')) ?>">Değiştir</a></p>
            </div>
        <?php endif; ?>

        <label>Ürün Açıklaması
            <textarea name="description" rows="5" required placeholder="Ürün açıklaması..."><?= e($product['description'] ?? '') ?></textarea>
        </label>

        <div class="admin-features" data-seed-comments data-yorum-api="<?= e(url('admin/api-yorum.php')) ?>">
            <div class="admin-panel-head" style="margin-bottom:0.65rem">
                <h2 style="font-size:1rem;margin:0">Rastgele Yorumlar</h2>
                <div style="display:flex;gap:0.4rem;flex-wrap:wrap">
                    <button type="button" class="admin-btn ghost sm" data-comment-random>Rastgele üret</button>
                    <button type="button" class="admin-btn ghost sm" data-comment-add>+ Yorum</button>
                </div>
            </div>
            <p class="hint" style="margin-top:0">
                Önce ürün adını yaz → <strong>Rastgele üret</strong>. Bazı diyaloglarda 2. soru–cevap (devam) da gelir; ürünle ilgili ve doğal yazılır.
                <?php if ($isEdit): ?>Şu an vitrinde <?= (int) $existingCommentCount ?> yorum var.<?php endif; ?>
            </p>
            <div data-comment-rows>
                <?php foreach ($seedComments as $c): ?>
                    <div class="admin-comment-thread" data-comment-thread>
                        <div class="admin-feature-row">
                            <input type="text" name="comment_name[]" value="<?= e($c['name'] ?? '') ?>" placeholder="Müşteri adı">
                            <input type="text" name="comment_text[]" value="<?= e($c['text'] ?? '') ?>" placeholder="Soru / yorum">
                            <button type="button" class="admin-btn danger sm" data-comment-remove>Sil</button>
                        </div>
                        <div class="admin-feature-row admin-reply-row">
                            <input type="text" name="reply_name[]" value="<?= e($c['reply_name'] ?? 'Satıcı') ?>" placeholder="Cevaplayan">
                            <input type="text" name="reply_text[]" value="<?= e($c['reply_text'] ?? '') ?>" placeholder="@isim cevap...">
                            <span class="admin-reply-tag">Cevap</span>
                        </div>
                        <div class="admin-feature-row admin-reply-row">
                            <input type="text" name="followup_text[]" value="<?= e($c['followup_text'] ?? '') ?>" placeholder="2. soru (opsiyonel)">
                            <input type="text" name="followup_reply[]" value="<?= e($c['followup_reply'] ?? '') ?>" placeholder="@isim 2. cevap...">
                            <span class="admin-reply-tag">Devam</span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <button class="admin-btn" type="submit" <?= (!$siteIban || !$sellers || !$catRoots) ? 'disabled' : '' ?>>
            <?= $isEdit ? 'Ürünü Kaydet' : 'Ürünü Yayınla' ?>
        </button>
    </form>
    <?php
}
