<?php
declare(strict_types=1);

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

require_admin();

$banks = bank_options();
$current = iban_site();

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

    if ($action === 'save') {
        $accountName = trim((string) ($_POST['account_name'] ?? ''));
        $bankKey = trim((string) ($_POST['bank_key'] ?? 'diger'));
        $bankOther = trim((string) ($_POST['bank_other'] ?? ''));
        $ibanNo = trim((string) ($_POST['iban'] ?? ''));
        $removeLogo = !empty($_POST['remove_logo']);

        if ($accountName === '' || $ibanNo === '') {
            flash('error', 'Hesap adı ve IBAN zorunlu.');
            redirect(url('admin/ibanlar.php'));
        }
        if (!isset($banks[$bankKey])) {
            $bankKey = 'diger';
        }
        $bank = $bankKey === 'diger'
            ? ($bankOther !== '' ? $bankOther : 'Diğer')
            : $banks[$bankKey];

        $item = $current ?? [
            'id' => new_id('iban_'),
            'created_at' => date('c'),
        ];
        $item['label'] = $bank;
        $item['account_name'] = $accountName;
        $item['bank'] = $bank;
        $item['bank_key'] = $bankKey;
        $item['iban'] = $ibanNo;
        $item['is_default'] = true;

        if ($removeLogo) {
            $item['logo'] = '';
        }

        if (!empty($_FILES['logo']['name'])) {
            $savedLogo = save_bank_logo_upload($_FILES['logo'], 256);
            if ($savedLogo === false) {
                flash('error', 'Logo yüklenemedi. PNG/JPG/WEBP dene.');
                redirect(url('admin/ibanlar.php'));
            }
            $item['logo'] = $savedLogo;
        }

        $result = iban_save_site($item);
        $n = (int) ($result['products'] ?? 0);
        flash('success', 'IBAN kaydedildi. Tüm ürünler bu IBAN’a bağlandı' . ($n > 0 ? " ({$n} ürün güncellendi)" : '') . '.');
        redirect(url('admin/ibanlar.php'));
    }

    if ($action === 'delete') {
        store_write('ibans', []);
        $products = store_read('products');
        foreach ($products as &$p) {
            $p['iban_id'] = '';
        }
        unset($p);
        store_write('products', array_values($products));
        flash('success', 'IBAN silindi. Ürünlerden de kaldırıldı.');
        redirect(url('admin/ibanlar.php'));
    }

    flash('error', 'Geçersiz işlem.');
    redirect(url('admin/ibanlar.php'));
}

$edit = $current;
$editKey = $edit ? bank_logo_key($edit) : 'ziraat';
$editLogo = $edit ? (bank_custom_logo_url($edit) ?: bank_logo_url($editKey)) : bank_logo_url($editKey);
$hasCustomLogo = $edit && bank_custom_logo_url($edit) !== '';
$productCount = count(store_read('products'));

admin_layout_start('IBAN', 'ibans');
?>

<section class="admin-panel">
    <h2><?= $edit ? 'Site IBAN’ı' : 'IBAN ekle' ?></h2>
    <p class="hint">Tek IBAN kullanılır. Kaydedince <strong>tüm ürünler</strong> otomatik bu IBAN’a bağlanır<?= $productCount ? ' (şu an ' . (int) $productCount . ' ürün)' : '' ?>.</p>

    <form method="post" enctype="multipart/form-data" class="admin-form" data-iban-form>
        <input type="hidden" name="action" value="save">
        <div class="admin-form-row">
            <label>Hesap adı
                <input type="text" name="account_name" required value="<?= e($edit['account_name'] ?? '') ?>">
            </label>
            <label>Banka
                <select name="bank_key" data-bank-key>
                    <?php foreach ($banks as $key => $label): ?>
                        <option value="<?= e($key) ?>" data-logo="<?= e(bank_logo_url($key)) ?>" <?= $editKey === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
        </div>
        <label data-bank-other-wrap style="<?= $editKey === 'diger' ? '' : 'display:none' ?>">
            Diğer banka adı
            <input type="text" name="bank_other" value="<?= e($editKey === 'diger' ? ($edit['bank'] ?? '') : '') ?>" placeholder="Banka adı">
        </label>

        <div class="bank-logo-box" data-bank-logo-box data-has-custom="<?= $hasCustomLogo ? '1' : '0' ?>">
            <p class="bank-logo-box-title">Banka logosu</p>
            <div class="bank-logo-preview" data-bank-preview>
                <img class="bank-logo bank-logo-lg" data-bank-img src="<?= e($editLogo) ?>" alt="Banka logosu" width="72" height="72">
                <div>
                    <strong data-bank-logo-hint><?= $hasCustomLogo ? 'Yüklediğin logo' : 'Önizleme' ?></strong>
                    <p class="hint" style="margin:0.2rem 0 0">PNG / JPG / WEBP — otomatik 256×256.</p>
                </div>
            </div>
            <label class="bank-logo-file">
                <span>Logo seç / değiştir</span>
                <input type="file" name="logo" accept="image/png,image/jpeg,image/webp,image/gif" data-bank-logo-input>
            </label>
            <?php if ($hasCustomLogo): ?>
                <label style="display:flex;align-items:center;gap:0.45rem;font-weight:600;margin:0">
                    <input type="checkbox" name="remove_logo" value="1" style="width:auto">
                    Yüklenen logoyu kaldır
                </label>
            <?php endif; ?>
        </div>

        <label>IBAN
            <input type="text" name="iban" required value="<?= e($edit['iban'] ?? '') ?>" placeholder="TR00 0000 0000 0000 0000 0000 00">
        </label>

        <button class="admin-btn" type="submit"><?= $edit ? 'Kaydet' : 'IBAN Ekle' ?></button>
    </form>

    <?php if ($edit): ?>
        <form method="post" style="margin-top:0.75rem" onsubmit="return confirm('IBAN silinsin mi? Ürünlerden de kalkar.');">
            <input type="hidden" name="action" value="delete">
            <button class="admin-btn danger" type="submit">IBAN’ı Sil</button>
        </form>
    <?php endif; ?>
</section>

<?php if ($edit): ?>
<section class="admin-panel">
    <h2>Özet</h2>
    <div class="admin-order admin-iban-card">
        <div class="admin-order-head" style="align-items:center;gap:0.7rem">
            <?= bank_logo_html($edit) ?>
            <strong><?= e($edit['bank'] ?? $edit['account_name'] ?? 'IBAN') ?></strong>
            <span class="admin-badge paid">Aktif</span>
        </div>
        <p><?= e($edit['account_name'] ?? '') ?> · <?= e($edit['bank'] ?? '') ?></p>
        <p><code><?= e($edit['iban'] ?? '') ?></code></p>
    </div>
</section>
<?php endif; ?>

<script>
(() => {
  const sel = document.querySelector('[data-bank-key]');
  const other = document.querySelector('[data-bank-other-wrap]');
  const img = document.querySelector('[data-bank-img]');
  const fileInp = document.querySelector('[data-bank-logo-input]');
  const hint = document.querySelector('[data-bank-logo-hint]');
  const box = document.querySelector('[data-bank-logo-box]');
  let customPreview = null;

  const syncBank = () => {
    const key = sel?.value || 'diger';
    const opt = sel?.options?.[sel.selectedIndex];
    if (other) other.style.display = key === 'diger' ? '' : 'none';
    if (customPreview || (box && box.getAttribute('data-has-custom') === '1' && !fileInp?.files?.length)) {
      return;
    }
    if (img && opt) img.src = opt.getAttribute('data-logo') || img.src;
  };

  sel?.addEventListener('change', () => {
    customPreview = null;
    if (box) box.setAttribute('data-has-custom', '0');
    syncBank();
  });

  fileInp?.addEventListener('change', () => {
    const file = fileInp.files && fileInp.files[0];
    if (!file || !img) return;
    const url = URL.createObjectURL(file);
    customPreview = url;
    img.src = url;
    if (hint) hint.textContent = 'Yeni logo (kayıtta otomatik boyutlanır)';
    if (box) box.setAttribute('data-has-custom', '1');
  });

  syncBank();
})();
</script>

<?php admin_layout_end(); ?>
