<?php
declare(strict_types=1);

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

require_admin();

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

    if ($action === 'save') {
        $id = trim((string) ($_POST['id'] ?? ''));
        $name = trim((string) ($_POST['name'] ?? ''));
        $phone = trim((string) ($_POST['phone'] ?? ''));
        $usernameIn = seller_normalize_username((string) ($_POST['username'] ?? ''));
        $rating = (float) str_replace(',', '.', (string) ($_POST['rating'] ?? '5'));
        $rating = max(1, min(5, round($rating, 1)));
        $reviewCount = max(0, (int) ($_POST['review_count'] ?? 0));
        $likes = max(0, (int) ($_POST['likes'] ?? 0));
        $followers = max(0, (int) ($_POST['followers'] ?? 0));
        $following = max(0, (int) ($_POST['following'] ?? 0));
        $memberYear = max(1, min(15, (int) ($_POST['member_year'] ?? 1)));
        $memberSince = trim((string) ($_POST['member_since'] ?? ''));
        $removeAvatar = !empty($_POST['remove_avatar']);

        if ($name === '') {
            flash('error', 'Satıcı adı zorunlu.');
            redirect(url('admin/saticilar.php' . ($id !== '' ? '?edit=' . urlencode($id) : '') . '#seller-edit'));
        }

        $item = $id !== '' ? (seller_find($id) ?? ['id' => $id, 'created_at' => date('c')]) : [
            'id' => new_id('s_'),
            'created_at' => date('c'),
            'auto' => false,
            'avatar_seed' => avatar_random_seed(),
        ];
        if (empty($item['avatar_seed'])) {
            $item['avatar_seed'] = avatar_random_seed();
        }

        if ($usernameIn === '') {
            $usernameIn = !empty($item['username'])
                ? seller_normalize_username((string) $item['username'])
                : seller_make_username($name);
        }
        if (strlen($usernameIn) < 3) {
            flash('error', 'Kullanıcı adı en az 3 karakter olmalı.');
            redirect(url('admin/saticilar.php' . ($id !== '' ? '?edit=' . urlencode($id) : '') . '#seller-edit'));
        }
        if (seller_username_taken($usernameIn, (string) ($item['id'] ?? ''))) {
            flash('error', 'Bu kullanıcı adı başka satıcıda var. Başka bir tane seç.');
            redirect(url('admin/saticilar.php' . ($id !== '' ? '?edit=' . urlencode($id) : '') . '#seller-edit'));
        }

        $item['name'] = $name;
        $item['username'] = $usernameIn;
        $item['phone'] = $phone !== '' ? $phone : settings_phone_display();
        $item['rating'] = $rating;
        $item['review_count'] = $reviewCount;
        $item['likes'] = $likes;
        $item['followers'] = $followers;
        $item['following'] = $following;
        $item['member_year'] = (string) $memberYear;
        $item['member_since'] = $memberSince !== '' ? $memberSince : ('Ocak ' . ((int) date('Y') - $memberYear));
        $item['updated_at'] = date('c');

        if ($removeAvatar) {
            $item['avatar'] = '';
        }
        if (!empty($_FILES['avatar']['name'])) {
            $saved = save_seller_avatar_upload($_FILES['avatar'], 256);
            if ($saved === false) {
                flash('error', 'Profil resmi yüklenemedi. PNG/JPG dene.');
                redirect(url('admin/saticilar.php' . ($id !== '' ? '?edit=' . urlencode($id) : '')));
            }
            $item['avatar'] = $saved;
        }

        store_upsert('sellers', $item);
        flash('success', $id !== '' ? 'Satıcı güncellendi.' : 'Satıcı eklendi.');
        redirect(url('admin/saticilar.php'));
    }

    if ($action === 'generate') {
        $count = max(1, min(40, (int) ($_POST['count'] ?? 10)));
        $created = seller_generate_many($count);
        flash('success', count($created) . ' otomatik satıcı eklendi (yıldız + üyelik tarihi hazır).');
        redirect(url('admin/saticilar.php'));
    }

    if ($action === 'delete') {
        store_delete('sellers', (string) ($_POST['id'] ?? ''));
        flash('success', 'Satıcı silindi.');
        redirect(url('admin/saticilar.php'));
    }
}

$sellers = sellers_all();
$sitePhone = settings_phone_display();
$editId = (string) ($_GET['edit'] ?? '');
$edit = $editId !== '' ? seller_find($editId) : null;
$editPhone = $edit ? seller_phone($edit) : $sitePhone;
$hasCustomAvatar = $edit && seller_avatar_url($edit) !== '';

admin_layout_start('Satıcılar', 'sellers');
?>

<section class="admin-panel">
    <div class="admin-panel-head">
        <h2>Otomatik satıcı üret</h2>
    </div>
    <p class="hint">İsim, profil resmi, ★ puan, beğeni, yorum sayısı ve üyelik tarihi otomatik gelir. Telefon varsayılan: Site Ayarları<?= $sitePhone !== '' ? ' (<strong>' . e($sitePhone) . '</strong>)' : '' ?> — düzenlerken değiştirebilirsin.</p>
    <form method="post" class="admin-form" style="max-width:420px">
        <input type="hidden" name="action" value="generate">
        <label>Kaç satıcı
            <input type="number" name="count" min="1" max="40" value="10">
        </label>
        <button class="admin-btn" type="submit">Rastgele Satıcı Üret</button>
    </form>
</section>

<section class="admin-panel" id="seller-edit">
    <h2><?= $edit ? 'Satıcı düzenle' : 'Manuel satıcı ekle' ?></h2>
    <form method="post" enctype="multipart/form-data" class="admin-form">
        <input type="hidden" name="action" value="save">
        <?php if ($edit): ?>
            <input type="hidden" name="id" value="<?= e((string) $edit['id']) ?>">
        <?php endif; ?>

        <div class="admin-form-row">
            <label>Ad Soyad
                <input type="text" name="name" required value="<?= e($edit['name'] ?? '') ?>" placeholder="Hasan Özgü">
            </label>
            <label>Telefon
                <input type="text" name="phone" value="<?= e($editPhone) ?>" placeholder="0 (555) 555 55 55">
            </label>
        </div>
        <label>Kullanıcı adı
            <div style="display:flex;align-items:center;gap:0.25rem">
                <span style="font-weight:800;color:#3d7a45">@</span>
                <input type="text" name="username" value="<?= e($edit ? seller_username($edit) : '') ?>"
                       placeholder="mehmettunc13234" pattern="[A-Za-z0-9._\-ğüşıöçĞÜŞİÖÇ]+"
                       autocomplete="off" style="flex:1">
            </div>
            <p class="hint">Sitede @kullaniciadi olarak görünür. Boş bırakırsan otomatik üretilir / mevcut kalır.</p>
        </label>

        <div class="bank-logo-box">
            <p class="bank-logo-box-title">Profil resmi</p>
            <div class="bank-logo-preview">
                <div style="width:72px;height:72px;flex-shrink:0" data-seller-avatar-preview>
                    <?= $edit ? seller_avatar_html($edit, 'avatar', (string) ($edit['name'] ?? '')) : avatar_img_html('preview', 'avatar', '', 'seller') ?>
                </div>
                <div>
                    <strong><?= $hasCustomAvatar ? 'Yüklediğin fotoğraf' : 'Mevcut profil' ?></strong>
                    <p class="hint" style="margin:0.2rem 0 0">PNG/JPG yükle — otomatik kare 256px yapılır.</p>
                </div>
            </div>
            <label class="bank-logo-file">
                <span>Profil resmi seç / değiştir</span>
                <input type="file" name="avatar" accept="image/png,image/jpeg,image/webp,image/gif" data-seller-avatar-input>
            </label>
            <?php if ($hasCustomAvatar): ?>
                <label style="display:flex;align-items:center;gap:0.45rem;font-weight:600;margin:0">
                    <input type="checkbox" name="remove_avatar" value="1" style="width:auto">
                    Yüklenen profil resmini kaldır
                </label>
            <?php endif; ?>
        </div>

        <div class="admin-form-row">
            <label>Yıldız (1–5)
                <input type="number" step="0.1" min="1" max="5" name="rating" value="<?= e((string) ($edit['rating'] ?? '4.8')) ?>">
            </label>
            <label>Yorum / değerlendirme sayısı
                <input type="number" min="0" name="review_count" value="<?= (int) ($edit['review_count'] ?? 12) ?>">
            </label>
        </div>
        <label>Beğeni sayısı
            <input type="number" min="0" name="likes" value="<?= (int) ($edit['likes'] ?? 120) ?>">
            <p class="hint">Bu satıcının tüm ürünlerinde aynı beğeni sayısı görünür.</p>
        </label>
        <div class="admin-form-row">
            <label>Takipçi sayısı
                <input type="number" min="0" name="followers" value="<?= $edit ? seller_followers($edit) : 350 ?>">
            </label>
            <label>Takip ettiği
                <input type="number" min="0" name="following" value="<?= $edit ? seller_following($edit) : 12 ?>">
            </label>
        </div>
        <p class="hint" style="margin-top:-0.35rem">Mağaza profilinde “Takipçi / Takip Ettiği” olarak görünür.</p>
        <div class="admin-form-row">
            <label>Üyelik yılı
                <input type="number" min="1" max="15" name="member_year" value="<?= (int) ($edit['member_year'] ?? 2) ?>">
            </label>
            <label>Üyelik tarihi
                <input type="text" name="member_since" value="<?= e($edit['member_since'] ?? '') ?>" placeholder="Haziran 2022">
            </label>
        </div>
        <div style="display:flex;gap:0.5rem;flex-wrap:wrap">
            <button class="admin-btn" type="submit"><?= $edit ? 'Güncelle' : 'Satıcı Ekle' ?></button>
            <?php if ($edit): ?>
                <a class="admin-btn ghost" href="<?= e(url('admin/saticilar.php')) ?>">İptal</a>
            <?php endif; ?>
        </div>
    </form>
</section>

<section class="admin-panel">
    <h2>Satıcı listesi (<?= count($sellers) ?>)</h2>
    <?php if (!$sellers): ?>
        <p class="hint">Henüz satıcı yok. Yukarıdan otomatik üret veya manuel ekle.</p>
    <?php endif; ?>
    <?php foreach ($sellers as $s): ?>
        <div class="admin-order">
            <div class="admin-order-head" style="align-items:center;gap:0.65rem">
                <div style="width:40px;height:40px;flex-shrink:0"><?= seller_avatar_html($s, 'avatar', (string) ($s['name'] ?? '')) ?></div>
                <strong><?= e($s['name'] ?? '') ?></strong>
                <span class="admin-badge paid">★ <?= e(number_format((float) ($s['rating'] ?? 5), 1, '.', '')) ?> (<?= (int) ($s['review_count'] ?? 0) ?>) · ♡ <?= seller_likes($s) ?> · <?= number_format(seller_followers($s), 0, ',', '.') ?> takipçi</span>
            </div>
            <p><strong><?= e(seller_handle($s)) ?></strong> · <?= e(seller_phone($s) !== '' ? seller_phone($s) : '—') ?> · ♡ <?= seller_likes($s) ?> · <?= number_format(seller_followers($s), 0, ',', '.') ?> takipçi · <?= e((string) ($s['member_year'] ?? '1')) ?>. yıl · <?= e($s['member_since'] ?? '') ?></p>
            <?php if (!empty($s['auto'])): ?><p class="hint">Otomatik üretildi</p><?php endif; ?>
            <div style="display:flex;gap:0.4rem;flex-wrap:wrap;margin-top:0.5rem">
                <a class="admin-btn ghost sm" href="<?= e(url('admin/saticilar.php?edit=' . urlencode((string) $s['id']) . '#seller-edit')) ?>">Düzenle</a>
                <form method="post" onsubmit="return confirm('Satıcı silinsin mi?')">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= e((string) $s['id']) ?>">
                    <button class="admin-btn danger sm" type="submit">Sil</button>
                </form>
            </div>
        </div>
    <?php endforeach; ?>
</section>

<script>
(() => {
  const inp = document.querySelector('[data-seller-avatar-input]');
  const box = document.querySelector('[data-seller-avatar-preview]');
  inp?.addEventListener('change', () => {
    const file = inp.files && inp.files[0];
    if (!file || !box) return;
    const url = URL.createObjectURL(file);
    box.innerHTML = '<div class="avatar diamond has-photo"><span class="diamond-inner"><img src="' + url + '" alt="" width="72" height="72"></span></div>';
  });
})();
</script>

<?php admin_layout_end(); ?>
