<?php
/**
 * Admin - Slider Düzenle (Otomatik Görsel Optimizasyonlu)
 * Konum: /magaza/admin/slider/duzenle.php
 */
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
adminCheck();

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: index.php");
    exit;
}

$id = (int)$_GET['id'];
$mesaj = '';

// Mevcut Slider Verisini Çek
$stmt = $db->prepare("SELECT * FROM sliders WHERE id = ?");
$stmt->execute([$id]);
$slider = $stmt->fetch();

if (!$slider) {
    die("Düzenlenecek afiş bulunamadı.");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $subtitle = trim($_POST['subtitle']);
    $button_text = trim($_POST['button_text']);
    $button_link = trim($_POST['button_link']);
    $sort_order = (int)$_POST['sort_order'];
    $status = isset($_POST['status']) ? 1 : 0;
    
    $db_path = $slider['image_path']; // Varsayılan: Mevcut resim yolu

    // --- YENİ RESİM YÜKLENDİYSE OPTİMİZASYON BAŞLAR ---
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $dosya = $_FILES['image'];
        $uzanti = strtolower(pathinfo($dosya['name'], PATHINFO_EXTENSION));
        $izin_verilenler = ['jpg', 'jpeg', 'png', 'webp', 'gif'];

        if (!in_array($uzanti, $izin_verilenler)) {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: Sadece JPG, PNG, WEBP veya GIF yükleyebilirsiniz.</div>";
        } elseif ($dosya['size'] > 5 * 1024 * 1024) {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: Dosya boyutu 5MB'dan büyük olamaz.</div>";
        } else {
            $klasor = "../../uploads/sliders/";
            if (!is_dir($klasor)) mkdir($klasor, 0777, true);
            
            // Boyutları al ve oranla
            list($width, $height) = getimagesize($dosya['tmp_name']);
            $max_width = 1920;

            if ($width > $max_width) {
                $oran = $width / $height;
                $new_width = $max_width;
                $new_height = $max_width / $oran;
            } else {
                $new_width = $width;
                $new_height = $height;
            }

            $yeni_resim = imagecreatetruecolor($new_width, $new_height);
            imagealphablending($yeni_resim, false);
            imagesavealpha($yeni_resim, true);
            
            $kaynak = null;
            switch ($uzanti) {
                case 'jpg': case 'jpeg': $kaynak = imagecreatefromjpeg($dosya['tmp_name']); break;
                case 'png': $kaynak = imagecreatefrompng($dosya['tmp_name']); break;
                case 'webp': $kaynak = imagecreatefromwebp($dosya['tmp_name']); break;
                case 'gif': $kaynak = imagecreatefromgif($dosya['tmp_name']); break;
            }

            if ($kaynak) {
                imagecopyresampled($yeni_resim, $kaynak, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                $yeni_ad = "slider_" . uniqid() . ".webp";
                $hedef = $klasor . $yeni_ad;

                if (imagewebp($yeni_resim, $hedef, 80)) {
                    // YENİ RESİM BAŞARIYLA OLUŞTU: ESKİ RESMİ SİL
                    if (file_exists("../../" . $slider['image_path'])) {
                        unlink("../../" . $slider['image_path']);
                    }
                    $db_path = "uploads/sliders/" . $yeni_ad;
                }
                imagedestroy($yeni_resim);
                imagedestroy($kaynak);
            }
        }
    }

    // Veritabanı Güncelleme
    if (empty($mesaj)) {
        try {
            $upd = $db->prepare("UPDATE sliders SET title = ?, subtitle = ?, image_path = ?, button_text = ?, button_link = ?, sort_order = ?, status = ? WHERE id = ?");
            $upd->execute([$title, $subtitle, $db_path, $button_text, $button_link, $sort_order, $status, $id]);
            
            $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Değişiklikler ve görsel optimizasyonu başarıyla tamamlandı.</div>";
            
            // Veriyi tazele
            $stmt->execute([$id]);
            $slider = $stmt->fetch();
        } catch (Exception $e) {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: " . $e->getMessage() . "</div>";
        }
    }
}

require_once '../header.php';
?>

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0">
            <a href="index.php" class="btn btn-sm btn-outline-secondary me-2 border-2"><i class="bi bi-arrow-left"></i> Geri</a>
            Slider Düzenle
        </h2>
    </div>
</div>

<?= $mesaj ?>

<form action="" method="POST" enctype="multipart/form-data">
    <div class="row text-dark">
        <div class="col-lg-8">
            <div class="card shadow-sm border-0 rounded-4 mb-4">
                <div class="card-body p-4 p-md-5">
                    
                    <div class="mb-4 text-center bg-light p-3 rounded-4 border">
                        <small class="text-muted d-block fw-bold mb-2">Mevcut Vitrin Görseli (WEBP)</small>
                        <img src="../../<?= htmlspecialchars($slider['image_path']) ?>" class="img-fluid rounded shadow-sm" style="max-height: 200px; object-fit: cover;">
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold">Görseli Güncelle (Opsiyonel)</label>
                        <input type="file" name="image" class="form-control form-control-lg border-2" accept="image/*">
                        <div class="form-text mt-2 text-primary fw-bold">
                            <i class="bi bi-magic me-1"></i> Yeni bir resim seçerseniz otomatik olarak optimize edilecek ve eskisi silinecektir.
                        </div>
                    </div>

                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-muted">Ana Başlık</label>
                            <input type="text" name="title" class="form-control border-2" value="<?= htmlspecialchars($slider['title']) ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-muted">Alt Başlık</label>
                            <input type="text" name="subtitle" class="form-control border-2" value="<?= htmlspecialchars($slider['subtitle']) ?>">
                        </div>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-muted">Buton Yazısı</label>
                            <input type="text" name="button_text" class="form-control border-2" value="<?= htmlspecialchars($slider['button_text']) ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-muted">Buton Linki</label>
                            <input type="text" name="button_link" class="form-control border-2" value="<?= htmlspecialchars($slider['button_link']) ?>">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card shadow-sm border-0 rounded-4 mb-4 h-100">
                <div class="card-header bg-white py-3 border-bottom"><h6 class="mb-0 fw-bold">Yayın Ayarları</h6></div>
                <div class="card-body p-4">
                    <div class="mb-4">
                        <label class="form-label fw-bold small text-muted">Sıralama</label>
                        <input type="number" name="sort_order" class="form-control border-2" value="<?= $slider['sort_order'] ?>">
                    </div>
                    
                    <div class="form-check form-switch mb-4 fs-5">
                        <input class="form-check-input cursor-pointer" type="checkbox" name="status" id="statusSwitch" <?= $slider['status'] == 1 ? 'checked' : '' ?>>
                        <label class="form-check-label fs-6 ms-2 fw-bold" for="statusSwitch">Sitede Göster</label>
                    </div>

                    <button type="submit" class="btn btn-success btn-lg w-100 fw-bold shadow-sm rounded-pill">
                        <i class="bi bi-arrow-repeat me-1"></i> Değişiklikleri Uygula
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>

<?php require_once '../footer.php'; ?>