<?php
// panel/anketler.php
require_once '../config/database.php';
session_start();
if (!isset($_SESSION['uye_id']) || !isset($_SESSION['site_id'])) {
    header('Location: login.php');
    exit;
}
$uye_id = (int)$_SESSION['uye_id'];
$site_id = (int)$_SESSION['site_id'];
$hata = '';
$basari = '';

// Oy gönderme / güncelleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['oy_gonder'])) {
    $anket_id = (int)$_POST['anket_id'];
    $cevaplar = $_POST['cevaplar'] ?? [];
    if ($anket_id <= 0 || empty($cevaplar)) {
        $hata = 'Lütfen tüm soruları cevaplayın.';
    } else {
        $stmt = $pdo->prepare("SELECT id FROM anketler WHERE id = ? AND site_id = ? AND durum = 'aktif'");
        $stmt->execute([$anket_id, $site_id]);
        if (!$stmt->fetch()) {
            $hata = 'Anket aktif değil veya bulunamadı.';
        } else {
            // Eski cevapları sil
            $pdo->prepare("DELETE FROM anket_cevaplar WHERE anket_id = ? AND uye_id = ?")->execute([$anket_id, $uye_id]);
            // Yeni cevapları ekle (secenek için id, metin için metin)
            $insert_stmt = $pdo->prepare("INSERT INTO anket_cevaplar (anket_id, soru_id, uye_id, cevap) VALUES (?, ?, ?, ?)");
            foreach ($cevaplar as $soru_id => $cevap) {
                $insert_stmt->execute([$anket_id, $soru_id, $uye_id, $cevap]);
            }
            $basari = 'Oyunuz kaydedildi, teşekkürler!';
        }
    }
}

// Liste için aktif anketler
$anketler = $pdo->prepare("SELECT * FROM anketler WHERE site_id = ? AND durum = 'aktif' ORDER BY olusturma_tarihi DESC");
$anketler->execute([$site_id]);
$anketler = $anketler->fetchAll();

// Detay için anket verisi
$anket = null;
$sorular = [];
$kullanici_cevaplar = [];
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $pdo->prepare("SELECT * FROM anketler WHERE id = ? AND site_id = ? AND durum = 'aktif'");
    $stmt->execute([$id, $site_id]);
    $anket = $stmt->fetch();
    if ($anket) {
        $stmt = $pdo->prepare("SELECT * FROM anket_sorular WHERE anket_id = ? ORDER BY id ASC");
        $stmt->execute([$id]);
        $sorular = $stmt->fetchAll();
        foreach ($sorular as &$soru) {
            if ($soru['tip'] == 'secenek') {
                $stmt = $pdo->prepare("SELECT id, secenek FROM anket_siklari WHERE soru_id = ? ORDER BY id ASC");
                $stmt->execute([$soru['id']]);
                $soru['secenekler'] = $stmt->fetchAll();
            }
        }
        // Kullanıcı cevapları
        $stmt = $pdo->prepare("SELECT soru_id, cevap FROM anket_cevaplar WHERE anket_id = ? AND uye_id = ?");
        $stmt->execute([$id, $uye_id]);
        $kullanici_cevaplar = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    } else {
        $hata = 'Anket bulunamadı veya aktif değil.';
    }
}
?>
<?php include '../inc/header.php'; ?>
<?php include '../inc/sidebar.php'; ?>
<?php include '../inc/navbar.php'; ?>
<div class="content-wrapper">
  <section class="content-header">
    <div class="container-fluid">
      <h1>Anketler</h1>
    </div>
  </section>
  <section class="content">
    <div class="container-fluid">
      <?php if ($hata): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($hata) ?></div>
      <?php endif; ?>
      <?php if ($basari): ?>
        <div class="alert alert-success"><?= htmlspecialchars($basari) ?></div>
      <?php endif; ?>
      <?php if (!$anket): ?>
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">Aktif Anketler</h3>
          </div>
          <div class="card-body">
            <?php if (empty($anketler)): ?>
              <div class="alert alert-info">Aktif anket bulunmamaktadır.</div>
            <?php else: ?>
              <div class="list-group">
                <?php foreach ($anketler as $a): ?>
                  <a href="?id=<?= $a['id'] ?>" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                    <div>
                      <strong><?= htmlspecialchars($a['baslik']) ?></strong><br>
                      <small class="text-muted">Oluşturma: <?= date('d.m.Y', strtotime($a['olusturma_tarihi'])) ?></small>
                    </div>
                    <span class="btn btn-sm btn-outline-primary">Ankete Katıl</span>
                  </a>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      <?php else: ?>
        <div class="card">
          <div class="card-header">
            <h3 class="card-title"><?= htmlspecialchars($anket['baslik']) ?></h3>
            <div class="card-tools">
              <a href="anketler.php" class="btn btn-sm btn-secondary">Geri</a>
            </div>
          </div>
          <div class="card-body">
            <form method="post">
              <input type="hidden" name="anket_id" value="<?= $anket['id'] ?>">
              <?php foreach ($sorular as $soru): ?>
                <div class="mb-4">
                  <h5><?= htmlspecialchars($soru['soru']) ?></h5>
                  <?php if ($soru['tip'] == 'secenek'): ?>
                    <?php foreach ($soru['secenekler'] as $secenek): ?>
                      <div class="form-check">
                        <input class="form-check-input" type="radio" name="cevaplar[<?= $soru['id'] ?>]" value="<?= $secenek['id'] ?>" <?= ($kullanici_cevaplar[$soru['id']] ?? '') == $secenek['id'] ? 'checked' : '' ?> required>
                        <label class="form-check-label"><?= htmlspecialchars($secenek['secenek']) ?></label>
                      </div>
                    <?php endforeach; ?>
                  <?php else: ?>
                    <textarea name="cevaplar[<?= $soru['id'] ?>]" class="form-control" rows="3" required><?= htmlspecialchars($kullanici_cevaplar[$soru['id']] ?? '') ?></textarea>
                  <?php endif; ?>
                </div>
              <?php endforeach; ?>
              <button type="submit" name="oy_gonder" class="btn btn-success mt-3"><?= !empty($kullanici_cevaplar) ? 'Güncelle' : 'Anketi Tamamla' ?></button>
            </form>
          </div>
        </div>
      <?php endif; ?>
    </div>
  </section>
</div>
<?php include '../inc/footer.php'; ?>