<?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/firmalar')) mkdir('uploads/firmalar', 0755, true);

// EKLE / DÜZENLE
if (isset($_POST['kaydet'])) {
    $id = $_POST['id'] ?? null;
    $banner = $_POST['mevcut_banner'] ?? '';
    if (!empty($_FILES['banner']['name'])) {
        $banner = 'uploads/firmalar/' . time() . '_' . basename($_FILES['banner']['name']);
        move_uploaded_file($_FILES['banner']['tmp_name'], $banner);
    }
    $data = [
        $_POST['baslik'],
        $_POST['firma_adi'],
        $banner,
        $_POST['web_site'],
        $_POST['telefon'],
        $_POST['email'],
        $_POST['aciklama'],
        (int)($_POST['sira'] ?? 0),
        isset($_POST['aktif']) ? 1 : 0
    ];
    if ($id) {
        $sql = "UPDATE anlasmali_firmalar SET baslik=?, firma_adi=?, banner_url=?, web_site=?, telefon=?, email=?, aciklama=?, sira=?, aktif=? WHERE id=?";
        $data[] = $id;
    } else {
        $sql = "INSERT INTO anlasmali_firmalar (baslik, firma_adi, banner_url, web_site, telefon, email, aciklama, sira, aktif) VALUES (?,?,?,?,?,?,?,?,?)";
    }
    try {
        $pdo->prepare($sql)->execute($data);
        $basari = $id ? "Firma güncellendi!" : "Firma 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_url FROM anlasmali_firmalar WHERE id=$id")->fetchColumn();
    if ($banner && file_exists($banner)) unlink($banner);
    $pdo->prepare("DELETE FROM anlasmali_firmalar WHERE id=?")->execute([$id]);
    $basari = "Firma silindi!";
}

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

$firmalar = $pdo->query("SELECT * FROM anlasmali_firmalar 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-handshake"></i> Anlaşmalı Firmalar</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-primary shadow mb-5">
        <div class="card-header bg-gradient-primary">
          <h3 class="card-title"><i class="fas fa-plus"></i> Yeni Firma 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-6">
                <label>Banner Altı Başlık (Gösterilecek Metin)</label>
                <input name="baslik" id="baslik" class="form-control" required>
              </div>
              <div class="col-md-6">
                <label>Firma Adı (İç Kullanım)</label>
                <input name="firma_adi" id="firma_adi" class="form-control">
              </div>
              <div class="col-md-4">
                <label>Web Sitesi</label>
                <input name="web_site" id="web_site" class="form-control" placeholder="https://">
              </div>
              <div class="col-md-4">
                <label>Telefon</label>
                <input name="telefon" id="telefon" class="form-control">
              </div>
              <div class="col-md-4">
                <label>E-posta</label>
                <input name="email" id="email" type="email" class="form-control">
              </div>
              <div class="col-md-2">
                <label>Sıra</label>
                <input name="sira" id="sira" type="number" class="form-control" value="0">
              </div>
              <div class="col-md-2 mt-4">
                <div class="form-check">
                  <input type="checkbox" name="aktif" id="aktif" class="form-check-input" checked>
                  <label class="form-check-label">Aktif</label>
                </div>
              </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 (Banner Altı Metin)</label>
                <textarea name="aciklama" id="aciklama" class="form-control" rows="3"></textarea>
              </div>
              <div class="col-12 text-right mt-3">
                <button name="kaydet" class="btn btn-primary btn-lg">KAYDET</button>
              </div>
            </div>
          </form>
        </div>
      </div>

      <!-- FİRMALAR LİSTESİ -->
      <div class="card">
        <div class="card-header">
          <h3 class="card-title">Firmalar (Sıralamak için sürükleyin)</h3>
        </div>
        <div class="card-body">
          <div id="siralanabilir" class="row">
            <?php foreach($firmalar as $f): ?>
              <div class="col-lg-4 col-md-6 mb-4 firma-kart" data-id="<?= $f['id'] ?>">
                <div class="card h-100 shadow">
                  <?php if($f['banner_url']): ?>
                    <img src="<?= htmlspecialchars($f['banner_url']) ?>" 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-image fa-4x text-muted"></i>
                    </div>
                  <?php endif; ?>
                  <div class="card-body text-center">
                    <h5 class="card-title"><?= htmlspecialchars($f['baslik'] ?: $f['firma_adi']) ?></h5>
                    <p class="text-muted small">
                      Sıra: <?= $f['sira'] ?> | 
                      <?= $f['aktif'] ? '<span class="badge badge-success">Aktif</span>' : '<span class="badge badge-secondary">Pasif</span>' ?>
                    </p>
                    <div class="btn-group">
                      <button onclick='doldur(<?= json_encode($f) ?>)' class="btn btn-warning btn-sm"><i class="fas fa-edit"></i></button>
                      <a href="?sil=<?= $f['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('firma_adi').value = data.firma_adi || '';
    document.getElementById('web_site').value = data.web_site || '';
    document.getElementById('telefon').value = data.telefon || '';
    document.getElementById('email').value = data.email || '';
    document.getElementById('aciklama').value = data.aciklama || '';
    document.getElementById('sira').value = data.sira || 0;
    document.getElementById('aktif').checked = data.aktif == 1;
    document.getElementById('mevcut_banner').value = data.banner_url || '';
    document.getElementById('banner_onizleme').src = data.banner_url || '';
    document.getElementById('banner_onizleme').style.display = data.banner_url ? 'block' : 'none';
    window.scrollTo(0,0);
}

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