<?php
session_start();
require_once __DIR__ . '/api/db.php';

// Logout
if (isset($_GET['logout'])) { session_destroy(); header('Location: admin.php'); exit; }

// AJAX login endpoint
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json; charset=utf-8');
    $d    = json_decode(file_get_contents('php://input'), true) ?: [];
    $pass = $d['password'] ?? '';
    $db   = getDB();
    $stored = $db->querySingle("SELECT value FROM settings WHERE key='admin_password'");
    $ok = $stored ? password_verify($pass, $stored) : ($pass === ADMIN_PASSWORD);
    if ($ok) {
        $_SESSION['admin_logged_in'] = true;
        echo json_encode(['success' => true]);
    } else {
        http_response_code(401);
        echo json_encode(['error' => 'Hatalı şifre!']);
    }
    exit;
}

$logged_in = !empty($_SESSION['admin_logged_in']);
?>
<!DOCTYPE html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Avis Admin Paneli</title>
  <style>
    *{box-sizing:border-box;margin:0;padding:0}
    body{font-family:'Segoe UI',sans-serif;background:#f0f2f5;color:#333}
    /* Login */
    .login-screen{display:flex;justify-content:center;align-items:center;min-height:100vh;background:linear-gradient(135deg,#c0392b,#922b21)}
    .login-box{background:#fff;border-radius:12px;padding:40px;width:360px;text-align:center;box-shadow:0 8px 32px rgba(0,0,0,.2)}
    .login-box img{width:140px;margin-bottom:24px}
    .login-box h2{margin-bottom:24px;color:#c0392b}
    .login-box input{width:100%;padding:12px;border:1px solid #ddd;border-radius:6px;font-size:1rem;margin-bottom:14px;transition:border .2s}
    .login-box input:focus{outline:none;border-color:#c0392b}
    .login-box button{width:100%;padding:13px;background:#c0392b;color:#fff;border:none;border-radius:6px;font-size:1rem;font-weight:700;cursor:pointer;transition:background .2s}
    .login-box button:hover{background:#a93226}
    .login-box button:disabled{opacity:.6;cursor:not-allowed}
    .login-error{color:#c0392b;font-size:.9rem;margin-top:8px;min-height:20px}
    /* Layout */
    .admin-layout{display:none;min-height:100vh}
    .admin-layout.visible{display:flex}
    .sidebar{width:240px;background:#1a1a2e;position:fixed;top:0;left:0;height:100vh;padding:24px 0;overflow-y:auto;z-index:100}
    .sidebar .logo{padding:0 20px 24px;border-bottom:1px solid #2d2d4e}
    .sidebar .logo img{width:120px;filter:brightness(0) invert(1)}
    .sidebar nav{padding:16px 0}
    .sidebar nav a{display:block;padding:12px 20px;color:#aaa;text-decoration:none;font-size:.95rem;transition:all .2s;cursor:pointer;user-select:none}
    .sidebar nav a:hover,.sidebar nav a.active{background:#c0392b;color:#fff}
    .sidebar nav a span{margin-right:10px}
    .main-content{margin-left:240px;padding:28px;flex:1;min-width:0}
    .topbar{background:#fff;padding:16px 24px;border-radius:10px;margin-bottom:24px;display:flex;justify-content:space-between;align-items:center;box-shadow:0 2px 8px rgba(0,0,0,.06)}
    .topbar h1{font-size:1.3rem;color:#333}
    .btn-logout{background:#c0392b;color:#fff;border:none;padding:8px 18px;border-radius:6px;cursor:pointer;font-size:.9rem}
    /* Cards */
    .card{background:#fff;border-radius:10px;padding:24px;margin-bottom:20px;box-shadow:0 2px 8px rgba(0,0,0,.06)}
    .card h3{margin-bottom:18px;font-size:1.1rem;color:#c0392b;border-bottom:2px solid #f5c6c6;padding-bottom:10px}
    .stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px}
    .stat-card{background:#fff;border-radius:10px;padding:20px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,.06);border-left:4px solid #c0392b}
    .stat-card .num{font-size:2rem;font-weight:700;color:#c0392b}
    .stat-card .label{font-size:.85rem;color:#888;margin-top:4px}
    /* Table */
    table{width:100%;border-collapse:collapse;font-size:.9rem}
    th{background:#f8f9fa;padding:10px 12px;text-align:left;font-weight:600;color:#555;border-bottom:2px solid #eee}
    td{padding:10px 12px;border-bottom:1px solid #f0f0f0;vertical-align:middle}
    tr:hover td{background:#fafafa}
    .badge{display:inline-block;padding:3px 10px;border-radius:20px;font-size:.78rem;font-weight:600}
    .badge-beklemede{background:#fff3cd;color:#856404}
    .badge-onaylandi{background:#d1e7dd;color:#0f5132}
    .badge-iptal{background:#f8d7da;color:#842029}
    .badge-tamamlandi{background:#cfe2ff;color:#084298}
    /* Buttons */
    .btn{padding:7px 14px;border:none;border-radius:5px;cursor:pointer;font-size:.85rem;font-weight:600;transition:opacity .15s;position:relative}
    .btn:hover{opacity:.85}
    .btn[title]:hover::after{content:attr(title);position:absolute;bottom:120%;left:50%;transform:translateX(-50%);background:#333;color:#fff;padding:3px 8px;border-radius:4px;font-size:.72rem;white-space:nowrap;pointer-events:none;z-index:9999}
    .btn-primary{background:#c0392b;color:#fff}
    .btn-success{background:#27ae60;color:#fff}
    .btn-warning{background:#f39c12;color:#fff}
    .btn-danger{background:#e74c3c;color:#fff}
    .btn-sm{padding:4px 10px;font-size:.8rem}
    /* Forms */
    .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
    .form-group{margin-bottom:0}
    .form-group label{display:block;font-size:.85rem;font-weight:600;margin-bottom:5px;color:#555}
    .form-group input,.form-group select{width:100%;padding:9px 12px;border:1px solid #ddd;border-radius:6px;font-size:.9rem;transition:border .2s}
    .form-group input:focus,.form-group select:focus{outline:none;border-color:#c0392b}
    .form-group.full{grid-column:1/-1}
    /* Tabs */
    .tab-content{display:none}
    .tab-content.active{display:block;animation:fadeIn .2s ease}
    @keyframes fadeIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
    /* Modals */
    .modal-overlay{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:9999;justify-content:center;align-items:center}
    .modal-overlay.active{display:flex;animation:fadeIn .15s ease}
    .modal-box{background:#fff;border-radius:10px;padding:28px;width:90%;max-width:500px;box-shadow:0 8px 32px rgba(0,0,0,.2)}
    .modal-box h3{margin-bottom:18px;color:#c0392b}
    .modal-actions{display:flex;gap:10px;margin-top:18px;justify-content:flex-end}
    /* Misc */
    .search-bar{display:flex;gap:10px;margin-bottom:16px;flex-wrap:wrap}
    .search-bar input,.search-bar select{padding:8px 12px;border:1px solid #ddd;border-radius:6px;font-size:.9rem}
    .car-img-preview{width:80px;height:40px;object-fit:contain}
    .toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:#333;color:#fff;padding:12px 24px;border-radius:8px;font-size:.9rem;z-index:99999;opacity:0;transition:opacity .3s;pointer-events:none}
    .toast.show{opacity:1}
    .toast.success{background:#27ae60}
    .toast.error{background:#e74c3c}
    @media(max-width:768px){.stats-grid{grid-template-columns:repeat(2,1fr)}.sidebar{width:200px}.main-content{margin-left:200px;padding:16px}}
  </style>
</head>
<body>

<!-- Toast -->
<div class="toast" id="toast"></div>

<!-- Login -->
<div class="login-screen" id="loginScreen" <?= $logged_in ? 'style="display:none"' : '' ?>>
  <div class="login-box">
    <img src="images/Avis_logo.svg.png" alt="Avis">
    <h2>Admin Girişi</h2>
    <input type="password" id="loginPass" placeholder="Şifre" onkeydown="if(event.key==='Enter')doLogin()">
    <button id="loginBtn" onclick="doLogin()">Giriş Yap</button>
    <div class="login-error" id="loginError"></div>
  </div>
</div>

<!-- Admin Layout -->
<div class="admin-layout <?= $logged_in ? 'visible' : '' ?>" id="adminLayout">
  <div class="sidebar">
    <div class="logo"><img src="images/Avis_logo.svg.png" alt="Avis"></div>
    <nav>
      <a class="active" onclick="showTab('dashboard',this)"><span>📊</span>Dashboard</a>
      <a onclick="showTab('reservations',this)"><span>📋</span>Rezervasyonlar</a>
      <a onclick="showTab('cars',this)"><span>🚗</span>Araçlar</a>
      <a onclick="showTab('settings',this)"><span>⚙️</span>Ayarlar</a>
      <a onclick="showTab('usom',this)"><span>🔎</span>USOM Kontrol</a>
    </nav>
  </div>
  <div class="main-content">
    <div class="topbar">
      <h1 id="page-title">Dashboard</h1>
      <button class="btn-logout" onclick="doLogout()">Çıkış</button>
    </div>

    <!-- Dashboard -->
    <div class="tab-content active" id="tab-dashboard">
      <div class="stats-grid">
        <div class="stat-card"><div class="num" id="stat-total">-</div><div class="label">Toplam Rezervasyon</div></div>
        <div class="stat-card" style="border-color:#f39c12"><div class="num" style="color:#f39c12" id="stat-beklemede">-</div><div class="label">Beklemede</div></div>
        <div class="stat-card" style="border-color:#27ae60"><div class="num" style="color:#27ae60" id="stat-onaylandi">-</div><div class="label">Onaylanan</div></div>
        <div class="stat-card" style="border-color:#3498db"><div class="num" style="color:#3498db" id="stat-cars">-</div><div class="label">Aktif Araç</div></div>
      </div>
      <div class="card">
        <h3>Son Rezervasyonlar</h3>
        <table><thead><tr><th>#</th><th>Müşteri</th><th>Araç</th><th>Tarih</th><th>Ödeme</th><th>Durum</th></tr></thead>
        <tbody id="recent-tbody"></tbody></table>
      </div>
    </div>

    <!-- Rezervasyonlar -->
    <div class="tab-content" id="tab-reservations">
      <div class="card">
        <h3>Rezervasyonlar</h3>
        <div class="search-bar">
          <input type="text" id="res-search" placeholder="Müşteri ara..." oninput="filterReservations()">
          <select id="res-status-filter" onchange="filterReservations()">
            <option value="">Tüm Durumlar</option>
            <option value="beklemede">Beklemede</option>
            <option value="onaylandi">Onaylandi</option>
            <option value="iptal">İptal</option>
            <option value="tamamlandi">Tamamlandı</option>
          </select>
          <button class="btn btn-primary btn-sm" onclick="loadReservations()">🔄 Yenile</button>
        </div>
        <div style="overflow-x:auto">
          <table><thead><tr><th>#</th><th>Müşteri</th><th>Telefon</th><th>Araç</th><th>Alış</th><th>İade</th><th>Tarihler</th><th>Fiyat</th><th>Ödeme</th><th>Durum</th><th>IBAN</th><th>İşlem</th></tr></thead>
          <tbody id="res-tbody"></tbody></table>
        </div>
      </div>
    </div>

    <!-- USOM -->
    <div class="tab-content" id="tab-usom">
      <div class="card">
        <h3>🔎 USOM Zararlı Bağlantı Kontrolü</h3>
        <p style="font-size:.88rem;color:#888;margin-bottom:16px">
          Türkiye Ulusal Siber Olaylara Müdahale Merkezi (USOM) tarafından yayımlanan zararlı URL listesiyle domain/URL kontrolü yapın.
          Liste kaynağı: <a href="https://www.usom.gov.tr/zararli-baglantilar" target="_blank" style="color:#c0392b">usom.gov.tr</a>
        </p>
        <div style="display:flex;gap:10px;align-items:center;margin-bottom:20px;flex-wrap:wrap">
          <div id="usom-cache-info" style="font-size:.85rem;color:#888;flex:1">Liste yükleniyor...</div>
          <button class="btn btn-primary btn-sm" onclick="usomRefresh()" id="btn-usom-refresh">🔄 Listeyi Güncelle</button>
        </div>
      </div>

      <!-- Tekli Sorgulama -->
      <div class="card">
        <h3>Tekli Domain/URL Sorgula</h3>
        <div style="display:flex;gap:10px;max-width:600px">
          <input type="text" id="usom-domain" placeholder="örn: example.com veya https://example.com/path"
            style="flex:1;padding:10px 14px;border:1.5px solid #ddd;border-radius:6px;font-size:.95rem"
            onkeydown="if(event.key==='Enter')usomCheck()">
          <button class="btn btn-primary" onclick="usomCheck()" id="btn-usom-check">Sorgula</button>
        </div>
        <div id="usom-result" style="margin-top:16px;display:none"></div>
      </div>

      <!-- Toplu Sorgulama -->
      <div class="card">
        <h3>Toplu Domain Sorgula <span style="font-size:.78rem;color:#aaa;font-weight:400">(max 100 domain)</span></h3>
        <textarea id="usom-bulk" rows="8" placeholder="Her satıra bir domain yazın:&#10;example.com&#10;test.net&#10;https://phishing.site/page"
          style="width:100%;padding:10px 14px;border:1.5px solid #ddd;border-radius:6px;font-size:.88rem;font-family:monospace;resize:vertical;box-sizing:border-box"></textarea>
        <div style="display:flex;gap:10px;margin-top:10px;align-items:center">
          <button class="btn btn-primary" onclick="usomBulk()" id="btn-usom-bulk">🔍 Toplu Sorgula</button>
          <button class="btn btn-sm" style="background:#eee;color:#555" onclick="document.getElementById('usom-bulk').value='';document.getElementById('usom-bulk-result').style.display='none'">Temizle</button>
        </div>
        <div id="usom-bulk-result" style="margin-top:16px;display:none"></div>
      </div>
    </div>
    <div class="tab-content" id="tab-cars">
      <div class="card">
        <h3>Araç Ekle</h3>
        <div class="form-grid">
          <div class="form-group"><label>Araç Adı *</label><input type="text" id="car-name" placeholder="Örn: Toyota Corolla"></div>
          <div class="form-group"><label>Model Yılı</label><input type="number" id="car-year" placeholder="2025"></div>
          <div class="form-group"><label>Günlük Fiyat (TL) *</label><input type="number" id="car-price" placeholder="1500"></div>
          <div class="form-group"><label>Görsel URL</label><input type="text" id="car-image" placeholder="images/arac.png veya https://..."></div>
          <div class="form-group full"><button class="btn btn-primary" onclick="addCar()">+ Araç Ekle</button></div>
        </div>
      </div>
      <div class="card">
        <h3>Araç Listesi</h3>
        <table><thead><tr><th>Görsel</th><th>Araç</th><th>Yıl</th><th>Günlük Fiyat</th><th>Durum</th><th>İşlem</th></tr></thead>
        <tbody id="cars-tbody"></tbody></table>
      </div>
    </div>

    <!-- Ayarlar -->
    <div class="tab-content" id="tab-settings">
      <div class="card">
        <h3>WhatsApp Numarası</h3>
        <p style="font-size:.88rem;color:#888;margin-bottom:14px;">Sitedeki tüm WhatsApp butonlarında kullanılır.</p>
        <div style="display:flex;gap:10px;max-width:500px;align-items:flex-end">
          <div class="form-group" style="flex:1"><label>Numara (ülke kodu ile)</label><input type="text" id="set-whatsapp" placeholder="905344250782"></div>
          <button class="btn btn-success" onclick="saveWhatsapp()">💾 Kaydet</button>
        </div>
      </div>
      <div class="card">
        <h3>IBAN Yönetimi</h3>
        <div style="display:grid;gap:8px;max-width:600px;margin-bottom:16px">
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
            <input type="text" id="new-iban-label" placeholder="Banka adı" style="padding:9px 12px;border:1px solid #ddd;border-radius:6px;font-size:.9rem">
            <input type="text" id="new-iban-alici" placeholder="Alıcı adı soyadı" style="padding:9px 12px;border:1px solid #ddd;border-radius:6px;font-size:.9rem">
          </div>
          <div style="display:flex;gap:8px">
            <input type="text" id="new-iban-number" placeholder="TR00 0000 0000 0000 0000 0000 00" style="flex:1;padding:9px 12px;border:1px solid #ddd;border-radius:6px;font-size:.9rem">
            <button class="btn btn-primary" onclick="addIban()">+ Ekle</button>
          </div>
        </div>
        <table><thead><tr><th>Banka</th><th>Alıcı</th><th>IBAN</th><th>İşlem</th></tr></thead>
        <tbody id="iban-tbody"></tbody></table>
      </div>
      <div class="card">
        <h3>Telegram Bildirimleri</h3>
        <p style="font-size:.88rem;color:#888;margin-bottom:14px;">Yeni rezervasyon ve IBAN taleplerinde Telegram'a bildirim gönderilir.</p>
        <div style="display:grid;gap:14px;max-width:500px">
          <div class="form-group">
            <label>Bot Token <span style="font-size:.78rem;color:#aaa;font-weight:400">(@BotFather'dan alınır)</span></label>
            <input type="text" id="set-telegram-token" placeholder="1234567890:ABCdefGHIjklMNO...">
          </div>
          <div class="form-group">
            <label>Chat ID <span style="font-size:.78rem;color:#aaa;font-weight:400">(Kendi chat ID'niz)</span></label>
            <input type="text" id="set-telegram-chatid" placeholder="123456789">
          </div>
          <div style="display:flex;gap:10px;align-items:center">
            <button class="btn btn-success" onclick="saveTelegram()">💾 Kaydet</button>
            <button class="btn btn-sm" style="background:#229ed9;color:#fff" onclick="testTelegram()">📨 Test Mesajı Gönder</button>
          </div>
          <div id="telegram-test-result" style="font-size:.85rem;display:none"></div>
        </div>
      </div>
      <div class="card">
        <div style="display:grid;gap:14px;max-width:500px">
          <div class="form-group"><label>Hero Başlık</label><input type="text" id="set-hero-title"></div>
          <div class="form-group"><label>Hero Alt Başlık</label><input type="text" id="set-hero-subtitle"></div>
          <button class="btn btn-primary" onclick="saveSettings()" style="width:fit-content">Kaydet</button>
        </div>
      </div>
      <div class="card">
        <h3>Şifre Değiştir</h3>
        <div style="display:grid;gap:12px;max-width:400px">
          <div class="form-group"><label>Yeni Şifre</label><input type="password" id="new-pass"></div>
          <div class="form-group"><label>Şifre Tekrar</label><input type="password" id="new-pass2"></div>
          <button class="btn btn-warning" onclick="changePass()" style="width:fit-content">Güncelle</button>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Araç Düzenle Modal -->
<div class="modal-overlay" id="editCarModal">
  <div class="modal-box">
    <h3>Araç Düzenle</h3>
    <input type="hidden" id="edit-car-id">
    <div class="form-grid">
      <div class="form-group"><label>Araç Adı</label><input type="text" id="edit-car-name"></div>
      <div class="form-group"><label>Model Yılı</label><input type="number" id="edit-car-year"></div>
      <div class="form-group"><label>Günlük Fiyat</label><input type="number" id="edit-car-price"></div>
      <div class="form-group"><label>Görsel URL</label><input type="text" id="edit-car-image"></div>
      <div class="form-group"><label>Durum</label>
        <select id="edit-car-available"><option value="1">Aktif</option><option value="0">Pasif</option></select>
      </div>
    </div>
    <div class="modal-actions">
      <button class="btn btn-danger" onclick="closeModal('editCarModal')">İptal</button>
      <button class="btn btn-success" onclick="saveEditCar()">Kaydet</button>
    </div>
  </div>
</div>

<!-- Rezervasyon Detay Modal -->
<div class="modal-overlay" id="resDetailModal">
  <div class="modal-box" style="max-width:580px">
    <h3>Rezervasyon Detayı</h3>
    <div id="res-detail-content" style="font-size:.92rem;line-height:1.9"></div>
    <div class="modal-actions"><button class="btn btn-danger btn-sm" onclick="closeModal('resDetailModal')">Kapat</button></div>
  </div>
</div>

<!-- IBAN Gönder Modal -->
<div class="modal-overlay" id="sendIbanModal">
  <div class="modal-box" style="max-width:460px">
    <h3>🏦 IBAN Gönder</h3>
    <p style="font-size:.88rem;color:#666;margin-bottom:16px">Müşteri IBAN talep etti. Kayıtlı IBAN'lardan seçin veya manuel girin.</p>
    <input type="hidden" id="iban-res-id">
    <div class="form-group" style="margin-bottom:12px">
      <label>Kayıtlı IBAN'lardan Seç</label>
      <select id="iban-select" onchange="ibanSelectChange()"><option value="">— Manuel gir —</option></select>
    </div>
    <div class="form-group" style="margin-bottom:12px"><label>Alıcı Adı Soyadı</label><input type="text" id="iban-alici" placeholder="Örn: Ahmet Yılmaz"></div>
    <div class="form-group" style="margin-bottom:12px"><label>Banka Adı</label><input type="text" id="iban-banka" placeholder="Örn: Ziraat Bankası"></div>
    <div class="form-group"><label>IBAN Numarası</label><input type="text" id="iban-input" placeholder="TR00 0000 0000 0000 0000 0000 00" style="letter-spacing:1px"></div>
    <div class="modal-actions">
      <button class="btn btn-danger" onclick="closeModal('sendIbanModal')">İptal</button>
      <button class="btn btn-success" onclick="submitIban()">Gönder</button>
    </div>
  </div>
</div>

<?php include __DIR__ . '/admin_js.php'; ?>
