<?php if (session_status() === PHP_SESSION_NONE) session_start(); ?>
<script>
const API = 'api/';
let allReservations = [];
let autoRefreshTimer = null;

function toast(msg, type='success') {
  const el = document.getElementById('toast');
  el.textContent = msg; el.className = 'toast show ' + type;
  setTimeout(() => el.className = 'toast', 2800);
}

async function doLogin() {
  const pass = document.getElementById('loginPass').value;
  const btn  = document.getElementById('loginBtn');
  const err  = document.getElementById('loginError');
  if (!pass) { err.textContent = 'Şifre boş olamaz!'; return; }
  btn.textContent = 'Giriş yapılıyor...'; btn.disabled = true; err.textContent = '';
  try {
    const res = await fetch('admin.php', {
      method:'POST',
      headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
      body: JSON.stringify({password: pass})
    });
    const data = await res.json();
    if (data.success) {
      document.getElementById('loginScreen').style.display = 'none';
      document.getElementById('adminLayout').classList.add('visible');
      initAdmin();
    } else {
      err.textContent = data.error || 'Hatalı şifre!';
    }
  } catch(e) { err.textContent = 'Sunucuya bağlanılamadı.'; }
  finally { btn.textContent = 'Giriş Yap'; btn.disabled = false; }
}

function doLogout() {
  if (autoRefreshTimer) clearInterval(autoRefreshTimer);
  window.location.href = 'admin.php?logout=1';
}

function initAdmin() {
  loadDashboard(); loadCars(); loadSettings(); loadReservations();
  usomInfo();
  autoRefreshTimer = setInterval(() => { loadReservations(true); loadDashboard(); }, 5000);
}

<?php if (!empty($_SESSION['admin_logged_in'])): ?>
window.addEventListener('DOMContentLoaded', initAdmin);
<?php endif; ?>

function showTab(tab, el) {
  document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
  document.querySelectorAll('.sidebar nav a').forEach(a => a.classList.remove('active'));
  document.getElementById('tab-' + tab).classList.add('active');
  if (el) el.classList.add('active');
  const titles = {dashboard:'Dashboard',reservations:'Rezervasyonlar',cars:'Araçlar',settings:'Ayarlar',usom:'🔎 USOM Kontrol'};
  document.getElementById('page-title').textContent = titles[tab];
}

function openModal(id) { document.getElementById(id).classList.add('active'); }
function closeModal(id) { document.getElementById(id).classList.remove('active'); }
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.modal-overlay').forEach(m => {
    m.addEventListener('click', e => { if (e.target === m) m.classList.remove('active'); });
  });
});

async function loadDashboard() {
  try {
    const [resData, carsData] = await Promise.all([
      fetch(API+'reservations.php').then(r=>r.json()),
      fetch(API+'cars.php').then(r=>r.json())
    ]);
    document.getElementById('stat-total').textContent     = resData.length;
    document.getElementById('stat-beklemede').textContent = resData.filter(r=>r.status==='beklemede').length;
    document.getElementById('stat-onaylandi').textContent = resData.filter(r=>r.status==='onaylandi').length;
    document.getElementById('stat-cars').textContent      = carsData.filter(c=>c.available==1).length;
    const tbody = document.getElementById('recent-tbody');
    tbody.innerHTML = '';
    resData.slice(0,8).forEach(r => {
      const pm = r.payment_method==='havale' ? '🏦' : '💳';
      tbody.innerHTML += `<tr>
        <td>${r.id}</td>
        <td><a href="#" onclick="showResDetail(${r.id});return false" style="color:#c0392b;text-decoration:none;font-weight:600">${r.customer_name}</a></td>
        <td>${r.car_name}</td><td>${r.pickup_date}</td><td>${pm}</td>
        <td><span class="badge badge-${r.status}">${r.status}</span></td>
      </tr>`;
    });
  } catch(e) {}
}

async function loadReservations(silent=false) {
  try {
    const prev = allReservations.length;
    allReservations = await fetch(API+'reservations.php').then(r=>r.json());
    renderReservations(allReservations);
    if (silent && allReservations.length > prev) toast('🔔 Yeni rezervasyon geldi!');
  } catch(e) {}
}

function renderReservations(data) {
  const tbody = document.getElementById('res-tbody');
  tbody.innerHTML = '';
  data.forEach(r => {
    const pm = r.payment_method==='havale' ? '🏦 Havale' : '💳 K.Kartı';
    const ibanCell = r.iban_requested==1
      ? (r.iban_sent
          ? `<span style="color:#27ae60;font-size:.78rem;font-weight:600">✅ Gönderildi</span>`
          : `<button class="btn btn-warning btn-sm" onclick="openSendIban(${r.id})">🏦 IBAN Gönder</button>`)
      : '-';
    tbody.innerHTML += `<tr>
      <td>${r.id}</td>
      <td><a href="#" onclick="showResDetail(${r.id});return false" style="color:#c0392b;text-decoration:none;font-weight:600">${r.customer_name}</a></td>
      <td>${r.customer_phone}</td><td>${r.car_name}</td>
      <td style="font-size:.8rem">${r.pickup_airport}</td>
      <td style="font-size:.8rem">${r.dropoff_airport}</td>
      <td style="font-size:.8rem">${r.pickup_date}<br>${r.dropoff_date}</td>
      <td>${r.total_price ? r.total_price+' TL' : '-'}</td>
      <td style="font-size:.8rem">${pm}</td>
      <td>
        <select onchange="updateStatus(${r.id},this.value)" style="padding:4px;border-radius:4px;border:1px solid #ddd;font-size:.8rem">
          <option value="beklemede" ${r.status==='beklemede'?'selected':''}>Beklemede</option>
          <option value="onaylandi" ${r.status==='onaylandi'?'selected':''}>Onaylandi</option>
          <option value="tamamlandi" ${r.status==='tamamlandi'?'selected':''}>Tamamlandı</option>
          <option value="iptal" ${r.status==='iptal'?'selected':''}>İptal</option>
        </select>
      </td>
      <td style="min-width:110px">${ibanCell}</td>
      <td style="white-space:nowrap">
        <div style="display:flex;gap:4px;align-items:center;flex-wrap:wrap">
          <button class="btn btn-danger btn-sm" onclick="deleteReservation(${r.id})">Sil</button>
          <button class="btn btn-sm" style="background:#6c757d;color:#fff" onclick="showResDetail(${r.id})">Detaylar</button>
          <div style="display:flex;gap:3px;border-left:1px solid #eee;padding-left:4px">
            <a href="api/fatura.php?id=${r.id}" target="_blank" class="btn btn-sm" style="background:#3498db;color:#fff;text-decoration:none" title="E-Arşiv Fatura">🧾</a>
            <a href="api/sozlesme.php?id=${r.id}" target="_blank" class="btn btn-sm" style="background:#27ae60;color:#fff;text-decoration:none" title="Sözleşme PDF">📋</a>
            <a href="sozlesme-imza.php?id=${r.id}" target="_blank" class="btn btn-sm" style="background:#f39c12;color:#fff;text-decoration:none" title="İmzalı Sözleşme">✍️</a>
            ${r.dekont_path ? `<a href="api/dekont.php?id=${r.id}" target="_blank" class="btn btn-sm" style="background:#8e44ad;color:#fff;text-decoration:none" title="Dekontu Görüntüle">📎</a>` : ''}
          </div>
        </div>
      </td>
    </tr>`;
  });
}

function filterReservations() {
  const s  = document.getElementById('res-search').value.toLowerCase();
  const st = document.getElementById('res-status-filter').value;
  let f = allReservations;
  if (s)  f = f.filter(r => r.customer_name.toLowerCase().includes(s) || r.customer_phone.includes(s));
  if (st) f = f.filter(r => r.status === st);
  renderReservations(f);
}

async function updateStatus(id, status) {
  await fetch(API+'reservations.php?id='+id+'&action=status', {
    method:'PATCH', headers:{'Content-Type':'application/json'}, body:JSON.stringify({status})
  });
  toast('Durum güncellendi'); loadDashboard();
}

async function deleteReservation(id) {
  if (!confirm('Bu rezervasyonu silmek istediğinize emin misiniz?')) return;
  await fetch(API+'reservations.php?id='+id, {method:'DELETE'});
  toast('Rezervasyon silindi'); loadReservations(); loadDashboard();
}

function showResDetail(id) {
  const r = allReservations.find(x=>x.id==id);
  if (!r) return;
  const pm = r.payment_method==='havale' ? '🏦 Havale/EFT' : '💳 Kredi Kartı';
  let ibanInfo = '-';
  if (r.iban_sent) {
    try { const p = JSON.parse(r.iban_sent); ibanInfo = `${p.banka||''} — ${p.alici||''} — ${p.iban||r.iban_sent}`; }
    catch(e) { ibanInfo = r.iban_sent; }
  }
  const dekontBtn = r.dekont_path
    ? `<a href="api/dekont.php?id=${r.id}" target="_blank" class="btn btn-success" style="text-decoration:none">🧾 Dekontu Görüntüle</a>`
    : `<span style="color:#aaa;font-size:.85rem">Dekont yüklenmedi</span>`;

  document.getElementById('res-detail-content').innerHTML = `
    <b>Müşteri:</b> ${r.customer_name}<br><b>Telefon:</b> ${r.customer_phone}<br>
    <b>TC Kimlik:</b> ${r.tc_no||'-'}<br>
    <b>Rezervasyon No:</b> <span style="font-weight:700;color:#c0392b">${r.rezervasyon_no||'-'}</span><br>
    <b>E-posta:</b> ${r.customer_email||'-'}<br><b>Araç:</b> ${r.car_name}<br>
    <b>Alış:</b> ${r.pickup_airport}<br><b>İade:</b> ${r.dropoff_airport}<br>
    <b>Tarihler:</b> ${r.pickup_date} → ${r.dropoff_date}<br>
    <b>Toplam Fiyat:</b> ${r.total_price ? r.total_price+' TL' : '-'}<br>
    <b>Ödeme:</b> ${pm}<br>
    <b>IBAN Talebi:</b> ${r.iban_requested==1 ? '✅ Talep edildi' : 'Hayır'}<br>
    <b>IBAN:</b> ${ibanInfo}<br>
    <b>Dekont:</b> ${dekontBtn}<br>
    <b>Durum:</b> <span class="badge badge-${r.status}">${r.status}</span><br>
    <b>Not:</b> ${r.notes||'-'}<br><b>Kayıt:</b> ${r.created_at}
    <div style="margin-top:14px;display:flex;gap:8px">
      <button class="btn btn-primary" onclick="window.open('api/fatura.php?id=${r.id}','_blank')">🧾 E-Arşiv Fatura</button>
      <button class="btn btn-success" onclick="window.open('api/sozlesme.php?id=${r.id}','_blank')">📋 Sözleşme PDF</button>
      <button class="btn btn-warning" onclick="window.open('sozlesme-imza.php?id=${r.id}','_blank')">✍️ İmzalı Sözleşme</button>
    </div>`;
  openModal('resDetailModal');
}

function openSendIban(id) {
  document.getElementById('iban-res-id').value = id;
  ['iban-input','iban-alici','iban-banka'].forEach(i => document.getElementById(i).value = '');
  document.getElementById('iban-select').value = '';
  fetch(API+'settings.php').then(r=>r.json()).then(s => {
    let ibans = [];
    try { ibans = JSON.parse(s.iban_list||'[]'); } catch(e) {}
    const sel = document.getElementById('iban-select');
    sel.innerHTML = '<option value="">— Manuel gir —</option>';
    ibans.forEach(item => {
      const o = document.createElement('option');
      o.value = JSON.stringify({iban:item.iban, alici:item.alici||'', banka:item.label||''});
      o.textContent = item.label + (item.alici?' — '+item.alici:'') + ' — ' + item.iban;
      sel.appendChild(o);
    });
  });
  openModal('sendIbanModal');
}

function ibanSelectChange() {
  const raw = document.getElementById('iban-select').value;
  if (!raw) return;
  try {
    const d = JSON.parse(raw);
    document.getElementById('iban-input').value = d.iban||'';
    document.getElementById('iban-alici').value = d.alici||'';
    document.getElementById('iban-banka').value = d.banka||'';
  } catch(e) {}
}

async function submitIban() {
  const id    = document.getElementById('iban-res-id').value;
  const iban  = document.getElementById('iban-input').value.trim();
  const alici = document.getElementById('iban-alici').value.trim();
  const banka = document.getElementById('iban-banka').value.trim();
  if (!iban) { toast('IBAN boş olamaz!','error'); return; }
  const res = await fetch(API+'reservations.php?id='+id+'&action=send-iban', {
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({iban, alici, banka})
  });
  if (res.ok) { closeModal('sendIbanModal'); loadReservations(); toast('✅ IBAN müşteriye gönderildi!'); }
  else toast('Hata oluştu.','error');
}

async function loadCars() {
  const cars = await fetch(API+'cars.php').then(r=>r.json());
  const tbody = document.getElementById('cars-tbody');
  tbody.innerHTML = '';
  cars.forEach(c => {
    tbody.innerHTML += `<tr>
      <td><img src="${c.image_url}" class="car-img-preview" onerror="this.src='images/Avis_logo.svg.png'"></td>
      <td><b>${c.name}</b></td><td>${c.model_year||'-'}</td>
      <td><b>${c.daily_price} TL</b></td>
      <td><span class="badge ${c.available==1?'badge-onaylandi':'badge-iptal'}">${c.available==1?'Aktif':'Pasif'}</span></td>
      <td style="display:flex;gap:6px">
        <button class="btn btn-warning btn-sm" onclick="openEditCar(${c.id})">Düzenle</button>
        <button class="btn btn-danger btn-sm" onclick="deleteCar(${c.id})">Sil</button>
      </td></tr>`;
  });
}

async function addCar() {
  const name  = document.getElementById('car-name').value.trim();
  const price = document.getElementById('car-price').value;
  if (!name || !price) { toast('Araç adı ve fiyat zorunlu!','error'); return; }
  await fetch(API+'cars.php', {
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({name, model_year:document.getElementById('car-year').value||null,
      daily_price:price, image_url:document.getElementById('car-image').value})
  });
  ['car-name','car-year','car-price','car-image'].forEach(id=>document.getElementById(id).value='');
  loadCars(); loadDashboard(); toast('Araç eklendi!');
}

async function deleteCar(id) {
  if (!confirm('Bu aracı silmek istediğinize emin misiniz?')) return;
  await fetch(API+'cars.php?id='+id, {method:'DELETE'});
  loadCars(); loadDashboard(); toast('Araç silindi');
}

async function openEditCar(id) {
  const car = await fetch(API+'cars.php?id='+id).then(r=>r.json());
  document.getElementById('edit-car-id').value    = car.id;
  document.getElementById('edit-car-name').value  = car.name;
  document.getElementById('edit-car-year').value  = car.model_year||'';
  document.getElementById('edit-car-price').value = car.daily_price;
  document.getElementById('edit-car-image').value = car.image_url||'';
  document.getElementById('edit-car-available').value = car.available;
  openModal('editCarModal');
}

async function saveEditCar() {
  const id = document.getElementById('edit-car-id').value;
  await fetch(API+'cars.php?id='+id, {
    method:'PUT', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({
      name:      document.getElementById('edit-car-name').value,
      model_year:document.getElementById('edit-car-year').value,
      daily_price:document.getElementById('edit-car-price').value,
      image_url: document.getElementById('edit-car-image').value,
      available: document.getElementById('edit-car-available').value
    })
  });
  closeModal('editCarModal'); loadCars(); loadDashboard(); toast('Araç güncellendi!');
}

async function loadSettings() {
  const s = await fetch(API+'settings.php').then(r=>r.json());
  document.getElementById('set-whatsapp').value        = s.whatsapp_number||'';
  document.getElementById('set-hero-title').value      = s.hero_title||'';
  document.getElementById('set-hero-subtitle').value   = s.hero_subtitle||'';
  document.getElementById('set-telegram-token').value  = s.telegram_token||'';
  document.getElementById('set-telegram-chatid').value = s.telegram_chat_id||'';
  loadIbanList(s);
}

async function saveTelegram() {
  const token  = document.getElementById('set-telegram-token').value.trim();
  const chatId = document.getElementById('set-telegram-chatid').value.trim();
  if (!token || !chatId) { toast('Token ve Chat ID zorunlu!','error'); return; }
  await Promise.all([
    fetch(API+'settings.php?key=telegram_token',   {method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({value:token})}),
    fetch(API+'settings.php?key=telegram_chat_id', {method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({value:chatId})}),
  ]);
  toast('✅ Telegram ayarları kaydedildi!');
}

async function testTelegram() {
  const btn = event.currentTarget;
  btn.textContent = 'Gönderiliyor...'; btn.disabled = true;
  const el = document.getElementById('telegram-test-result');
  try {
    const res = await fetch(API+'settings.php?action=telegram-test', {method:'POST', headers:{'Content-Type':'application/json'}});
    const data = await res.json();
    el.style.display = 'block';
    if (data.success) {
      el.style.color = '#27ae60';
      el.textContent = '✅ Test mesajı başarıyla gönderildi!';
    } else {
      el.style.color = '#e74c3c';
      el.textContent = '❌ Hata: ' + (data.error || 'Gönderilemedi. Token ve Chat ID\'yi kontrol edin.');
    }
  } catch(e) {
    el.style.display = 'block'; el.style.color = '#e74c3c';
    el.textContent = '❌ Sunucuya bağlanılamadı.';
  }
  btn.textContent = '📨 Test Mesajı Gönder'; btn.disabled = false;
}

async function saveWhatsapp() {
  const val = document.getElementById('set-whatsapp').value.trim();
  if (!val) { toast('Numara boş olamaz!','error'); return; }
  await fetch(API+'settings.php?key=whatsapp_number', {
    method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({value:val})
  });
  toast('✅ WhatsApp numarası güncellendi!');
}

async function saveSettings() {
  await Promise.all([
    ['hero_title',    document.getElementById('set-hero-title').value],
    ['hero_subtitle', document.getElementById('set-hero-subtitle').value],
  ].map(([key,value]) =>
    fetch(API+'settings.php?key='+key, {method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({value})})
  ));
  toast('Ayarlar kaydedildi!');
}

function loadIbanList(settings) {
  let ibans = [];
  try { ibans = JSON.parse(settings.iban_list||'[]'); } catch(e) {}
  const tbody = document.getElementById('iban-tbody');
  tbody.innerHTML = ibans.length ? '' : '<tr><td colspan="4" style="text-align:center;color:#aaa;padding:16px">Henüz IBAN eklenmedi</td></tr>';
  ibans.forEach((item, i) => {
    tbody.innerHTML += `<tr>
      <td><b>${item.label}</b></td>
      <td>${item.alici||'-'}</td>
      <td style="font-family:monospace;font-size:.85rem">${item.iban}</td>
      <td><button class="btn btn-danger btn-sm" onclick="deleteIban(${i})">Sil</button></td>
    </tr>`;
  });
}

async function addIban() {
  const label = document.getElementById('new-iban-label').value.trim();
  const alici = document.getElementById('new-iban-alici').value.trim();
  const iban  = document.getElementById('new-iban-number').value.trim();
  if (!label || !iban) { toast('Banka adı ve IBAN zorunlu!','error'); return; }
  const s = await fetch(API+'settings.php').then(r=>r.json());
  let ibans = [];
  try { ibans = JSON.parse(s.iban_list||'[]'); } catch(e) {}
  ibans.push({label, alici, iban});
  await fetch(API+'settings.php?key=iban_list', {
    method:'PUT', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({value: JSON.stringify(ibans)})
  });
  ['new-iban-label','new-iban-alici','new-iban-number'].forEach(id=>document.getElementById(id).value='');
  loadSettings(); toast('IBAN eklendi!');
}

async function deleteIban(index) {
  if (!confirm('Bu IBAN silinsin mi?')) return;
  const s = await fetch(API+'settings.php').then(r=>r.json());
  let ibans = [];
  try { ibans = JSON.parse(s.iban_list||'[]'); } catch(e) {}
  ibans.splice(index, 1);
  await fetch(API+'settings.php?key=iban_list', {
    method:'PUT', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({value: JSON.stringify(ibans)})
  });
  loadSettings(); toast('IBAN silindi');
}

async function changePass() {
  const p1 = document.getElementById('new-pass').value;
  const p2 = document.getElementById('new-pass2').value;
  if (!p1) { toast('Şifre boş olamaz!','error'); return; }
  if (p1 !== p2) { toast('Şifreler eşleşmiyor!','error'); return; }
  await fetch(API+'settings.php?key=admin_password', {
    method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({value:p1})
  });
  toast('Şifre güncellendi! Tekrar giriş yapın.');
  setTimeout(() => doLogout(), 1500);
}

// ===== USOM =====
async function usomInfo() {
  try {
    const d = await fetch('api/usom.php?action=info').then(r=>r.json());
    const el = document.getElementById('usom-cache-info');
    if (!el) return;
    if (d.cached) {
      el.innerHTML = `📋 Liste: <strong>${d.count.toLocaleString('tr-TR')}</strong> zararlı kayıt | Son güncelleme: <strong>${d.updated}</strong> (${d.age_min} dk önce)`;
    } else {
      el.innerHTML = `⚠️ Liste henüz indirilmedi. "Listeyi Güncelle" butonuna basın.`;
    }
  } catch(e) {}
}

async function usomRefresh() {
  const btn = document.getElementById('btn-usom-refresh');
  btn.textContent = 'İndiriliyor...'; btn.disabled = true;
  try {
    const d = await fetch('api/usom.php?action=refresh').then(r=>r.json());
    if (d.success) {
      toast(`✅ Liste güncellendi: ${d.count.toLocaleString('tr-TR')} kayıt`);
      usomInfo();
    } else {
      toast('❌ ' + (d.error || 'Liste alınamadı'), 'error');
    }
  } catch(e) { toast('Sunucuya bağlanılamadı', 'error'); }
  btn.textContent = '🔄 Listeyi Güncelle'; btn.disabled = false;
}

async function usomCheck() {
  const domain = document.getElementById('usom-domain').value.trim();
  if (!domain) { toast('Domain boş olamaz!', 'error'); return; }
  const btn = document.getElementById('btn-usom-check');
  btn.textContent = 'Sorgulanıyor...'; btn.disabled = true;
  const el = document.getElementById('usom-result');
  el.style.display = 'none';
  try {
    const d = await fetch('api/usom.php?action=check', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({domain})
    }).then(r=>r.json());

    if (d.error) { toast(d.error, 'error'); return; }

    if (d.found) {
      el.innerHTML = `
        <div style="background:#fdf2f2;border:2px solid #e74c3c;border-radius:8px;padding:16px">
          <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px">
            <span style="font-size:1.8rem">⚠️</span>
            <div>
              <div style="font-size:1rem;font-weight:700;color:#c0392b">ZARALI BAĞLANTI TESPİT EDİLDİ</div>
              <div style="font-size:.85rem;color:#666">Domain: <strong>${d.domain}</strong></div>
            </div>
          </div>
          <div style="font-size:.82rem;color:#555;margin-top:8px">
            <strong>Eşleşen kayıtlar:</strong><br>
            ${d.matches.map(m=>`<code style="background:#fff;padding:2px 6px;border-radius:3px;display:inline-block;margin:2px 0">${m}</code>`).join('<br>')}
          </div>
          <div style="font-size:.75rem;color:#aaa;margin-top:8px">Kontrol tarihi: ${d.checked} | Liste boyutu: ${d.total.toLocaleString('tr-TR')} kayıt</div>
        </div>`;
    } else {
      el.innerHTML = `
        <div style="background:#f0fdf4;border:2px solid #27ae60;border-radius:8px;padding:16px;display:flex;align-items:center;gap:12px">
          <span style="font-size:1.8rem">✅</span>
          <div>
            <div style="font-size:1rem;font-weight:700;color:#27ae60">TEMİZ — Zararlı listede bulunamadı</div>
            <div style="font-size:.85rem;color:#666">Domain: <strong>${d.domain}</strong></div>
            <div style="font-size:.75rem;color:#aaa;margin-top:4px">Kontrol tarihi: ${d.checked} | Liste boyutu: ${d.total.toLocaleString('tr-TR')} kayıt</div>
          </div>
        </div>`;
    }
    el.style.display = 'block';
  } catch(e) { toast('Sorgu başarısız', 'error'); }
  btn.textContent = 'Sorgula'; btn.disabled = false;
}

async function usomBulk() {
  const text = document.getElementById('usom-bulk').value.trim();
  if (!text) { toast('Domain listesi boş!', 'error'); return; }
  const btn = document.getElementById('btn-usom-bulk');
  btn.textContent = 'Sorgulanıyor...'; btn.disabled = true;
  const el = document.getElementById('usom-bulk-result');
  el.style.display = 'none';
  try {
    const d = await fetch('api/usom.php?action=bulk', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({domains: text})
    }).then(r=>r.json());

    if (d.error) { toast(d.error, 'error'); return; }

    const zaralilar = d.results.filter(r=>r.found);
    const temizler  = d.results.filter(r=>!r.found);

    let html = `<div style="display:flex;gap:12px;margin-bottom:14px;flex-wrap:wrap">
      <div style="background:#fdf2f2;border:1px solid #e74c3c;border-radius:8px;padding:12px 20px;text-align:center">
        <div style="font-size:1.6rem;font-weight:900;color:#c0392b">${zaralilar.length}</div>
        <div style="font-size:.8rem;color:#888">Zararlı</div>
      </div>
      <div style="background:#f0fdf4;border:1px solid #27ae60;border-radius:8px;padding:12px 20px;text-align:center">
        <div style="font-size:1.6rem;font-weight:900;color:#27ae60">${temizler.length}</div>
        <div style="font-size:.8rem;color:#888">Temiz</div>
      </div>
      <div style="background:#f8f9fa;border:1px solid #ddd;border-radius:8px;padding:12px 20px;text-align:center">
        <div style="font-size:1.6rem;font-weight:900;color:#333">${d.total_checked}</div>
        <div style="font-size:.8rem;color:#888">Toplam</div>
      </div>
    </div>`;

    if (zaralilar.length > 0) {
      html += `<div style="background:#fdf2f2;border:1px solid #e74c3c;border-radius:8px;padding:14px;margin-bottom:10px">
        <div style="font-weight:700;color:#c0392b;margin-bottom:8px">⚠️ Zararlı Domainler:</div>
        ${zaralilar.map(r=>`<div style="font-family:monospace;font-size:.88rem;padding:3px 0;border-bottom:1px solid #fcc;color:#c0392b">⛔ ${r.domain}</div>`).join('')}
      </div>`;
    }

    html += `<div style="font-size:.75rem;color:#aaa">Liste boyutu: ${d.list_size.toLocaleString('tr-TR')} kayıt</div>`;
    el.innerHTML = html;
    el.style.display = 'block';
  } catch(e) { toast('Sorgu başarısız', 'error'); }
  btn.textContent = '🔍 Toplu Sorgula'; btn.disabled = false;
}
</script>
</body>
</html>
