<?php
require_once '../config/database.php';
session_start();
if (!isset($_SESSION['yonetici'])) header('Location: login.php');
$site_id = (int)$_SESSION['site_id'];
$basari = $hata = '';

// ANKET EKLE
if (isset($_POST['anket_olustur'])) {
    $stmt = $pdo->prepare("INSERT INTO anketler (site_id, baslik, durum) VALUES (?, ?, 'pasif')");
    $stmt->execute([$site_id, $_POST['baslik']]);
    $anket_id = $pdo->lastInsertId();

    foreach ($_POST['sorular'] as $i => $soru) {
        if (!empty($soru['soru'])) {
            $stmt = $pdo->prepare("INSERT INTO anket_sorular (anket_id, soru, tip) VALUES (?, ?, ?)");
            $stmt->execute([$anket_id, $soru['soru'], $soru['tip']]);
            $soru_id = $pdo->lastInsertId();

            if ($soru['tip'] == 'secenek' && !empty($soru['secenekler'])) {
                $secenekler = explode(',', $soru['secenekler']);
                $insert_stmt = $pdo->prepare("INSERT INTO anket_siklari (soru_id, secenek) VALUES (?, ?)");
                foreach ($secenekler as $secenek) {
                    $secenek = trim($secenek);
                    if ($secenek) {
                        $insert_stmt->execute([$soru_id, $secenek]);
                    }
                }
            }
        }
    }
    $basari = "Anket oluşturuldu!";
    header('Location: anket.php');
    exit;
}

// ANKET DÜZENLE (GET ile veri çek)
$duzenle = null;
if (isset($_GET['duzenle']) && is_numeric($_GET['duzenle'])) {
    $stmt = $pdo->prepare("SELECT * FROM anketler WHERE id = ? AND site_id = ?");
    $stmt->execute([$_GET['duzenle'], $site_id]);
    $duzenle = $stmt->fetch();
    if ($duzenle) {
        $stmt = $pdo->prepare("SELECT * FROM anket_sorular WHERE anket_id = ? ORDER BY id ASC");
        $stmt->execute([$duzenle['id']]);
        $duzenle['sorular'] = $stmt->fetchAll();
        foreach ($duzenle['sorular'] as &$soru) {
            if ($soru['tip'] == 'secenek') {
                $stmt = $pdo->prepare("SELECT secenek FROM anket_siklari WHERE soru_id = ? ORDER BY id ASC");
                $stmt->execute([$soru['id']]);
                $soru['secenekler'] = implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN));
            } else {
                $soru['secenekler'] = '';
            }
        }
    }
}

// ANKET GÜNCELLE (POST)
if (isset($_POST['anket_guncelle'])) {
    $anket_id = (int)$_POST['anket_id'];
    $stmt = $pdo->prepare("UPDATE anketler SET baslik = ? WHERE id = ? AND site_id = ?");
    $stmt->execute([$_POST['baslik'], $anket_id, $site_id]);

    // Mevcut soruları ve şıkları sil
    $pdo->prepare("DELETE FROM anket_cevaplar WHERE soru_id IN (SELECT id FROM anket_sorular WHERE anket_id = ? )")->execute([$anket_id]);
    $pdo->prepare("DELETE FROM anket_siklari WHERE soru_id IN (SELECT id FROM anket_sorular WHERE anket_id = ? )")->execute([$anket_id]);
    $pdo->prepare("DELETE FROM anket_sorular WHERE anket_id = ?")->execute([$anket_id]);

    foreach ($_POST['sorular'] as $i => $soru) {
        if (!empty($soru['soru'])) {
            $stmt = $pdo->prepare("INSERT INTO anket_sorular (anket_id, soru, tip) VALUES (?, ?, ?)");
            $stmt->execute([$anket_id, $soru['soru'], $soru['tip']]);
            $soru_id = $pdo->lastInsertId();

            if ($soru['tip'] == 'secenek' && !empty($soru['secenekler'])) {
                $secenekler = explode(',', $soru['secenekler']);
                $insert_stmt = $pdo->prepare("INSERT INTO anket_siklari (soru_id, secenek) VALUES (?, ?)");
                foreach ($secenekler as $secenek) {
                    $secenek = trim($secenek);
                    if ($secenek) {
                        $insert_stmt->execute([$soru_id, $secenek]);
                    }
                }
            }
        }
    }
    $basari = "Anket güncellendi!";
    header('Location: anket.php');
    exit;
}

// ANKET SİL
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $anket_id = (int)$_GET['sil'];
    $pdo->prepare("DELETE FROM anket_cevaplar WHERE anket_id = ?")->execute([$anket_id]);
    $pdo->prepare("DELETE FROM anket_siklari WHERE soru_id IN (SELECT id FROM anket_sorular WHERE anket_id = ? )")->execute([$anket_id]);
    $pdo->prepare("DELETE FROM anket_sorular WHERE anket_id = ?")->execute([$anket_id]);
    $pdo->prepare("DELETE FROM anketler WHERE id = ? AND site_id = ?")->execute([$anket_id, $site_id]);
    $basari = "Anket silindi!";
    header('Location: anket.php');
    exit;
}

// DURUM DEĞİŞTİR (Aktif/Pasif)
if (isset($_GET['toggle']) && is_numeric($_GET['toggle'])) {
    $anket_id = (int)$_GET['toggle'];
    $stmt = $pdo->prepare("SELECT durum FROM anketler WHERE id = ? AND site_id = ?");
    $stmt->execute([$anket_id, $site_id]);
    $mevcut = $stmt->fetchColumn();
    $yeni_durum = $mevcut == 'aktif' ? 'pasif' : 'aktif';
    $pdo->prepare("UPDATE anketler SET durum = ? WHERE id = ? AND site_id = ?")->execute([$yeni_durum, $anket_id, $site_id]);
    $basari = "Anket durumu güncellendi!";
    header('Location: anket.php');
    exit;
}

// RAPORLA (Kapat ve Yönlendir)
if (isset($_GET['raporla']) && is_numeric($_GET['raporla'])) {
    $anket_id = (int)$_GET['raporla'];

    // Anketi kapat
    $pdo->prepare("UPDATE anketler SET durum = 'kapali' WHERE id = ? AND site_id = ?")->execute([$anket_id, $site_id]);

    // Anket verilerini çek
    $stmt = $pdo->prepare("SELECT * FROM anketler WHERE id = ? AND site_id = ?");
    $stmt->execute([$anket_id, $site_id]);
    $anket = $stmt->fetch();

    // Sonuçları hesapla (örnek olarak metin + seçenekli)
    $icerik = "<h4>{$anket['baslik']}</h4>\n";
    $stmt = $pdo->prepare("SELECT * FROM anket_sorular WHERE anket_id = ? ORDER BY id ASC");
    $stmt->execute([$anket_id]);
    $sorular = $stmt->fetchAll();

    foreach ($sorular as $soru) {
        $icerik .= "<p><strong>{$soru['soru']}</strong></p>\n";
        if ($soru['tip'] == 'secenek') {
            $stmt = $pdo->prepare("SELECT s.secenek, COUNT(c.id) AS oy_sayisi
              FROM anket_siklari s
              LEFT JOIN anket_cevaplar c ON c.cevap = s.id AND c.soru_id = s.soru_id
              WHERE s.soru_id = ?
              GROUP BY s.id");
            $stmt->execute([$soru['id']]);
            $sonuclar = $stmt->fetchAll();
            $toplam_oy = array_sum(array_column($sonuclar, 'oy_sayisi'));
            $icerik .= "<ul>\n";
            foreach ($sonuclar as $sonuc) {
                $percent = $toplam_oy > 0 ? round($sonuc['oy_sayisi'] / $toplam_oy * 100, 1) : 0;
                $icerik .= "<li>{$sonuc['secenek']} : {$sonuc['oy_sayisi']} oy (%{$percent})</li>\n";
            }
            $icerik .= "</ul>\n";
        } else {
            $stmt = $pdo->prepare("SELECT cevap FROM anket_cevaplar WHERE soru_id = ?");
            $stmt->execute([$soru['id']]);
            $cevaplar = $stmt->fetchAll(PDO::FETCH_COLUMN);
            $icerik .= "<ul>\n";
            foreach ($cevaplar as $cevap) {
                $icerik .= "<li>" . htmlspecialchars($cevap) . "</li>\n";
            }
            $icerik .= "</ul>\n";
        }
    }

    // Rapor tablosuna ekle
    $pdo->prepare("INSERT INTO raporlar (site_id, tip, baslik, icerik, durum) VALUES (?, 'anket', ?, ?, 'aktif')")
        ->execute([$site_id, $anket['baslik'], $icerik]);

    $basari = "Anket raporlandı ve üyeler için aktif hale getirildi!";
    header('Location: anket.php');
    exit;
}

// ANKET LİSTESİ
$anketler = $pdo->prepare("SELECT * FROM anketler WHERE site_id = ? ORDER BY olusturma_tarihi DESC");
$anketler->execute([$site_id]);
$anketler = $anketler->fetchAll();
?>
<?php include '../inc/header.php'; ?>
<?php include '../inc/sidebar.php'; ?>
<?php include '../inc/navbar.php'; ?>
<div class="content-wrapper">
  <div class="content-header"><div class="container-fluid"><h1>Anket Yönetimi</h1></div></div>
  <section class="content"><div class="container-fluid">
    <?php if($basari): ?><div class="alert alert-success"><?= $basari ?></div><?php endif; ?>

    <!-- YENİ ANKET OLUŞTUR / DÜZENLE -->
    <div class="card card-info mb-4">
      <div class="card-header"><h3 class="card-title"><?= $duzenle ? 'Anket Düzenle' : 'Yeni Anket Oluştur' ?></h3></div>
      <div class="card-body">
        <form method="post" id="anketForm">
          <?php if($duzenle): ?><input type="hidden" name="anket_id" value="<?= $duzenle['id'] ?>"><?php endif; ?>
          <div class="form-group">
            <label>Anket Başlığı</label>
            <input type="text" name="baslik" class="form-control" value="<?= htmlspecialchars($duzenle['baslik'] ?? '') ?>" required>
          </div>
          <div id="sorular">
            <?php 
            $soru_sayisi = 0;
            if ($duzenle && !empty($duzenle['sorular'])) {
                foreach ($duzenle['sorular'] as $soru) {
                    $soru_sayisi++;
                    ?>
                    <div class="soru mb-3 p-3 border rounded">
                      <div class="form-group">
                        <label>Soru</label>
                        <input type="text" name="sorular[<?=$soru_sayisi?>][soru]" class="form-control" value="<?= htmlspecialchars($soru['soru']) ?>" required>
                      </div>
                      <div class="form-group">
                        <label>Cevap Tipi</label>
                        <select name="sorular[<?=$soru_sayisi?>][tip]" class="form-control cevap-tipi" onchange="toggleSecenekler(this)">
                          <option value="secenek" <?= $soru['tip'] == 'secenek' ? 'selected' : '' ?>>Seçenekli</option>
                          <option value="metin" <?= $soru['tip'] == 'metin' ? 'selected' : '' ?>>Metin</option>
                        </select>
                      </div>
                      <div class="secenekler" style="display: <?= $soru['tip'] == 'secenek' ? 'block' : 'none' ?>;">
                        <label>Seçenekler (virgülle ayırın)</label>
                        <input type="text" name="sorular[<?=$soru_sayisi?>][secenekler]" class="form-control mb-1" value="<?= htmlspecialchars($soru['secenekler']) ?>" placeholder="Evet, Hayır, Belki">
                      </div>
                    </div>
                    <?php
                }
            } else {
                $soru_sayisi = 1;
                ?>
                <div class="soru mb-3 p-3 border rounded">
                  <div class="form-group">
                    <label>Soru</label>
                    <input type="text" name="sorular[1][soru]" class="form-control" required>
                  </div>
                  <div class="form-group">
                    <label>Cevap Tipi</label>
                    <select name="sorular[1][tip]" class="form-control cevap-tipi" onchange="toggleSecenekler(this)">
                      <option value="secenek">Seçenekli</option>
                      <option value="metin">Metin</option>
                    </select>
                  </div>
                  <div class="secenekler">
                    <label>Seçenekler (virgülle ayırın)</label>
                    <input type="text" name="sorular[1][secenekler]" class="form-control mb-1" placeholder="Evet, Hayır, Belki">
                  </div>
                </div>
                <?php
            }
            ?>
          </div>
          <button type="button" class="btn btn-secondary" onclick="yeniSoruEkle(<?= $soru_sayisi ?>)">+ Soru Ekle</button>
          <div class="text-right mt-3">
            <button name="<?= $duzenle ? 'anket_guncelle' : 'anket_olustur' ?>" class="btn btn-info btn-lg"><?= $duzenle ? 'Güncelle' : 'Oluştur' ?></button>
          </div>
        </form>
      </div>
    </div>

    <!-- ANKET LİSTESİ -->
    <div class="card">
      <div class="card-header"><h3 class="card-title">Anketler</h3></div>
      <div class="card-body table-responsive p-0">
        <table class="table table-hover">
          <thead>
            <tr>
              <th>Başlık</th>
              <th>Durum</th>
              <th>Tarih</th>
              <th>İstatistik</th>
              <th>İşlem</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($anketler as $a): ?>
            <?php 
            $toplam_uye = $pdo->query("SELECT COUNT(*) FROM uyeler WHERE site_id = $site_id AND aktif = 1")->fetchColumn();
            $katilim = $pdo->prepare("SELECT COUNT(DISTINCT uye_id) FROM anket_cevaplar WHERE anket_id = ?");
            $katilim->execute([$a['id']]);
            $katilim_sayi = $katilim->fetchColumn();
            $beklenen = $toplam_uye - $katilim_sayi;
            ?>
            <tr>
              <td><?= htmlspecialchars($a['baslik']) ?></td>
              <td><span class="badge <?= $a['durum']=='aktif'?'bg-success':($a['durum']=='pasif'?'bg-warning':'bg-secondary') ?>"><?= ucfirst($a['durum']) ?></span></td>
              <td><?= date('d.m.Y', strtotime($a['olusturma_tarihi'])) ?></td>
              <td>
                <small>Tanımlı: <?= $toplam_uye ?> | Katılan: <?= $katilim_sayi ?> | Beklenen: <?= $beklenen ?></small>
              </td>
              <td>
                <a href="?toggle=<?= $a['id'] ?>" class="btn btn-<?= $a['durum']=='aktif'?'warning':'success' ?> btn-sm"><i class="fas fa-toggle-<?= $a['durum']=='aktif'?'off':'on' ?>"></i></a>
                <a href="?duzenle=<?= $a['id'] ?>" class="btn btn-info btn-sm"><i class="fas fa-edit"></i></a>
                <a href="?raporla=<?= $a['id'] ?>" class="btn btn-primary btn-sm"><i class="fas fa-chart-bar"></i> Raporla</a>
                <a href="?sil=<?= $a['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash"></i></a>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div></section>
</div>
<script>
let soruSayisi = <?= $soru_sayisi ?>;
function yeniSoruEkle() {
  soruSayisi++;
  const div = document.createElement('div');
  div.className = 'soru mb-3 p-3 border rounded';
  div.innerHTML = `
    <div class="form-group">
      <label>Soru</label>
      <input type="text" name="sorular[${soruSayisi}][soru]" class="form-control" required>
    </div>
    <div class="form-group">
      <label>Cevap Tipi</label>
      <select name="sorular[${soruSayisi}][tip]" class="form-control cevap-tipi" onchange="toggleSecenekler(this)">
        <option value="secenek">Seçenekli</option>
        <option value="metin">Metin</option>
      </select>
    </div>
    <div class="secenekler">
      <label>Seçenekler (virgülle ayırın)</label>
      <input type="text" name="sorular[${soruSayisi}][secenekler]" class="form-control mb-1" placeholder="Evet, Hayır, Belki">
    </div>
  `;
  document.getElementById('sorular').appendChild(div);
}
function toggleSecenekler(select) {
  const secenekler = select.closest('.soru').querySelector('.secenekler');
  secenekler.style.display = select.value == 'secenek' ? 'block' : 'none';
}
</script>
<?php include '../inc/footer.php'; ?>