<?php
declare(strict_types=1);

function sellers_all(): array
{
    $items = store_read('sellers');
    usort($items, static fn(array $a, array $b): int => strcmp($a['name'] ?? '', $b['name'] ?? ''));
    return $items;
}

function seller_find(string $id): ?array
{
    if ($id === '') {
        return null;
    }
    return store_find('sellers', $id);
}

/** Satıcı telefonu; boşsa Site Ayarları numarası. */
function seller_phone(?array $seller = null): string
{
    if ($seller) {
        $phone = trim((string) ($seller['phone'] ?? ''));
        if ($phone !== '') {
            return $phone;
        }
    }
    return settings_phone_display();
}

function seller_avatar_url(?array $seller): string
{
    if (!$seller) {
        return '';
    }
    $file = trim((string) ($seller['avatar'] ?? ''));
    if ($file === '') {
        return '';
    }
    $path = BASE_PATH . '/uploads/avatars/' . ltrim($file, '/');
    if (!is_file($path)) {
        return '';
    }
    return url('uploads/avatars/' . ltrim($file, '/'));
}

function seller_avatar_html(?array $seller, string $class = 'avatar', string $alt = ''): string
{
    $custom = seller_avatar_url($seller);
    if ($custom !== '') {
        $name = $alt !== '' ? $alt : (string) ($seller['name'] ?? 'Satıcı');
        return '<div class="' . e($class) . ' diamond has-photo" aria-hidden="true">'
            . '<span class="diamond-inner">'
            . '<img src="' . e($custom) . '" alt="' . e($name) . '" loading="lazy" width="48" height="48">'
            . '</span></div>';
    }
    $seed = avatar_seed_of($seller ?? [], (string) ($seller['name'] ?? 'satici'));
    return avatar_img_html($seed, $class, $alt !== '' ? $alt : (string) ($seller['name'] ?? ''), 'seller');
}

/** Profil fotoğrafını 256px kare PNG yapar. */
function save_seller_avatar_upload(array $file, int $size = 256): string|false
{
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        return false;
    }
    $dir = BASE_PATH . '/uploads/avatars';
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }
    if (!function_exists('imagecreatetruecolor')) {
        return save_uploaded_image($file, $dir, 'a_');
    }

    $tmp = (string) ($file['tmp_name'] ?? '');
    if ($tmp === '' || !is_file($tmp)) {
        return false;
    }
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = (string) $finfo->file($tmp);
    $src = match ($mime) {
        'image/jpeg' => @imagecreatefromjpeg($tmp),
        'image/png' => @imagecreatefrompng($tmp),
        'image/webp' => function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($tmp) : false,
        'image/gif' => @imagecreatefromgif($tmp),
        default => false,
    };
    if ($src === false) {
        return false;
    }
    $sw = imagesx($src);
    $sh = imagesy($src);
    if ($sw < 1 || $sh < 1) {
        imagedestroy($src);
        return false;
    }

    $size = max(64, min(512, $size));
    $dst = imagecreatetruecolor($size, $size);
    if ($dst === false) {
        imagedestroy($src);
        return false;
    }
    // Cover crop (ortadan kare kes)
    $side = min($sw, $sh);
    $sx = (int) (($sw - $side) / 2);
    $sy = (int) (($sh - $side) / 2);
    imagecopyresampled($dst, $src, 0, 0, $sx, $sy, $size, $size, $side, $side);
    imagedestroy($src);

    $name = 'a_' . bin2hex(random_bytes(8)) . '.png';
    $ok = imagepng($dst, $dir . '/' . $name, 6);
    imagedestroy($dst);
    return $ok ? $name : false;
}

/** Mehmet Tunç → mehmettunc */
function seller_slugify_name(string $name): string
{
    $map = [
        'ş' => 's', 'Ş' => 's', 'ı' => 'i', 'İ' => 'i', 'I' => 'i',
        'ğ' => 'g', 'Ğ' => 'g', 'ü' => 'u', 'Ü' => 'u',
        'ö' => 'o', 'Ö' => 'o', 'ç' => 'c', 'Ç' => 'c',
    ];
    $s = strtr($name, $map);
    $s = mb_strtolower($s);
    $s = preg_replace('/[^a-z0-9]+/u', '', $s) ?? '';
    return $s !== '' ? $s : 'satici';
}

function seller_make_username(string $name): string
{
    return seller_slugify_name($name) . (string) random_int(1000, 99999);
}

/** Formdan gelen kullanıcı adını temizler: @mehmet.tunc → mehmettunc */
function seller_normalize_username(string $username): string
{
    $u = ltrim(trim($username), '@');
    $u = seller_slugify_name($u);
    return $u;
}

function seller_username_taken(string $username, string $exceptId = ''): bool
{
    $username = seller_normalize_username($username);
    if ($username === '') {
        return false;
    }
    foreach (sellers_all() as $s) {
        if (($s['id'] ?? '') === $exceptId) {
            continue;
        }
        if (seller_username($s) === $username) {
            return true;
        }
    }
    return false;
}

/** Kullanıcı adı (başında @ yok): mehmettunc13234 */
function seller_username(?array $seller = null, string $fallbackName = ''): string
{
    if ($seller) {
        $u = trim((string) ($seller['username'] ?? ''));
        $u = ltrim($u, '@');
        if ($u !== '') {
            return $u;
        }
        $base = seller_slugify_name((string) ($seller['name'] ?? $fallbackName));
        $idDigits = preg_replace('/\D+/', '', (string) ($seller['id'] ?? '')) ?? '';
        $suffix = $idDigits !== '' ? substr($idDigits, -4) : '1000';
        return $base . $suffix;
    }
    $base = seller_slugify_name($fallbackName !== '' ? $fallbackName : 'satici');
    return $base . '1000';
}

function seller_handle(?array $seller = null, string $fallbackName = ''): string
{
    return '@' . seller_username($seller, $fallbackName);
}

/** Profilde gösterilen üyelik metni (saat ikonu yanında). */
function seller_member_label(?array $seller): string
{
    if (!$seller) {
        return 'Bölgesel satış';
    }
    $since = trim((string) ($seller['member_since'] ?? ''));
    if ($since !== '' && strcasecmp($since, 'null') !== 0) {
        return $since;
    }
    $year = (int) ($seller['member_year'] ?? 0);
    if ($year > 0) {
        return $year . '. yıl üye';
    }
    return 'Üye';
}

/** Takipçi sayısı — kayıttaysa o, yoksa id’den stabil demo. */
function seller_followers(?array $seller): int
{
    if (!$seller) {
        return 0;
    }
    if (array_key_exists('followers', $seller)) {
        return max(0, (int) $seller['followers']);
    }
    $id = (string) ($seller['id'] ?? '');
    $n = abs(crc32($id . ':followers'));
    return 120 + ($n % 4800);
}

/** Takip ettiği sayısı — kayıttaysa o, yoksa id’den stabil demo. */
function seller_following(?array $seller): int
{
    if (!$seller) {
        return 0;
    }
    if (array_key_exists('following', $seller)) {
        return max(0, (int) $seller['following']);
    }
    $id = (string) ($seller['id'] ?? '');
    $n = abs(crc32($id . ':following'));
    return $n % 85;
}

/** Başarılı satış sayısı — gerçek satılan varsa o, yoksa stabil demo sayı. */
function seller_successful_sales(?array $seller, int $realSold = 0): int
{
    if ($realSold > 0) {
        return $realSold;
    }
    if (!$seller) {
        return 0;
    }
    $stored = (int) ($seller['successful_sales'] ?? 0);
    if ($stored > 0) {
        return $stored;
    }
    $id = (string) ($seller['id'] ?? '');
    return 5 + (abs(crc32($id . ':sales')) % 95);
}

function seller_likes(?array $seller): int
{
    if (!is_array($seller)) {
        return 0;
    }
    return max(0, (int) ($seller['likes'] ?? 0));
}

function seller_label(array $seller): string
{
    $name = trim((string) ($seller['name'] ?? 'Satıcı'));
    $handle = seller_handle($seller);
    $stars = number_format((float) ($seller['rating'] ?? 5), 1, '.', '');
    return $name . ' · ' . $handle . ' · ★' . $stars;
}

/** @return list<string> */
function seller_first_names(): array
{
    return ['Ayşe', 'Mehmet', 'Fatma', 'Hasan', 'Zeynep', 'Ali', 'Elif', 'Mustafa', 'Hatice', 'Hüseyin', 'Emine', 'İbrahim', 'Selin', 'Murat', 'Deniz', 'Burak', 'Canan', 'Kemal', 'Seda', 'Onur', 'Gül', 'Yusuf', 'Merve', 'Serkan', 'Derya'];
}

/** @return list<string> */
function seller_last_names(): array
{
    return ['Yılmaz', 'Kaya', 'Demir', 'Çelik', 'Şahin', 'Yıldız', 'Öztürk', 'Aydın', 'Özdemir', 'Arslan', 'Doğan', 'Kılıç', 'Aslan', 'Çetin', 'Kara', 'Koç', 'Kurt', 'Özkan', 'Şimşek', 'Erdoğan', 'Aksoy', 'Polat', 'Güneş', 'Bulut', 'Acar'];
}

function seller_random_since(): array
{
    $months = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'];
    $year = random_int((int) date('Y') - 6, (int) date('Y') - 1);
    $month = $months[array_rand($months)];
    $memberYear = max(1, (int) date('Y') - $year);
    return [
        'member_since' => $month . ' ' . $year,
        'member_year' => (string) $memberYear,
    ];
}

function seller_generate_one(): array
{
    $first = seller_first_names()[array_rand(seller_first_names())];
    $last = seller_last_names()[array_rand(seller_last_names())];
    $since = seller_random_since();
    $rating = [4.8, 5.0][random_int(0, 1)];
    $reviews = random_int(3, 180);
    $likes = random_int(40, 4200);
    $followers = random_int(120, 4900);
    $following = random_int(0, 84);

    $name = $first . ' ' . $last;
    $id = new_id('s_');
    return [
        'id' => $id,
        'name' => $name,
        'username' => seller_make_username($name),
        'phone' => settings_phone_display(),
        'avatar_seed' => avatar_random_seed(),
        'rating' => $rating,
        'review_count' => $reviews,
        'likes' => $likes,
        'followers' => $followers,
        'following' => $following,
        'member_year' => $since['member_year'],
        'member_since' => $since['member_since'],
        'auto' => true,
        'created_at' => date('c'),
    ];
}

function seller_generate_many(int $count): array
{
    $count = max(1, min(50, $count));
    $created = [];
    for ($i = 0; $i < $count; $i++) {
        $seller = seller_generate_one();
        store_upsert('sellers', $seller);
        $created[] = $seller;
    }
    return $created;
}
