<?php
session_start();
require_once '../includes/config.php';
require_once 'functions.php';

requireLogin();

$action = $_GET['action'] ?? 'list';
$category_id = $_GET['id'] ?? 0;

// Kategori Ekleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'add') {
    if (verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $name = trim($_POST['name']);
        $slug = createSlug($name);
        $display_order = intval($_POST['display_order'] ?? 0);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // Görsel yükleme
        $image = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
            $upload = uploadImage($_FILES['image'], 'resimler');
            if ($upload['success']) {
                $image = $upload['filename'];
            } else {
                setErrorMessage($upload['message']);
            }
        }
        
        try {
            $stmt = $pdo->prepare("INSERT INTO categories (name, slug, image, display_order, is_active) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$name, $slug, $image, $display_order, $is_active]);
            
            setSuccessMessage('Kategori başarıyla eklendi!');
            header('Location: categories.php');
            exit;
        } catch (PDOException $e) {
            setErrorMessage('Kategori eklenirken hata oluştu: ' . $e->getMessage());
        }
    } else {
        setErrorMessage('Güvenlik hatası! Lütfen tekrar deneyin.');
    }
}

// Kategori Güncelleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'edit' && $category_id) {
    if (verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $name = trim($_POST['name']);
        $slug = createSlug($name);
        $display_order = intval($_POST['display_order'] ?? 0);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // Mevcut kategoriyi çek
        $stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
        $stmt->execute([$category_id]);
        $current = $stmt->fetch();
        
        $image = $current['image'];
        
        // Yeni görsel yükleme
        if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
            $upload = uploadImage($_FILES['image'], 'resimler');
            if ($upload['success']) {
                // Eski görseli sil
                if ($image && file_exists('../' . $image)) {
                    unlink('../' . $image);
                }
                $image = $upload['filename'];
            } else {
                setErrorMessage($upload['message']);
            }
        }
        
        try {
            $stmt = $pdo->prepare("UPDATE categories SET name=?, slug=?, image=?, display_order=?, is_active=? WHERE id=?");
            $stmt->execute([$name, $slug, $image, $display_order, $is_active, $category_id]);
            
            setSuccessMessage('Kategori başarıyla güncellendi!');
            header('Location: categories.php');
            exit;
        } catch (PDOException $e) {
            setErrorMessage('Kategori güncellenirken hata oluştu: ' . $e->getMessage());
        }
    } else {
        setErrorMessage('Güvenlik hatası! Lütfen tekrar deneyin.');
    }
}

// Kategori Silme
if ($action === 'delete' && $category_id) {
    try {
        // Önce kategori görselini al
        $stmt = $pdo->prepare("SELECT image FROM categories WHERE id = ?");
        $stmt->execute([$category_id]);
        $category = $stmt->fetch();
        
        // Kategoriyi sil
        $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
        $stmt->execute([$category_id]);
        
        // Görseli sil
        if ($category && $category['image'] && file_exists('../' . $category['image'])) {
            unlink('../' . $category['image']);
        }
        
        setSuccessMessage('Kategori başarıyla silindi!');
        header('Location: categories.php');
        exit;
    } catch (PDOException $e) {
        setErrorMessage('Kategori silinirken hata oluştu. Önce bu kategorideki ürünleri silin.');
    }
}

// Durum Değiştirme
if ($action === 'toggle' && $category_id) {
    try {
        $stmt = $pdo->prepare("UPDATE categories SET is_active = NOT is_active WHERE id = ?");
        $stmt->execute([$category_id]);
        
        setSuccessMessage('Kategori durumu güncellendi!');
        header('Location: categories.php');
        exit;
    } catch (PDOException $e) {
        setErrorMessage('Durum güncellenirken hata oluştu: ' . $e->getMessage());
    }
}

// Kategori Bilgisi Çek (Düzenleme için)
$category = null;
if ($action === 'edit' && $category_id) {
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
    $stmt->execute([$category_id]);
    $category = $stmt->fetch();
    
    if (!$category) {
        setErrorMessage('Kategori bulunamadı!');
        header('Location: categories.php');
        exit;
    }
}

// Kategori Listesi
$stmt = $pdo->query("
    SELECT c.*, 
           (SELECT COUNT(*) FROM products WHERE category_id = c.id) as product_count
    FROM categories c 
    ORDER BY c.display_order ASC, c.name ASC
");
$categories = $stmt->fetchAll();

$page_title = $action === 'add' ? 'Yeni Kategori Ekle' : ($action === 'edit' ? 'Kategori Düzenle' : 'Kategoriler');
include 'includes/header.php';
?>

<?php if ($action === 'list'): ?>
<!-- Kategori Listesi -->
<div class="space-y-6">
    <div class="flex justify-end">
        <a href="categories.php?action=add" class="bg-green-600 hover:bg-green-700 text-white px-6 py-2 rounded-lg transition inline-flex items-center">
            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            Yeni Kategori
        </a>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php foreach ($categories as $cat): ?>
            <div class="bg-white rounded-xl shadow-md overflow-hidden hover:shadow-lg transition">
                <?php if ($cat['image'] && file_exists('../' . $cat['image'])): ?>
                    <img src="../<?php echo h($cat['image']); ?>" alt="<?php echo h($cat['name']); ?>" class="w-full h-40 object-cover">
                <?php else: ?>
                    <div class="w-full h-40 bg-gradient-to-br from-amber-100 to-orange-100 flex items-center justify-center">
                        <svg class="w-16 h-16 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                        </svg>
                    </div>
                <?php endif; ?>
                
                <div class="p-4">
                    <div class="flex items-start justify-between mb-2">
                        <h3 class="text-lg font-bold text-gray-900"><?php echo h($cat['name']); ?></h3>
                        <a href="categories.php?action=toggle&id=<?php echo $cat['id']; ?>" class="text-sm">
                            <?php if ($cat['is_active']): ?>
                                <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Aktif</span>
                            <?php else: ?>
                                <span class="px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">Pasif</span>
                            <?php endif; ?>
                        </a>
                    </div>
                    
                    <div class="flex items-center justify-between text-sm text-gray-500 mb-4">
                        <span><?php echo $cat['product_count']; ?> ürün</span>
                        <span>Sıra: <?php echo $cat['display_order']; ?></span>
                    </div>
                    
                    <div class="flex gap-2">
                        <a href="categories.php?action=edit&id=<?php echo $cat['id']; ?>" 
                           class="flex-1 bg-amber-600 hover:bg-amber-700 text-white text-center py-2 rounded-lg transition text-sm">
                            Düzenle
                        </a>
                        <a href="categories.php?action=delete&id=<?php echo $cat['id']; ?>" 
                           onclick="return confirmDelete('Bu kategoriyi ve içindeki tüm ürünleri silmek istediğinizden emin misiniz?')"
                           class="flex-1 bg-red-600 hover:bg-red-700 text-white text-center py-2 rounded-lg transition text-sm">
                            Sil
                        </a>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<?php else: ?>
<!-- Kategori Ekleme/Düzenleme Formu -->
<div class="max-w-2xl mx-auto">
    <div class="bg-white rounded-xl shadow-md p-8">
        <form method="POST" action="categories.php?action=<?php echo $action; ?><?php echo $category_id ? '&id=' . $category_id : ''; ?>" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            
            <div class="space-y-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Kategori Adı *</label>
                    <input type="text" name="name" required 
                           value="<?php echo $category ? h($category['name']) : ''; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
                    <p class="mt-1 text-sm text-gray-500">Slug otomatik oluşturulacak</p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Kategori Görseli</label>
                    <?php if ($category && $category['image'] && file_exists('../' . $category['image'])): ?>
                        <img src="../<?php echo h($category['image']); ?>" alt="Mevcut görsel" class="w-full h-40 object-cover rounded-lg mb-2">
                    <?php endif; ?>
                    <input type="file" name="image" accept="image/*" 
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
                    <p class="mt-1 text-sm text-gray-500">JPG, PNG, GIF, WebP (Max: 5MB)</p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Sıra</label>
                    <input type="number" name="display_order" 
                           value="<?php echo $category ? $category['display_order'] : '0'; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
                    <p class="mt-1 text-sm text-gray-500">Menüde gösterilme sırası</p>
                </div>

                <div class="flex items-center">
                    <input type="checkbox" name="is_active" id="is_active" 
                           <?php echo (!$category || $category['is_active']) ? 'checked' : ''; ?>
                           class="h-4 w-4 text-amber-600 focus:ring-amber-500 border-gray-300 rounded">
                    <label for="is_active" class="ml-2 block text-sm text-gray-900">
                        Aktif
                    </label>
                </div>

                <div class="flex gap-4">
                    <button type="submit" 
                            class="flex-1 bg-amber-600 hover:bg-amber-700 text-white font-bold py-3 px-6 rounded-lg transition">
                        <?php echo $action === 'add' ? 'Ekle' : 'Güncelle'; ?>
                    </button>
                    <a href="categories.php" 
                       class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-3 px-6 rounded-lg transition text-center">
                        İptal
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

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