<?php
// Zaten kuruluysa engelle
if (file_exists(__DIR__ . '/data/avis.db') && file_exists(__DIR__ . '/.installed')) {
    die('<h2>Sistem zaten kurulu.</h2><a href="index.php">Ana Sayfaya Git</a> | <a href="admin.php">Admin Paneli</a>');
}

$step   = (int)($_POST['step'] ?? $_GET['step'] ?? 1);
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step === 2) {
    $site_title    = trim($_POST['site_title']    ?? '');
    $whatsapp      = trim($_POST['whatsapp']      ?? '');
    $admin_pass    = trim($_POST['admin_pass']     ?? '');
    $admin_pass2   = trim($_POST['admin_pass2']    ?? '');
    $hero_title    = trim($_POST['hero_title']     ?? '');
    $hero_sub      = trim($_POST['hero_sub']       ?? '');
    $tg_token      = trim($_POST['tg_token']       ?? '');
    $tg_chat       = trim($_POST['tg_chat']        ?? '');

    if (!$site_title)  $errors[] = 'Site başlığı zorunlu.';
    if (!$whatsapp)    $errors[] = 'WhatsApp numarası zorunlu.';
    if (!preg_match('/^\d{10,15}$/', $whatsapp)) $errors[] = 'WhatsApp numarası sadece rakam olmalı (örn: 905344250782).';
    if (strlen($admin_pass) < 6) $errors[] = 'Admin şifresi en az 6 karakter olmalı.';
    if ($admin_pass !== $admin_pass2) $errors[] = 'Şifreler eşleşmiyor.';

    if (empty($errors)) {
        // config.php yaz
        $config = "<?php\n"
            . "define('TELEGRAM_BOT_TOKEN', " . var_export($tg_token, true) . ");\n"
            . "define('TELEGRAM_CHAT_ID',   " . var_export($tg_chat,  true) . ");\n"
            . "define('ADMIN_PASSWORD',     " . var_export($admin_pass, true) . ");\n"
            . "define('DB_PATH', __DIR__ . '/../data/avis.db');\n";
        file_put_contents(__DIR__ . '/api/config.php', $config);

        // data klasörü oluştur
        if (!is_dir(__DIR__ . '/data')) mkdir(__DIR__ . '/data', 0755, true);
        if (!is_dir(__DIR__ . '/data/dekontlar')) mkdir(__DIR__ . '/data/dekontlar', 0755, true);

        // DB kur
        require_once __DIR__ . '/api/db.php';
        $db = getDB();

        // Ayarları kaydet
        $sets = [
            'whatsapp_number' => $whatsapp,
            'site_title'      => $site_title,
            'hero_title'      => $hero_title ?: 'Uygun Fiyatlı Araç Kiralama',
            'hero_subtitle'   => $hero_sub   ?: 'Online Araç Kiralama',
            'telegram_token'  => $tg_token,
            'telegram_chat_id'=> $tg_chat,
        ];
        foreach ($sets as $k => $v) {
            $stmt = $db->prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (:k, :v)");
            $stmt->bindValue(':k', $k);
            $stmt->bindValue(':v', $v);
            $stmt->execute();
        }

        // Admin şifresini hash'le
        $stmt = $db->prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('admin_password', :v)");
        $stmt->bindValue(':v', password_hash($admin_pass, PASSWORD_DEFAULT));
        $stmt->execute();

        // Kurulum tamamlandı işareti
        file_put_contents(__DIR__ . '/.installed', date('Y-m-d H:i:s'));

        $step = 3;
    }
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Kurulum — Avis Araç Kiralama</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: 'Segoe UI', Arial, sans-serif; background: #f0f2f5; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
    .wrap { width: 100%; max-width: 560px; }
    .logo-area { text-align: center; margin-bottom: 28px; }
    .logo-area img { height: 52px; }
    .logo-area h1 { font-size: 1.1rem; color: #555; margin-top: 10px; font-weight: 400; }
    .card { background: #fff; border-radius: 14px; padding: 36px; box-shadow: 0 4px 24px rgba(0,0,0,.1); }
    .steps { display: flex; gap: 0; margin-bottom: 28px; }
    .step { flex: 1; text-align: center; font-size: .78rem; color: #bbb; padding-bottom: 10px; border-bottom: 3px solid #eee; }
    .step.active { color: #c0392b; border-color: #c0392b; font-weight: 700; }
    .step.done { color: #27ae60; border-color: #27ae60; }
    h2 { font-size: 1.2rem; color: #333; margin-bottom: 6px; }
    .sub { font-size: .85rem; color: #888; margin-bottom: 24px; }
    .form-group { margin-bottom: 16px; }
    .form-group label { display: block; font-size: .85rem; font-weight: 600; color: #555; margin-bottom: 5px; }
    .form-group label span { color: #c0392b; }
    .form-group input { width: 100%; padding: 11px 14px; border: 1.5px solid #ddd; border-radius: 7px; font-size: .95rem; transition: border .2s; }
    .form-group input:focus { outline: none; border-color: #c0392b; }
    .form-group small { font-size: .75rem; color: #aaa; margin-top: 4px; display: block; }
    .divider { border: none; border-top: 1px solid #f0f0f0; margin: 20px 0; }
    .section-title { font-size: .78rem; font-weight: 700; color: #aaa; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 14px; }
    .btn { width: 100%; padding: 13px; background: #c0392b; color: #fff; border: none; border-radius: 8px; font-size: 1rem; font-weight: 700; cursor: pointer; margin-top: 8px; transition: background .2s; }
    .btn:hover { background: #a93226; }
    .errors { background: #fdf2f2; border: 1px solid #f5c6c6; border-radius: 8px; padding: 12px 16px; margin-bottom: 18px; }
    .errors p { font-size: .85rem; color: #c0392b; margin-bottom: 3px; }
    .errors p::before { content: '⚠ '; }
    /* Adım 3 */
    .success-icon { font-size: 3.5rem; text-align: center; margin-bottom: 16px; }
    .success-links { display: grid; gap: 10px; margin-top: 20px; }
    .link-btn { display: block; padding: 13px; border-radius: 8px; text-align: center; text-decoration: none; font-weight: 700; font-size: .95rem; }
    .link-btn.primary { background: #c0392b; color: #fff; }
    .link-btn.secondary { background: #f0f2f5; color: #333; }
    .link-btn:hover { opacity: .88; }
    .info-box { background: #fff8e1; border: 1px solid #ffe082; border-radius: 8px; padding: 12px 16px; margin-top: 16px; font-size: .82rem; color: #7d5a00; line-height: 1.6; }
  </style>
</head>
<body>
<div class="wrap">
  <div class="logo-area">
    <img src="images/Avis_logo.svg.png" alt="Avis" onerror="this.style.display='none'">
    <h1>Araç Kiralama Sistemi Kurulumu</h1>
  </div>
  <div class="card">
    <div class="steps">
      <div class="step <?= $step >= 1 ? ($step > 1 ? 'done' : 'active') : '' ?>">1. Hoş Geldiniz</div>
      <div class="step <?= $step >= 2 ? ($step > 2 ? 'done' : 'active') : '' ?>">2. Ayarlar</div>
      <div class="step <?= $step >= 3 ? 'done' : '' ?>">3. Tamamlandı</div>
    </div>

    <?php if ($step === 1): ?>
      <h2>Kuruluma Hoş Geldiniz</h2>
      <p class="sub">Bu sihirbaz sistemi birkaç adımda kurmanıza yardımcı olacak.</p>
      <p style="font-size:.88rem;color:#555;line-height:1.7;margin-bottom:20px">
        Kurulum tamamlandığında:<br>
        ✅ Veritabanı oluşturulacak<br>
        ✅ Admin şifreniz belirlenecek<br>
        ✅ WhatsApp ve Telegram ayarları yapılacak<br>
        ✅ Site içerikleri hazır olacak
      </p>
      <form method="POST">
        <input type="hidden" name="step" value="2">
        <button type="submit" class="btn">Kuruluma Başla →</button>
      </form>

    <?php elseif ($step === 2): ?>
      <h2>Site Ayarları</h2>
      <p class="sub">Aşağıdaki bilgileri doldurun. Tüm ayarlar daha sonra admin panelinden değiştirilebilir.</p>

      <?php if (!empty($errors)): ?>
        <div class="errors"><?php foreach ($errors as $e): ?><p><?= htmlspecialchars($e) ?></p><?php endforeach; ?></div>
      <?php endif; ?>

      <form method="POST">
        <input type="hidden" name="step" value="2">

        <div class="section-title">Site Bilgileri</div>
        <div class="form-group">
          <label>Site Başlığı <span>*</span></label>
          <input type="text" name="site_title" value="<?= htmlspecialchars($_POST['site_title'] ?? 'Uygun Araç Kiralama') ?>" placeholder="Uygun Araç Kiralama">
        </div>
        <div class="form-group">
          <label>Hero Başlık</label>
          <input type="text" name="hero_title" value="<?= htmlspecialchars($_POST['hero_title'] ?? '') ?>" placeholder="Uygun Fiyatlı Araç Kiralama">
        </div>
        <div class="form-group">
          <label>Hero Alt Başlık</label>
          <input type="text" name="hero_sub" value="<?= htmlspecialchars($_POST['hero_sub'] ?? '') ?>" placeholder="Online Araç Kiralama">
        </div>

        <hr class="divider">
        <div class="section-title">İletişim</div>
        <div class="form-group">
          <label>WhatsApp Numarası <span>*</span></label>
          <input type="text" name="whatsapp" value="<?= htmlspecialchars($_POST['whatsapp'] ?? '') ?>" placeholder="905344250782">
          <small>Ülke kodu dahil, boşluksuz (örn: 905344250782)</small>
        </div>

        <hr class="divider">
        <div class="section-title">Admin Girişi</div>
        <div class="form-group">
          <label>Admin Şifresi <span>*</span></label>
          <input type="password" name="admin_pass" placeholder="En az 6 karakter">
        </div>
        <div class="form-group">
          <label>Şifre Tekrar <span>*</span></label>
          <input type="password" name="admin_pass2" placeholder="Şifreyi tekrar girin">
        </div>

        <hr class="divider">
        <div class="section-title">Telegram Bildirimleri <span style="font-weight:400;color:#bbb">(İsteğe bağlı)</span></div>
        <div class="form-group">
          <label>Bot Token</label>
          <input type="text" name="tg_token" value="<?= htmlspecialchars($_POST['tg_token'] ?? '') ?>" placeholder="1234567890:ABCdefGHI...">
          <small>@BotFather'dan alınır. Boş bırakılabilir.</small>
        </div>
        <div class="form-group">
          <label>Chat ID</label>
          <input type="text" name="tg_chat" value="<?= htmlspecialchars($_POST['tg_chat'] ?? '') ?>" placeholder="123456789">
        </div>

        <button type="submit" class="btn">Kurulumu Tamamla ✓</button>
      </form>

    <?php elseif ($step === 3): ?>
      <div class="success-icon">🎉</div>
      <h2 style="text-align:center">Kurulum Tamamlandı!</h2>
      <p class="sub" style="text-align:center">Sistem başarıyla kuruldu ve kullanıma hazır.</p>
      <div class="success-links">
        <a href="index.php" class="link-btn primary">🌐 Siteye Git</a>
        <a href="admin.php" class="link-btn secondary">⚙️ Admin Paneline Git</a>
      </div>
      <div class="info-box">
        ⚠️ <strong>Güvenlik:</strong> Kurulum tamamlandıktan sonra <code>install.php</code> dosyasını silmeniz önerilir.
      </div>
    <?php endif; ?>
  </div>
</div>
</body>
</html>
