<?php
declare(strict_types=1);

/** @return array<string,string> key => görünen ad */
function bank_options(): array
{
    return [
        'ziraat' => 'Ziraat Bankası',
        'isbank' => 'İş Bankası',
        'garanti' => 'Garanti BBVA',
        'yapikredi' => 'Yapı Kredi',
        'akbank' => 'Akbank',
        'halkbank' => 'Halkbank',
        'vakifbank' => 'VakıfBank',
        'qnb' => 'QNB',
        'denizbank' => 'DenizBank',
        'teb' => 'TEB',
        'enpara' => 'Enpara',
        'kuveytturk' => 'Kuveyt Türk',
        'diger' => 'Diğer',
    ];
}

/** Türkçe karakterleri sadeleştir */
function bank_normalize(string $bank): string
{
    $b = mb_strtolower(trim($bank), 'UTF-8');
    $map = [
        'ş' => 's', 'Ş' => 's', 'ı' => 'i', 'İ' => 'i', 'I' => 'i',
        'ğ' => 'g', 'Ğ' => 'g', 'ü' => 'u', 'Ü' => 'u',
        'ö' => 'o', 'Ö' => 'o', 'ç' => 'c', 'Ç' => 'c',
    ];
    $b = strtr($b, $map);
    $b = preg_replace('/\s+/u', ' ', $b) ?? $b;
    return $b;
}

function bank_key_from_name(string $bank): string
{
    $b = bank_normalize($bank);
    if ($b === '') {
        return 'diger';
    }
    $rules = [
        'ziraat' => 'ziraat',
        'is bank' => 'isbank',
        'isbank' => 'isbank',
        'turkiye is' => 'isbank',
        'garanti' => 'garanti',
        'bbva' => 'garanti',
        'yapi kredi' => 'yapikredi',
        'yapikredi' => 'yapikredi',
        'akbank' => 'akbank',
        'halkbank' => 'halkbank',
        'halk bank' => 'halkbank',
        'vakif' => 'vakifbank',
        'qnb' => 'qnb',
        'finansbank' => 'qnb',
        'finans bank' => 'qnb',
        'deniz' => 'denizbank',
        'teb' => 'teb',
        'enpara' => 'enpara',
        'kuveyt' => 'kuveytturk',
    ];
    foreach ($rules as $needle => $key) {
        if (str_contains($b, $needle)) {
            return $key;
        }
    }
    return 'diger';
}

function bank_logo_key(array $iban): string
{
    $key = bank_normalize((string) ($iban['bank_key'] ?? ''));
    $key = str_replace(' ', '', $key);
    $opts = bank_options();
    if ($key !== '' && isset($opts[$key])) {
        return $key;
    }
    // eski kayıtlar: "isbank" yerine yanlış yazılmış olabilir
    $aliases = [
        'is' => 'isbank',
        'isbankasi' => 'isbank',
        'turkiyeisbankasi' => 'isbank',
        'ziraatbankasi' => 'ziraat',
    ];
    if (isset($aliases[$key])) {
        return $aliases[$key];
    }
    return bank_key_from_name((string) ($iban['bank'] ?? ''));
}

/** @return array{bg:string,fg:string,label:string} */
function bank_logo_style(string $key): array
{
    $styles = [
        'ziraat' => ['bg' => '#E30613', 'fg' => '#ffffff', 'label' => 'Z'],
        'isbank' => ['bg' => '#0033A0', 'fg' => '#ffffff', 'label' => 'Is'],
        'garanti' => ['bg' => '#ffffff', 'fg' => '#2F8F2B', 'label' => 'G'],
        'yapikredi' => ['bg' => '#004B93', 'fg' => '#F7A800', 'label' => 'YK'],
        'akbank' => ['bg' => '#E30613', 'fg' => '#ffffff', 'label' => 'A'],
        'halkbank' => ['bg' => '#0055A5', 'fg' => '#ffffff', 'label' => 'HB'],
        'vakifbank' => ['bg' => '#FDB913', 'fg' => '#1a1a1a', 'label' => 'VB'],
        'qnb' => ['bg' => '#7B1FA2', 'fg' => '#ffffff', 'label' => 'QNB'],
        'denizbank' => ['bg' => '#00A3E0', 'fg' => '#ffffff', 'label' => 'DB'],
        'teb' => ['bg' => '#00A651', 'fg' => '#ffffff', 'label' => 'TEB'],
        'enpara' => ['bg' => '#111111', 'fg' => '#ffffff', 'label' => 'EN'],
        'kuveytturk' => ['bg' => '#007A3D', 'fg' => '#ffffff', 'label' => 'KT'],
        'diger' => ['bg' => '#5f6d57', 'fg' => '#ffffff', 'label' => 'TL'],
    ];
    return $styles[$key] ?? $styles['diger'];
}

function bank_custom_logo_url(array $iban): string
{
    $file = trim((string) ($iban['logo'] ?? ''));
    if ($file === '') {
        return '';
    }
    $path = BASE_PATH . '/uploads/banks/' . ltrim($file, '/');
    if (!is_file($path)) {
        return '';
    }
    return url('uploads/banks/' . ltrim($file, '/'));
}

/** Hazır banka SVG yok — sadece harf rozeti (manuel logo yoksa). */
function bank_logo_url(string $key): string
{
    $style = bank_logo_style($key === '' ? 'diger' : $key);
    $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">'
        . '<rect width="40" height="40" rx="8" fill="' . htmlspecialchars($style['bg'], ENT_QUOTES) . '"/>'
        . '<text x="20" y="26" text-anchor="middle" fill="' . htmlspecialchars($style['fg'], ENT_QUOTES) . '" font-family="Arial,sans-serif" font-size="12" font-weight="800">'
        . htmlspecialchars($style['label'], ENT_QUOTES) . '</text></svg>';
    return 'data:image/svg+xml;utf8,' . rawurlencode($svg);
}

function bank_logo_html(array $iban, string $class = 'bank-logo'): string
{
    $key = bank_logo_key($iban);
    $name = trim((string) ($iban['bank'] ?? '')) ?: (bank_options()[$key] ?? 'Banka');
    // Önce admin’in yüklediği logo
    $src = bank_custom_logo_url($iban);
    if ($src === '') {
        $src = bank_logo_url($key);
    }
    return '<img class="' . e($class) . '" src="' . e($src) . '" alt="' . e($name) . '" width="40" height="40" loading="lazy">';
}

/**
 * Banka logosunu yükler, kare 256px PNG’ye otomatik boyutlandırır (şeffaf arka plan).
 */
function save_bank_logo_upload(array $file, int $size = 256): string|false
{
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        return false;
    }
    if (!function_exists('imagecreatetruecolor')) {
        $dir = BASE_PATH . '/uploads/banks';
        if (!is_dir($dir)) {
            mkdir($dir, 0775, true);
        }
        return save_uploaded_image($file, $dir, 'b_');
    }

    $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;
    }
    imagealphablending($dst, false);
    imagesavealpha($dst, true);
    $transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
    imagefilledrectangle($dst, 0, 0, $size, $size, $transparent);

    // Oranı koru, kareye sığdır (contain)
    $scale = min($size / $sw, $size / $sh);
    $nw = (int) max(1, round($sw * $scale));
    $nh = (int) max(1, round($sh * $scale));
    $dx = (int) (($size - $nw) / 2);
    $dy = (int) (($size - $nh) / 2);
    imagealphablending($dst, true);
    imagecopyresampled($dst, $src, $dx, $dy, 0, 0, $nw, $nh, $sw, $sh);
    imagedestroy($src);

    $dir = BASE_PATH . '/uploads/banks';
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }
    $name = 'b_' . bin2hex(random_bytes(8)) . '.png';
    $dest = $dir . '/' . $name;
    imagealphablending($dst, false);
    imagesavealpha($dst, true);
    $ok = imagepng($dst, $dest, 6);
    imagedestroy($dst);

    return $ok ? $name : false;
}

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

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

/** Sitede kullanılan tek IBAN (varsayılan veya ilk kayıt). */
function iban_default(): ?array
{
    foreach (ibans_all() as $iban) {
        if (!empty($iban['is_default'])) {
            return $iban;
        }
    }
    $all = ibans_all();
    return $all[0] ?? null;
}

function iban_site(): ?array
{
    return iban_default();
}

/**
 * Tek IBAN kaydı yazar (çoklu listeyi temizler) ve tüm ürünlere bağlar.
 *
 * @return array{iban:array, products:int}
 */
function iban_save_site(array $item): array
{
    $item['is_default'] = true;
    $item['updated_at'] = date('c');
    if (empty($item['id'])) {
        $item['id'] = new_id('iban_');
    }
    if (empty($item['created_at'])) {
        $item['created_at'] = date('c');
    }
    store_write('ibans', [$item]);
    $count = iban_assign_all_products((string) $item['id']);
    return ['iban' => $item, 'products' => $count];
}

/** Tüm ürünlerin iban_id alanını tek IBAN’a çeker. */
function iban_assign_all_products(string $ibanId): int
{
    if ($ibanId === '') {
        return 0;
    }
    $products = store_read('products');
    $n = 0;
    foreach ($products as &$p) {
        if ((string) ($p['iban_id'] ?? '') !== $ibanId) {
            $p['iban_id'] = $ibanId;
            $n++;
        }
    }
    unset($p);
    store_write('products', array_values($products));
    return $n;
}

function iban_for_product(array $product): ?array
{
    // Tek IBAN modeli: ürün seçimine bakmadan site IBAN’ı
    return iban_site();
}

function iban_label(array $iban): string
{
    $bank = trim((string) ($iban['bank'] ?? ''));
    $name = trim((string) ($iban['account_name'] ?? ''));
    $no = trim((string) ($iban['iban'] ?? ''));
    $short = $no !== '' ? (mb_substr(preg_replace('/\s+/', '', $no) ?? '', 0, 8) . '…') : '';
    $title = $bank !== '' ? $bank : ($name !== '' ? $name : 'IBAN');
    return $title . ($short !== '' ? ' · ' . $short : '');
}
