<?php
require_once '../config/database.php';
session_start();
if (!isset($_SESSION['admin'])) header('Location: login.php');

$basari = $hata = '';

// Klasör oluştur
if (!is_dir('uploads/teklifler')) mkdir('uploads/teklifler', 0755, true);

// EKLE / DÜZENLE
if (isset($_POST['kaydet'])) {
    $id = $_POST['id'] ?? null;
    $banner = $_POST['mevcut_banner'] ?? '';
    
    if (!empty($_FILES['banner']['name'])) {
        $banner = 'uploads/teklifler/' . time() . '_' . basename($_FILES['banner']['name']);
        move_uploaded_file($_FILES['banner']['tmp_name'], $banner);
    }
    
    $data = [
        $_POST['baslik'],
        $_POST['aciklama'],
        $banner,
        $_POST['gecerlilik_tarihi'],
        $_SESSION['admin'], // ekleyen_admin
    ];
    
    if ($id) {
        $sql = "UPDATE ozel_teklifler SET baslik=?, aciklama=?, banner=?, gecerlilik_tarihi=?, ekleyen_admin=? WHERE id=?";
        $data[] = $id;
    } else {
        $sql = "INSERT INTO ozel_teklifler (baslik, aciklama, banner, gecerlilik_tarihi, ekleyen_admin) VALUES (?,?,?,?,?)";
    }
    
    try {
        $pdo->prepare($sql)->execute($data);
        $basari = $id ? "Teklif güncellendi!" : "Teklif eklendi!";
    } catch (Exception $e) {
        $hata = "Hata: " . $e->getMessage();
    }
}

// SİL
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $id = (int)$_GET['sil'];
    $banner = $pdo->query("SELECT banner FROM ozel_teklifler WHERE id=$id")->fetchColumn();
    if ($banner && file_exists($banner)) unlink($banner);
    $pdo->prepare("DELETE FROM ozel_teklifler WHERE id=?")->execute([$id]);
    $basari = "Teklif silindi!";
}

// SIRA GÜNCELLE (AJAX)
if (isset($_POST['sira_guncelle'])) {
    $siralar = $_POST['sira'];
    foreach ($siralar as $sira => $id) {
        $pdo->prepare("UPDATE ozel_teklifler SET sira = ? WHERE id = ?")->execute([$sira, $id]);
    }
    exit;
}

$teklifler = $pdo->query("SELECT * FROM ozel_teklifler ORDER BY sira ASC, id DESC")->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 class="m-0"><i class="fas fa-gift text-success"></i> Özel Teklifler & Kampanyalar</h1>
    </div>
  </div>
  
  <section class="content">
    <div class="container-fluid">
      <?php if($basari): ?>
        <div class="alert alert-success alert-dismissible">
          <button type="button" class="close" data-dismiss="alert">×</button>
          <?= htmlspecialchars($basari) ?>
        </div>
      <?php endif; ?>
      <?php if($hata): ?>
        <div class="alert alert-danger alert-dismissible">
          <button type="button" class="close" data-dismiss="alert">×</button>
          <?= htmlspecialchars($hata) ?>
        </div>
      <?php endif; ?>

      <!-- EKLE / DÜZENLE FORMU -->
      <div class="card card-success shadow mb-5">
        <div class="card-header bg-gradient-success">
          <h3 class="card-title"><i class="fas fa-plus"></i> Yeni Özel Teklif Ekle / Düzenle</h3>
        </div>
        <div class="card-body">
          <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="id" id="edit_id">
            <input type="hidden" name="mevcut_banner" id="mevcut_banner">
            
            <div class="row">
              <div class="col-md-8">
                <label>Başlık (Kartta Görünecek)</label>
                <input name="baslik" id="baslik" class="form-control" required>
              </div>
              <div class="col-md-4">
                <label>Geçerlilik Tarihi</label>
                <input type="date" name="gecerlilik_tarihi" id="gecerlilik_tarihi" class="form-control" required>
              </div>
              <div class="col-md-4">
                <label>Banner (600x400 önerilir)</label>
                <input type="file" name="banner" class="form-control" accept="image/*">
                <img id="banner_onizleme" class="mt-2 img-fluid rounded" style="max-height:150px; display:none;">
              </div>
              <div class="col-md-12">
                <label>Açıklama</label>
                <textarea name="aciklama" id="aciklama" class="form-control" rows="4" required></textarea>
              </div>
              <div class="col-12 text-right mt-3">
                <button name="kaydet" class="btn btn-success btn-lg">KAYDET</button>
              </div>
            </div>
          </form>
        </div>
      </div>

      <!-- TEKLİFLER LİSTESİ -->
      <div class="card">
        <div class="card-header bg-success">
          <h3 class="card-title text-white">Teklifler (Sıralamak için sürükleyin)</h3>
        </div>
        <div class="card-body">
          <div id="siralanabilir" class="row">
            <?php foreach($teklifler as $t): ?>
              <div class="col-lg-4 col-md-6 mb-4 teklif-kart" data-id="<?= $t['id'] ?>">
                <div class="card h-100 shadow border-success">
                  <?php if($t['banner']): ?>
                    <img src="<?= htmlspecialchars($t['banner']) ?>" class="card-img-top" style="height:180px; object-fit:contain; background:#f8f9fa;">
                  <?php else: ?>
                    <div class="bg-light d-flex align-items-center justify-content-center" style="height:180px;">
                      <i class="fas fa-gift fa-4x text-success"></i>
                    </div>
                  <?php endif; ?>
                  <div class="card-body text-center">
                    <h5 class="card-title text-success"><?= htmlspecialchars($t['baslik']) ?></h5>
                    <p class="text-muted small">
                      Geçerlilik: <?= date('d.m.Y', strtotime($t['gecerlilik_tarihi'])) ?>
                    </p>
                    <div class="btn-group">
                      <button onclick='doldur(<?= json_encode($t) ?>)' class="btn btn-warning btn-sm"><i class="fas fa-edit"></i></button>
                      <a href="?sil=<?= $t['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash"></i></a>
                    </div>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script>
function doldur(data) {
    document.getElementById('edit_id').value = data.id;
    document.getElementById('baslik').value = data.baslik || '';
    document.getElementById('aciklama').value = data.aciklama || '';
    document.getElementById('gecerlilik_tarihi').value = data.gecerlilik_tarihi || '';
    document.getElementById('mevcut_banner').value = data.banner || '';
    document.getElementById('banner_onizleme').src = data.banner || '';
    document.getElementById('banner_onizleme').style.display = data.banner ? 'block' : 'none';
    window.scrollTo(0,0);
}

$("#siralanabilir").sortable({
    placeholder: "ui-state-highlight",
    update: function() {
        var sira = {};
        $('.teklif-kart').each(function(index) {
            sira[index] = $(this).data('id');
        });
        $.post('', {sira_guncelle: 1, sira: sira});
    }
});
</script>

<?php include '../inc/footer.php'; ?>