<?php
require_once __DIR__ . '/api/db.php';
$db       = getDB();
$settings = [];
$res      = $db->query("SELECT * FROM settings");
while ($r = $res->fetchArray(SQLITE3_ASSOC)) $settings[$r['key']] = $r['value'];
$wa           = $settings['whatsapp_number'] ?? '905344250782';
$hero_title   = htmlspecialchars($settings['hero_title']   ?? 'Bayram öncesi erken rezervasyon!');
$hero_sub     = htmlspecialchars($settings['hero_subtitle'] ?? 'Avis Online Araç Kiralama');

$cars = [];
// 2 ucuz (en düşük fiyatlı 2)
$r = $db->query("SELECT * FROM cars WHERE available=1 ORDER BY daily_price ASC LIMIT 2");
while ($c = $r->fetchArray(SQLITE3_ASSOC)) $cars[] = $c;
// 2 orta (1500-2500 TL arası)
$r = $db->query("SELECT * FROM cars WHERE available=1 AND daily_price BETWEEN 1500 AND 2500 ORDER BY daily_price ASC LIMIT 2");
while ($c = $r->fetchArray(SQLITE3_ASSOC)) $cars[] = $c;
// 2 biraz pahalı (2500-4000 TL arası)
$r = $db->query("SELECT * FROM cars WHERE available=1 AND daily_price BETWEEN 2500 AND 4000 ORDER BY daily_price ASC LIMIT 2");
while ($c = $r->fetchArray(SQLITE3_ASSOC)) $cars[] = $c;
// 2 pahalı (en yüksek fiyatlı 2)
$r = $db->query("SELECT * FROM cars WHERE available=1 ORDER BY daily_price DESC LIMIT 2");
while ($c = $r->fetchArray(SQLITE3_ASSOC)) $cars[] = $c;
?>
<!DOCTYPE html>
<html style="font-size: 16px;" lang="tr-TR">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <title>Uygun Araç Kiralama | Araç Kiralama</title>
    <meta name="description" content="Bayrama özel araç kiralama da %30 indirim günleri başladı. Hemen online kirala indirimden yararlan"/>
    <link rel="canonical" href="https://avisuygunarac.com"/>
    <meta property="og:title" content="Uygun Araç Kiralama | Araç Kiralama"/>
    <meta property="og:description" content="Bayrama özel araç kiralama da %30 indirim günleri başladı."/>
    <meta property="og:url" content="https://avisuygunarac.com"/>
    <meta property="og:type" content="website"/>
    <meta name="google-site-verification" content="vGcekyBAbrHugaLELB-1r46342_h79c-io6zz-mjv6Y"/>
    <meta name="twitter:card" content="summary_large_image"/>
    <link rel="stylesheet" href="nicepage.css" media="screen">
    <link rel="stylesheet" href="Ana-Sayfa.css" media="screen">
    <script type="text/javascript" src="jquery.js" defer=""></script>
    <script type="text/javascript" src="nicepage.js" defer=""></script>
    <link rel="icon" href="images/favicon.png">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Open+Sans:300,400,600,700,800">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:100,200,300,400,500,600,700,800,900|Roboto+Slab:100,200,300,400,500,600,700,800,900">
    <script type="application/ld+json">{"@context":"http://schema.org","@type":"Organization","name":"Avis","logo":"images/Avis_logo.svg.png"}</script>
    <meta name="theme-color" content="#c8625f">
    <style>
      .rezervasyon-modal-overlay {
        display:none; position:fixed; top:0; left:0; width:100%; height:100%;
        background:rgba(0,0,0,0.6); z-index:9999; justify-content:center; align-items:center;
      }
      .rezervasyon-modal-overlay.active { display:flex; }
      .rezervasyon-modal {
        background:#fff; border-radius:12px; padding:32px; width:90%; max-width:560px;
        max-height:90vh; overflow-y:auto; position:relative;
      }
      .rezervasyon-modal h3 { margin:0 0 20px; font-size:1.4rem; color:#c0392b; }
      .modal-close { position:absolute; top:16px; right:20px; font-size:1.5rem; cursor:pointer; background:none; border:none; color:#666; }
      .form-group { margin-bottom:14px; }
      .form-group label { display:block; font-size:0.85rem; font-weight:600; margin-bottom:4px; color:#333; }
      .form-group input, .form-group select { width:100%; padding:10px 12px; border:1px solid #ddd; border-radius:6px; font-size:0.95rem; box-sizing:border-box; }
      .form-row { display:grid; grid-template-columns:1fr 1fr; gap:12px; }
      .btn-rez { width:100%; padding:14px; background:#c0392b; color:#fff; border:none; border-radius:8px; font-size:1rem; font-weight:700; cursor:pointer; margin-top:8px; }
      .btn-rez:hover { background:#a93226; }
      .btn-rez:disabled { opacity:0.6; cursor:not-allowed; }
      .fiyat-bilgi { background:#fff8f8; border:1px solid #f5c6c6; border-radius:8px; padding:12px 14px; margin-bottom:14px; font-size:0.9rem; color:#333; display:none; line-height:1.8; }
      .fiyat-bilgi .fiyat-satir { display:flex; justify-content:space-between; }
      .fiyat-bilgi .fiyat-satir.kapora { color:#c0392b; font-weight:700; border-top:1px dashed #f5c6c6; margin-top:6px; padding-top:6px; font-size:0.95rem; }
      .success-msg { text-align:center; padding:20px; }
      .success-msg .checkmark { font-size:3rem; }
      .success-msg h4 { color:#27ae60; margin:10px 0 6px; }
      .payment-options { display:flex; gap:10px; margin-bottom:4px; }
      .payment-option { flex:1; border:2px solid #ddd; border-radius:8px; padding:12px 10px; text-align:center; cursor:pointer; transition:all 0.2s; user-select:none; }
      .payment-option.active { border-color:#c0392b; background:#fff5f5; }
      .payment-option.disabled-opt { opacity:0.45; cursor:not-allowed; background:#f5f5f5; }
      .payment-option .pay-icon { font-size:1.4rem; display:block; margin-bottom:4px; }
      .payment-option .pay-label { font-size:0.82rem; font-weight:600; color:#333; }
      .payment-option .pay-sub { font-size:0.72rem; color:#999; margin-top:2px; }
      .iban-waiting { text-align:center; padding:28px 16px; display:none; }
      .iban-waiting .spinner { width:44px; height:44px; border:4px solid #f0f0f0; border-top-color:#c0392b; border-radius:50%; animation:spin 0.9s linear infinite; margin:0 auto 16px; }
      @keyframes spin { to { transform:rotate(360deg); } }
      .iban-waiting h4 { color:#333; margin-bottom:8px; }
      .iban-waiting p { color:#888; font-size:0.88rem; }
      .iban-result { background:#eafaf1; border:2px solid #27ae60; border-radius:10px; padding:18px; text-align:center; display:none; margin-top:8px; }
      .iban-result h4 { color:#27ae60; margin-bottom:10px; }
      .iban-number { font-size:1.05rem; font-weight:700; letter-spacing:1px; background:#fff; border:1px solid #b2dfdb; border-radius:6px; padding:10px 14px; display:inline-block; margin-top:4px; word-break:break-all; }
      .btn-copy { margin-top:10px; padding:8px 20px; background:#27ae60; color:#fff; border:none; border-radius:6px; cursor:pointer; font-size:0.88rem; font-weight:600; }
    </style>
</head>
<body data-home-page="index.php" class="u-body u-xl-mode">

<header class="u-clearfix u-header u-header" id="sec-454d">
    <div class="u-clearfix u-sheet u-sheet-1">
        <a href="index.php" class="u-image u-logo u-image-1" title="Ana Sayfa">
            <img src="images/Avis_logo.svg.png" class="u-logo-image u-logo-image-1">
        </a>
        <nav class="u-menu u-menu-dropdown u-offcanvas u-menu-1" data-responsive-from="XL">
            <div class="menu-collapse" style="font-size:1rem;letter-spacing:0px;font-weight:500;">
                <a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="#">
                    <svg class="u-svg-link" viewBox="0 0 24 24"><use xlink:href="#menu-hamburger"></use></svg>
                    <svg class="u-svg-content" version="1.1" id="menu-hamburger" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
                        <g><rect y="1" width="16" height="2"></rect><rect y="7" width="16" height="2"></rect><rect y="13" width="16" height="2"></rect></g>
                    </svg>
                </a>
            </div>
            <div style="background-color:#F0F8FF;" class="u-custom-menu u-nav-container">
                <ul class="u-nav u-spacing-2 u-unstyled u-nav-1">
                    <li class="u-nav-item"><a class="u-active-grey-5 u-button-style u-hover-grey-10 u-nav-link u-text-grey-90" href="index.php" style="padding:10px 20px;">Ana Sayfa</a></li>
                    <li class="u-nav-item"><a class="u-active-grey-5 u-button-style u-hover-grey-10 u-nav-link u-text-grey-90" href="araclar.php" style="padding:10px 20px;">Kiralık Araçlar</a></li>
                    <li class="u-nav-item"><a class="u-active-grey-5 u-button-style u-hover-grey-10 u-nav-link u-text-grey-90" href="havalimani.php" style="padding:10px 20px;">Havalimanları</a></li>
                </ul>
            </div>
            <div style="background-color:#F0F8FF;" class="u-custom-menu u-nav-container-collapse">
                <div class="u-black u-container-style u-inner-container-layout u-opacity u-opacity-95 u-sidenav">
                    <div class="u-inner-container-layout u-sidenav-overflow">
                        <div class="u-menu-close"></div>
                        <ul class="u-align-center u-nav u-popupmenu-items u-unstyled u-nav-2">
                            <li class="u-nav-item"><a class="u-button-style u-nav-link" href="index.php">Ana Sayfa</a></li>
                            <li class="u-nav-item"><a class="u-button-style u-nav-link" href="araclar.php">Kiralık Araçlar</a></li>
                            <li class="u-nav-item"><a class="u-button-style u-nav-link" href="havalimani.php">Havalimanları</a></li>
                        </ul>
                    </div>
                </div>
                <div class="u-black u-menu-overlay u-opacity u-opacity-70"></div>
            </div>
        </nav>
    </div>
</header>

<section class="u-align-center u-clearfix u-image u-section-1" id="carousel_62a4">
    <div class="u-clearfix u-sheet u-valign-middle-lg u-valign-middle-sm u-sheet-1">
        <div class="u-clearfix u-expanded-width u-gutter-0 u-layout-wrap u-layout-wrap-1">
            <div class="u-layout"><div class="u-layout-row">
                <div class="u-container-style u-layout-cell u-left-cell u-size-28 u-layout-cell-1">
                    <div class="u-container-layout u-valign-top u-container-layout-1">
                        <div class="u-border-9 u-border-palette-3-base u-line u-line-horizontal u-line-1"></div>
                        <h3 class="u-custom-font u-font-montserrat u-text u-text-palette-5-dark-2 u-text-1"><?= $hero_sub ?></h3>
                        <h1 class="u-custom-font u-font-roboto-slab u-text u-text-palette-3-base u-text-2"><?= $hero_title ?></h1>
                        <a href="https://wa.me/+<?= htmlspecialchars($wa) ?>" class="u-active-black u-border-none u-btn u-btn-round u-button-style u-hover-black u-palette-3-base u-radius-2 u-text-active-white u-text-hover-white u-btn-1" target="_blank">Rezervasyon oluştur</a>
                    </div>
                </div>
                <div class="u-container-style u-image u-layout-cell u-right-cell u-size-32 u-image-1">
                    <div class="u-container-layout u-container-layout-2"></div>
                </div>
            </div></div>
        </div>

        <div class="u-expanded-width u-list u-list-1">
            <div style="text-align:center;padding:32px 0 20px;">
                <h2 style="font-size:2rem;font-weight:700;color:#333;margin-bottom:8px;">Kiralık Araçlar</h2>
                <div style="width:60px;height:4px;background:#c0392b;margin:0 auto 8px;border-radius:2px;"></div>
                <p style="color:#888;font-size:0.95rem;">2026 model araç filomuzdan size uygun olanı seçin</p>
            </div>
            <div class="arac-grid arac-grid-4">
<?php foreach ($cars as $car):
    $seats    = $car['seats']        ?? 5;
    $luggage  = $car['luggage']      ?? 2;
    $trans    = $car['transmission'] ?? 'Manuel';
    $fuel     = $car['fuel']         ?? 'Benzin';
    $fuelIcon = $fuel === 'Elektrik' ? '⚡' : ($fuel === 'Hibrit' ? '🔋' : ($fuel === 'Dizel' ? '🛢️' : '⛽'));
    $transIcon = $trans === 'Otomatik' ? '🔄' : '🔧';
?>
                <div class="arac-kart">
                    <div class="arac-kart-ust">
                        <div class="arac-model-yil"><?= $car['model_year'] ?> Model</div>
                        <h3 class="arac-isim"><?= htmlspecialchars($car['name']) ?></h3>
                        <div class="arac-gorsel-wrap">
                            <img src="<?= htmlspecialchars($car['image_url']) ?>"
                                 onerror="this.src='images/Avis_logo.svg.png'"
                                 alt="<?= htmlspecialchars($car['name']) ?> kiralama">
                        </div>
                        <div class="arac-fiyat">
                            <span class="fiyat-label">Günlük</span>
                            <span class="fiyat-rakam"><?= number_format($car['daily_price'], 0, ',', '.') ?> TL</span>
                        </div>
                    </div>
                    <div class="arac-ozellikler">
                        <div class="ozellik-baslik">Araç Özellikleri</div>
                        <div class="ozellik-grid">
                            <div class="ozellik-item">👥 <?= $seats ?> Yetişkin</div>
                            <div class="ozellik-item">🧳 <?= $luggage ?> Büyük Bavul</div>
                            <div class="ozellik-item">🛡️ Yolcu Airbag</div>
                            <div class="ozellik-item">🔒 ABS</div>
                            <div class="ozellik-item"><?= $fuelIcon ?> <?= $fuel ?></div>
                            <div class="ozellik-item"><?= $transIcon ?> <?= $trans ?></div>
                        </div>
                        <div class="kiralama-kosullari">
                            <div class="kosul-baslik">Kiralama Koşulları</div>
                            <div class="kosul-item">✅ 21 Yaş ve Üstü</div>
                            <div class="kosul-item">✅ Ehliyet Yaşı 1 ve Üzeri</div>
                            <div class="kosul-item">✅ Kredi Kartı Gerekmez</div>
                        </div>
                    </div>
                    <div class="arac-butonlar">
                        <button onclick="openModal(<?= $car['id'] ?>, '<?= addslashes($car['name'].' '.$car['model_year']) ?>', <?= $car['daily_price'] ?>)" class="btn-rezervasyon">
                            Rezervasyon Oluştur
                        </button>
                        <a href="https://wa.me/+<?= htmlspecialchars($wa) ?>?text=<?= urlencode('Merhaba, '.$car['name'].' '.$car['model_year'].' Model için rezervasyon yapmak istiyorum.') ?>"
                           target="_blank" class="btn-whatsapp">
                            💬 WhatsApp ile Rezervasyon
                        </a>
                    </div>
                </div>
<?php endforeach; ?>
            </div><!-- /arac-grid -->
            <div style="text-align:center;padding:24px 0 40px;">
                <a href="araclar.php" style="display:inline-block;background:#c0392b;color:#fff;padding:14px 40px;border-radius:8px;font-weight:700;font-size:1rem;text-decoration:none;letter-spacing:.5px;">
                    🚗 Tüm Araçları Gör (<?= $db->querySingle("SELECT COUNT(*) FROM cars WHERE available=1") ?> Araç)
                </a>
            </div>
        </div><!-- /u-list -->
    </div>
</section>

<section class="u-align-left u-clearfix u-white u-section-2" id="carousel_3b94">
    <div class="u-clearfix u-sheet u-valign-middle u-sheet-1">
        <h2 class="u-align-center u-text u-text-1">Nasıl Çalışır?</h2>
        <div class="u-border-16 u-border-palette-3-base u-expanded-width u-line u-line-horizontal u-line-1"></div>
        <div class="u-align-center u-expanded-width-xs u-list u-list-1">
            <div class="u-repeater u-repeater-1">
                <div class="u-align-left u-container-style u-hover-feature u-list-item u-palette-5-light-2 u-repeater-item u-list-item-1">
                    <div class="u-container-layout u-similar-container u-container-layout-1">
                        <h5 class="u-text u-text-default u-text-2">1. Aracınızı Seçin &amp; Rezervasyon Yapın</h5>
                        <div class="u-expanded-height-lg u-expanded-height-xl u-expanded-height-xs u-palette-3-base u-shape u-shape-rectangle u-shape-1"></div>
                        <p class="u-text u-text-3">Yukarıdaki araç listesinden size uygun modeli seçin. "Rezervasyon Oluştur" butonuna tıklayarak tarih, havalimanı ve kişisel bilgilerinizi girin. Tüm süreç 2 dakikadan kısa sürer.</p>
                    </div>
                </div>
                <div class="u-align-left u-container-style u-hover-feature u-list-item u-palette-5-light-2 u-repeater-item u-list-item-2">
                    <div class="u-container-layout u-similar-container u-container-layout-2">
                        <h5 class="u-text u-text-default u-text-4">2. IBAN Talep Edin &amp; 5.000 TL Kapora Yatırın</h5>
                        <div class="u-expanded-height-lg u-expanded-height-xl u-expanded-height-xs u-palette-3-base u-shape u-shape-rectangle u-shape-2"></div>
                        <p class="u-text u-text-5">Rezervasyonunuz oluştuktan sonra "IBAN Talep Et" butonuna basın. Ekibimiz size ödeme bilgilerini iletir. Sabit 5.000 TL kapora bedelini Havale/EFT ile gönderin, dekontunuzu yükleyin. Kira bedeli araç tesliminde ödenir.</p>
                    </div>
                </div>
                <div class="u-align-left u-container-style u-hover-feature u-list-item u-palette-5-light-2 u-repeater-item u-list-item-3">
                    <div class="u-container-layout u-similar-container u-container-layout-3">
                        <h5 class="u-text u-text-default u-text-6">3. Aracınız Kapınıza veya Havalimanına Gelir</h5>
                        <div class="u-expanded-height-lg u-expanded-height-xl u-expanded-height-xs u-palette-3-base u-shape u-shape-rectangle u-shape-3"></div>
                        <p class="u-text u-text-7">Ödemeniz onaylandıktan sonra müşteri temsilcimiz sizi arar. Belirttiğiniz adrese veya havalimanına ücretsiz vale hizmetiyle aracınız teslim edilir. Kira bedelini teslim sırasında nakit veya kart ile ödersiniz.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<?php include __DIR__ . '/inc/wa_widget.php'; ?>

<footer class="u-align-center u-clearfix u-footer u-grey-80 u-footer" id="sec-101c">
    <div class="u-clearfix u-sheet u-sheet-1">
        <p class="u-small-text u-text u-text-variant u-text-1">Avis Oto Kiralama Hizmetleri - <?= date('Y') ?> Copyright</p>
    </div>
</footer>

<!-- Rezervasyon Modal -->
<div class="rezervasyon-modal-overlay" id="rezervasyonModal">
  <div class="rezervasyon-modal">
    <button class="modal-close" onclick="closeModal()">✕</button>
    <div id="modal-form-content">
      <h3>🚗 Rezervasyon Oluştur</h3>
      <p id="modal-car-name" style="font-weight:600;color:#333;margin-bottom:16px;"></p>
      <div class="fiyat-bilgi" id="fiyat-bilgi"></div>
      <div class="form-row">
        <div class="form-group"><label>Adınız Soyadınız *</label><input type="text" id="r-name" placeholder="Ad Soyad"></div>
        <div class="form-group"><label>Telefon *</label><input type="tel" id="r-phone" placeholder="05XX XXX XX XX"></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label>TC Kimlik No *</label><input type="text" id="r-tc" placeholder="12345678901" maxlength="11" pattern="[0-9]{11}"></div>
        <div class="form-group"><label>E-posta</label><input type="email" id="r-email" placeholder="ornek@mail.com"></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label>Alış Havalimanı *</label><select id="r-pickup"><option value="">Yükleniyor...</option></select></div>
        <div class="form-group"><label>İade Havalimanı *</label><select id="r-dropoff"><option value="">Yükleniyor...</option></select></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label>Alış Tarihi *</label><input type="date" id="r-pickup-date"></div>
        <div class="form-group"><label>İade Tarihi *</label><input type="date" id="r-dropoff-date"></div>
      </div>
      <div class="form-group"><label>Notlar</label><input type="text" id="r-notes" placeholder="Eklemek istediğiniz notlar..."></div>
      <div class="form-group">
        <label>Ödeme Yöntemi</label>
        <div class="payment-options">
          <div class="payment-option disabled-opt" id="pay-kk" title="Kredi kartı şu an aktif değil">
            <span class="pay-icon">💳</span>
            <div class="pay-label">Kredi Kartı</div>
            <div class="pay-sub">Şu an aktif değil</div>
          </div>
          <div class="payment-option active" id="pay-havale" onclick="selectPayment('havale')">
            <span class="pay-icon">🏦</span>
            <div class="pay-label">Havale / EFT</div>
            <div class="pay-sub">IBAN ile ödeme</div>
          </div>
        </div>
      </div>
      <div id="iban-talep-wrap">
        <button type="button" class="btn-rez" id="btn-iban-talep" style="background:#2980b9;display:none;" onclick="talepIban()">🏦 IBAN Talep Et</button>
      </div>
      <div id="iban-bilgi-notu" style="display:none;background:#fff8e1;border:1px solid #ffe082;border-radius:8px;padding:10px 14px;margin-top:8px;font-size:0.84rem;color:#7d5a00;line-height:1.5;">
        ℹ️ Havale/EFT ile ödeme yapmak için önce <b>Rezervasyon Oluştur</b> butonuna basın. Ardından <b>IBAN Talep Et</b> butonuyla ödeme bilgilerini alabilirsiniz. Muhasebe onayından sonra IBAN bilgisi ekranınıza yansıyacaktır.
      </div>
      <button class="btn-rez" id="btn-rezervasyon-gonder" onclick="submitRezervasyon()">Rezervasyon Oluştur</button>
    </div>

    <div class="iban-waiting" id="iban-waiting-screen">
      <div class="spinner"></div>
      <h4>IBAN Bekleniyor...</h4>
      <p>Muhasebe onayladıktan sonra IBAN bilgisi burada görünecek.<br>Lütfen bu sayfayı kapatmayın.</p>

      <!-- IBAN onaylandı kutuları -->
      <div id="iban-result-box" style="display:none;text-align:left;">
        <div style="text-align:center;margin-bottom:14px;">
          <span style="font-size:2rem;">✅</span>
          <h4 style="color:#27ae60;margin:6px 0 2px;">IBAN Bilgisi Onaylandı!</h4>
          <p style="font-size:0.82rem;color:#e67e22;">⏱ Kalan süre: <b id="iban-countdown"></b></p>
        </div>

        <!-- Ödeme özeti kutusu -->
        <div style="background:#fff8e1;border:1px solid #ffe082;border-radius:8px;padding:12px 16px;margin-bottom:12px;">
          <div style="font-size:0.75rem;color:#888;font-weight:600;margin-bottom:6px;">ÖDEME ÖZETİ</div>
          <div id="odeme-ozet-kira" style="display:flex;justify-content:space-between;font-size:0.88rem;color:#555;margin-bottom:4px;">
            <span id="odeme-ozet-label">Kira bedeli</span><span id="odeme-ozet-tutar" style="font-weight:600;"></span>
          </div>
          <div style="display:flex;justify-content:space-between;font-size:0.95rem;color:#c0392b;font-weight:700;border-top:1px dashed #ffe082;padding-top:6px;margin-top:4px;">
            <span>💳 Şimdi Ödenecek (Kapora)</span><span>5.000 TL</span>
          </div>
          <div style="font-size:0.75rem;color:#888;margin-top:6px;">Kira bedeli araç tesliminde ayrıca tahsil edilir.</div>
        </div>

        <!-- Banka kutusu -->
        <div style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:8px;padding:12px 16px;margin-bottom:10px;display:flex;justify-content:space-between;align-items:center;">
          <div>
            <div style="font-size:0.75rem;color:#888;font-weight:600;margin-bottom:2px;">BANKA</div>
            <div id="iban-banka-display" style="font-size:0.95rem;font-weight:700;color:#333;"></div>
          </div>
          <span style="font-size:1.2rem;">🏦</span>
        </div>

        <!-- Alıcı adı kutusu -->
        <div style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:8px;padding:12px 16px;margin-bottom:10px;display:flex;justify-content:space-between;align-items:center;">
          <div style="flex:1;">
            <div style="font-size:0.75rem;color:#888;font-weight:600;margin-bottom:2px;">ALICI ADI SOYADI</div>
            <div id="iban-alici-display" style="font-size:0.95rem;font-weight:700;color:#333;"></div>
          </div>
          <button onclick="copyText('iban-alici-display', this)" style="background:#6c757d;color:#fff;border:none;border-radius:6px;padding:6px 12px;font-size:0.78rem;cursor:pointer;white-space:nowrap;margin-left:10px;">📋 Kopyala</button>
        </div>

        <!-- IBAN numarası kutusu -->
        <div style="background:#eafaf1;border:2px solid #27ae60;border-radius:8px;padding:12px 16px;margin-bottom:14px;display:flex;justify-content:space-between;align-items:center;">
          <div style="flex:1;">
            <div style="font-size:0.75rem;color:#27ae60;font-weight:600;margin-bottom:2px;">IBAN NUMARASI</div>
            <div id="iban-display" style="font-size:0.9rem;font-weight:700;color:#1a5c38;letter-spacing:1px;word-break:break-all;"></div>
          </div>
          <button onclick="copyText('iban-display', this)" style="background:#27ae60;color:#fff;border:none;border-radius:6px;padding:6px 12px;font-size:0.78rem;cursor:pointer;white-space:nowrap;margin-left:10px;">📋 Kopyala</button>
        </div>

        <!-- Dekont yükleme -->
        <div style="background:#fff;border:2px dashed #c0392b;border-radius:8px;padding:16px;text-align:center;">
          <p style="font-size:0.85rem;color:#555;margin-bottom:10px;">💳 Ödemenizi yaptıktan sonra dekontunuzu yükleyin.</p>
          <input type="file" id="dekont-input" accept="image/*,.pdf" style="display:none;" onchange="dekontSecildi(this)">
          <button onclick="document.getElementById('dekont-input').click()" id="btn-dekont-sec" style="background:#c0392b;color:#fff;border:none;border-radius:6px;padding:10px 20px;font-size:0.9rem;font-weight:700;cursor:pointer;">📎 Dekont Yükle</button>
          <div id="dekont-dosya-adi" style="font-size:0.8rem;color:#888;margin-top:8px;"></div>
          <button id="btn-dekont-gonder" onclick="dekontGonder()" style="display:none;background:#27ae60;color:#fff;border:none;border-radius:6px;padding:10px 20px;font-size:0.9rem;font-weight:700;cursor:pointer;margin-top:8px;">✅ Dekontu Gönder</button>
        </div>
      </div>

      <!-- Süre doldu -->
      <div id="iban-expired-box" style="display:none;background:#fff3cd;border:2px solid #f39c12;border-radius:10px;padding:18px;margin-top:8px;text-align:center;">
        <p style="font-size:1.5rem;">⏰</p>
        <h4 style="color:#856404;margin:8px 0;">Süre Doldu</h4>
        <p style="font-size:0.88rem;color:#666;">IBAN görüntüleme süresi (15 dk) doldu.<br>Lütfen tekrar IBAN talep edin veya bizimle iletişime geçin.</p>
      </div>
    </div>

    <div class="success-msg" id="modal-success" style="display:none;">
      <div class="checkmark">✅</div>
      <h4>Rezervasyonunuz Başarıyla Alınmıştır!</h4>
      <p style="color:#555;font-size:0.9rem;line-height:1.6;">Kontroller sağlanmaktadır.<br>Müşteri temsilcisi sizinle iletişime geçecektir.</p>
      <p id="redirect-countdown" style="color:#c0392b;font-size:0.85rem;margin-top:10px;"></p>
    </div>
  </div>
</div>

<script>
const API = 'api/';
let selectedCarId = null, selectedCarPrice = 0, selectedPayment = 'havale';
let ibanPollInterval = null, currentReservationId = null;

// Havalimanlarını yükle
fetch(API + 'airports.php').then(r=>r.json()).then(airports => {
  ['r-pickup','r-dropoff'].forEach(id => {
    const sel = document.getElementById(id);
    sel.innerHTML = '<option value="">Havalimanı seçin...</option>';
    airports.forEach(a => { const o = document.createElement('option'); o.value = a.name; o.textContent = a.name; sel.appendChild(o); });
  });
});

function openModal(carId, carName, price) {
  selectedCarId = carId; selectedCarPrice = price; selectedPayment = 'havale';
  currentReservationId = null;
  document.getElementById('modal-car-name').textContent = '🚘 ' + carName;
  document.getElementById('modal-form-content').style.display = 'block';
  document.getElementById('modal-success').style.display = 'none';
  document.getElementById('iban-waiting-screen').style.display = 'none';
  document.getElementById('iban-result-box').style.display = 'none';
  document.getElementById('iban-expired-box').style.display = 'none';
  document.getElementById('fiyat-bilgi').style.display = 'none';
  document.getElementById('btn-iban-talep').style.display = 'none';
  document.getElementById('iban-bilgi-notu').style.display = 'none';
  document.getElementById('odeme-ozet-label').textContent = 'Kira bedeli';
  document.getElementById('odeme-ozet-tutar').textContent = '';
  document.getElementById('btn-rezervasyon-gonder').style.display = 'block';
  document.getElementById('pay-havale').classList.add('active');
  document.getElementById('rezervasyonModal').classList.add('active');
  const today = new Date().toISOString().split('T')[0];
  document.getElementById('r-pickup-date').min = today;
  document.getElementById('r-dropoff-date').min = today;
}

function closeModal() {
  if (ibanPollInterval) { clearInterval(ibanPollInterval); ibanPollInterval = null; }
  if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
  document.getElementById('rezervasyonModal').classList.remove('active');
  ['r-name','r-phone','r-tc','r-email','r-notes'].forEach(id => document.getElementById(id).value = '');
  document.getElementById('r-pickup').value = '';
  document.getElementById('r-dropoff').value = '';
  document.getElementById('r-pickup-date').value = '';
  document.getElementById('r-dropoff-date').value = '';
}

function selectPayment(type) {
  if (type === 'kk') return;
  selectedPayment = type;
  document.getElementById('pay-havale').classList.toggle('active', type === 'havale');
}

document.addEventListener('change', function(e) {
  if (e.target.id === 'r-pickup-date' || e.target.id === 'r-dropoff-date') {
    const p = document.getElementById('r-pickup-date').value;
    const d = document.getElementById('r-dropoff-date').value;
    if (p && d && selectedCarPrice) {
      const days = Math.ceil((new Date(d) - new Date(p)) / 86400000);
      if (days > 0) {
        const total = days * selectedCarPrice;
        const el = document.getElementById('fiyat-bilgi');
        el.innerHTML =
          '<div class="fiyat-satir"><span>📅 ' + days + ' gün × ' + selectedCarPrice.toLocaleString('tr-TR') + ' TL</span><span><b>' + total.toLocaleString('tr-TR') + ' TL</b></span></div>' +
          '<div class="fiyat-satir kapora"><span>💳 Şimdi ödenecek (Kapora)</span><span>5.000 TL</span></div>' +
          '<div style="font-size:0.78rem;color:#888;margin-top:4px;">Kira bedeli ' + total.toLocaleString('tr-TR') + ' TL araç tesliminde ayrıca ödenir.</div>';
        el.style.display = 'block';
        // Ödeme özet kutusunu da güncelle (IBAN ekranı için)
        document.getElementById('odeme-ozet-label').textContent = days + ' gün × ' + selectedCarPrice.toLocaleString('tr-TR') + ' TL kira';
        document.getElementById('odeme-ozet-tutar').textContent = total.toLocaleString('tr-TR') + ' TL';
      }
    }
  }
});

async function submitRezervasyon() {
  const name = document.getElementById('r-name').value.trim();
  const phone = document.getElementById('r-phone').value.trim();
  const tc    = document.getElementById('r-tc').value.trim();
  const pickup = document.getElementById('r-pickup').value;
  const dropoff = document.getElementById('r-dropoff').value;
  const pickupDate = document.getElementById('r-pickup-date').value;
  const dropoffDate = document.getElementById('r-dropoff-date').value;
  if (!name || !phone || !tc || !pickup || !dropoff || !pickupDate || !dropoffDate) { alert('Lütfen zorunlu alanları doldurun.'); return; }
  if (!/^\d{11}$/.test(tc)) { alert('TC Kimlik No 11 haneli olmalıdır.'); return; }
  const btn = document.getElementById('btn-rezervasyon-gonder');
  btn.textContent = 'Gönderiliyor...'; btn.disabled = true;
  try {
    const res = await fetch(API + 'reservations.php', {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ car_id: selectedCarId, customer_name: name, customer_phone: phone,
        customer_email: document.getElementById('r-email').value,
        tc_no: tc,
        pickup_airport: pickup, dropoff_airport: dropoff,
        pickup_date: pickupDate, dropoff_date: dropoffDate,
        payment_method: selectedPayment, notes: document.getElementById('r-notes').value })
    });
    if (res.ok) {
      const data = await res.json();
      currentReservationId = data.id;
      if (selectedPayment === 'havale') {
        document.getElementById('btn-rezervasyon-gonder').style.display = 'none';
        document.getElementById('btn-iban-talep').style.display = 'block';
        document.getElementById('iban-bilgi-notu').style.display = 'block';
      } else {
        document.getElementById('modal-form-content').style.display = 'none';
        document.getElementById('modal-success').style.display = 'block';
        startRedirectCountdown();
      }
    } else { alert('Bir hata oluştu.'); }
  } catch(e) { alert('Sunucuya bağlanılamadı.'); }
  finally { btn.textContent = 'Rezervasyon Oluştur'; btn.disabled = false; }
}

async function talepIban() {
  if (!currentReservationId) return;
  const btn = document.getElementById('btn-iban-talep');
  btn.textContent = 'Talep gönderiliyor...'; btn.disabled = true;
  try {
    await fetch(API + 'reservations.php?id=' + currentReservationId + '&action=request-iban', { method: 'POST' });
    document.getElementById('modal-form-content').style.display = 'none';
    document.getElementById('iban-waiting-screen').style.display = 'block';
    startIbanPolling();
  } catch(e) { alert('Hata oluştu.'); btn.textContent = '🏦 IBAN Talep Et'; btn.disabled = false; }
}

function startIbanPolling() {
  if (ibanPollInterval) clearInterval(ibanPollInterval);
  ibanPollInterval = setInterval(async () => {
    try {
      const res = await fetch(API + 'reservations.php?id=' + currentReservationId + '&action=iban-status');
      const data = await res.json();

      if (data.iban_expired == 1) {
        clearInterval(ibanPollInterval); ibanPollInterval = null;
        if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
        document.getElementById('iban-result-box').style.display = 'none';
        document.getElementById('iban-expired-box').style.display = 'block';
        document.querySelector('.iban-waiting .spinner').style.display = 'none';
        document.querySelector('.iban-waiting h4').style.display = 'none';
        document.querySelector('.iban-waiting p').style.display = 'none';
        return;
      }

      if (data.iban_sent) {
        clearInterval(ibanPollInterval); ibanPollInterval = null;
        // IBAN verisi JSON formatında gelebilir
        let ibanVal = data.iban_sent, aliciVal = '', bankaVal = '';
        try {
          const parsed = JSON.parse(data.iban_sent);
          ibanVal  = parsed.iban  || data.iban_sent;
          aliciVal = parsed.alici || '';
          bankaVal = parsed.banka || '';
        } catch(e) { ibanVal = data.iban_sent; }
        document.getElementById('iban-display').textContent      = ibanVal;
        document.getElementById('iban-alici-display').textContent = aliciVal || '—';
        document.getElementById('iban-banka-display').textContent = bankaVal || '—';
        document.getElementById('iban-result-box').style.display = 'block';
        document.querySelector('.iban-waiting .spinner').style.display = 'none';
        document.querySelector('.iban-waiting h4').style.display = 'none';
        document.querySelector('.iban-waiting p').style.display  = 'none';
        startCountdown(data.remaining_sec || 900);
      }
    } catch(e) {}
  }, 3000);
}

let countdownInterval = null;
function startCountdown(seconds) {
  if (countdownInterval) clearInterval(countdownInterval);
  let remaining = seconds;
  function update() {
    if (remaining <= 0) {
      clearInterval(countdownInterval);
      document.getElementById('iban-result-box').style.display = 'none';
      document.getElementById('iban-expired-box').style.display = 'block';
      return;
    }
    const m = Math.floor(remaining / 60);
    const s = remaining % 60;
    document.getElementById('iban-countdown').textContent = m + ':' + String(s).padStart(2,'0');
    remaining--;
  }
  update();
  countdownInterval = setInterval(update, 1000);
}

function copyText(elId, btn) {
  const text = document.getElementById(elId).textContent.trim();
  navigator.clipboard.writeText(text).then(() => {
    const orig = btn.textContent;
    btn.textContent = '✅ Kopyalandı!';
    setTimeout(() => btn.textContent = orig, 2000);
  });
}

function dekontSecildi(input) {
  const file = input.files[0];
  if (!file) return;
  document.getElementById('dekont-dosya-adi').textContent = '📄 ' + file.name;
  document.getElementById('btn-dekont-gonder').style.display = 'inline-block';
}

async function dekontGonder() {
  const input = document.getElementById('dekont-input');
  const file  = input.files[0];
  if (!file || !currentReservationId) return;
  const btn = document.getElementById('btn-dekont-gonder');
  btn.textContent = 'Yükleniyor...'; btn.disabled = true;
  try {
    const fd = new FormData();
    fd.append('dekont', file);
    fd.append('reservation_id', currentReservationId);
    await fetch(API + 'upload_dekont.php', { method: 'POST', body: fd });
  } catch(e) {}
  // Başarı ekranı göster
  if (ibanPollInterval) { clearInterval(ibanPollInterval); ibanPollInterval = null; }
  if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
  document.getElementById('iban-waiting-screen').style.display = 'none';
  document.getElementById('modal-success').style.display = 'block';
  startRedirectCountdown();
}

function startRedirectCountdown() {
  let sec = 10;
  const el = document.getElementById('redirect-countdown');
  function tick() {
    el.textContent = sec + ' saniye sonra ana sayfaya yönlendirileceksiniz...';
    if (sec <= 0) { window.location.href = 'index.php'; return; }
    sec--;
    setTimeout(tick, 1000);
  }
  tick();
}

document.getElementById('rezervasyonModal').addEventListener('click', function(e) {
  if (e.target === this) closeModal();
});
</script>
</body>
</html>
