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

requireLogin();

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

// Kategorileri çek
$categories = $pdo->query("SELECT * FROM categories ORDER BY name ASC")->fetchAll();

// Ürün Ekleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'add') {
    if (verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $category_id = $_POST['category_id'];
        $name = trim($_POST['name']);
        $description = trim($_POST['description'] ?? '');
        $price = floatval($_POST['price']);
        $display_order = intval($_POST['display_order'] ?? 0);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        try {
            $stmt = $pdo->prepare("INSERT INTO products (category_id, name, description, price, display_order, is_active) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$category_id, $name, $description, $price, $display_order, $is_active]);
            
            setSuccessMessage('Ürün başarıyla eklendi!');
            header('Location: products.php');
            exit;
        } catch (PDOException $e) {
            setErrorMessage('Ürün eklenirken hata oluştu: ' . $e->getMessage());
        }
    } else {
        setErrorMessage('Güvenlik hatası! Lütfen tekrar deneyin.');
    }
}

// Ürün Güncelleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'edit' && $product_id) {
    if (verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $category_id = $_POST['category_id'];
        $name = trim($_POST['name']);
        $description = trim($_POST['description'] ?? '');
        $price = floatval($_POST['price']);
        $display_order = intval($_POST['display_order'] ?? 0);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        try {
            $stmt = $pdo->prepare("UPDATE products SET category_id=?, name=?, description=?, price=?, display_order=?, is_active=? WHERE id=?");
            $stmt->execute([$category_id, $name, $description, $price, $display_order, $is_active, $product_id]);
            
            setSuccessMessage('Ürün başarıyla güncellendi!');
            header('Location: products.php');
            exit;
        } catch (PDOException $e) {
            setErrorMessage('Ürün güncellenirken hata oluştu: ' . $e->getMessage());
        }
    } else {
        setErrorMessage('Güvenlik hatası! Lütfen tekrar deneyin.');
    }
}

// Ürün Silme
if ($action === 'delete' && $product_id) {
    try {
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        
        setSuccessMessage('Ürün başarıyla silindi!');
        header('Location: products.php');
        exit;
    } catch (PDOException $e) {
        setErrorMessage('Ürün silinirken hata oluştu: ' . $e->getMessage());
    }
}

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

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

// Ürün Listesi
$search = $_GET['search'] ?? '';
$category_filter = $_GET['category'] ?? '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;

$where = [];
$params = [];

if (!empty($search)) {
    $where[] = "(p.name LIKE ? OR p.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($category_filter)) {
    $where[] = "p.category_id = ?";
    $params[] = $category_filter;
}

$where_clause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$count_stmt = $pdo->prepare("SELECT COUNT(*) FROM products p $where_clause");
$count_stmt->execute($params);
$total_items = $count_stmt->fetchColumn();

$pagination = paginate($total_items, $per_page, $page);

$stmt = $pdo->prepare("
    SELECT p.*, c.name as category_name 
    FROM products p 
    JOIN categories c ON p.category_id = c.id 
    $where_clause
    ORDER BY p.display_order ASC, p.name ASC
    LIMIT {$pagination['items_per_page']} OFFSET {$pagination['offset']}
");
$stmt->execute($params);
$products = $stmt->fetchAll();

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

<?php if ($action === 'list'): ?>
<!-- Ürün Listesi -->
<div class="space-y-6">
    <!-- Filtreler ve Arama -->
    <div class="bg-white rounded-xl shadow-md p-6">
        <div class="flex flex-col md:flex-row gap-4 items-end">
            <div class="flex-1">
                <form method="GET" class="flex gap-2">
                    <input type="text" name="search" value="<?php echo h($search); ?>" 
                           placeholder="Ürün ara..." 
                           class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
                    <select name="category" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
                        <option value="">Tüm Kategoriler</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo $category_filter == $cat['id'] ? 'selected' : ''; ?>>
                                <?php echo h($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" class="bg-amber-600 hover:bg-amber-700 text-white px-6 py-2 rounded-lg transition">
                        Ara
                    </button>
                </form>
            </div>
            <a href="products.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 Ürün
            </a>
        </div>
    </div>

    <!-- Ürün Tablosu -->
    <div class="bg-white rounded-xl shadow-md overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Ürün</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kategori</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Fiyat</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Sıra</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Durum</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">İşlemler</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($products)): ?>
                        <tr>
                            <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                                Ürün bulunamadı.
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($products as $prod): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4">
                                    <div class="text-sm font-medium text-gray-900"><?php echo h($prod['name']); ?></div>
                                    <?php if ($prod['description']): ?>
                                        <div class="text-sm text-gray-500"><?php echo h(substr($prod['description'], 0, 50)) . (strlen($prod['description']) > 50 ? '...' : ''); ?></div>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                        <?php echo h($prod['category_name']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo formatPrice($prod['price']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    <?php echo $prod['display_order']; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <a href="products.php?action=toggle&id=<?php echo $prod['id']; ?>" 
                                       class="inline-flex items-center">
                                        <?php if ($prod['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>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
                                    <a href="products.php?action=edit&id=<?php echo $prod['id']; ?>" 
                                       class="text-amber-600 hover:text-amber-900">Düzenle</a>
                                    <a href="products.php?action=delete&id=<?php echo $prod['id']; ?>" 
                                       onclick="return confirmDelete('Bu ürünü silmek istediğinizden emin misiniz?')"
                                       class="text-red-600 hover:text-red-900">Sil</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($pagination['total_pages'] > 1): ?>
            <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
                <div class="flex-1 flex justify-between sm:hidden">
                    <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>" 
                           class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                            Önceki
                        </a>
                    <?php endif; ?>
                    <?php if ($page < $pagination['total_pages']): ?>
                        <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>" 
                           class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                            Sonraki
                        </a>
                    <?php endif; ?>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-gray-700">
                            Toplam <span class="font-medium"><?php echo $total_items; ?></span> ürün
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                            <?php for ($i = 1; $i <= $pagination['total_pages']; $i++): ?>
                                <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>" 
                                   class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium <?php echo $i == $page ? 'bg-amber-50 text-amber-600' : 'bg-white text-gray-700 hover:bg-gray-50'; ?>">
                                    <?php echo $i; ?>
                                </a>
                            <?php endfor; ?>
                        </nav>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php else: ?>
<!-- Ürün 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="products.php?action=<?php echo $action; ?><?php echo $product_id ? '&id=' . $product_id : ''; ?>">
            <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 *</label>
                    <select name="category_id" required 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
                        <option value="">Kategori Seçin</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" 
                                    <?php echo ($product && $product['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                                <?php echo h($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Ürün Adı *</label>
                    <input type="text" name="name" required 
                           value="<?php echo $product ? h($product['name']) : ''; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Açıklama</label>
                    <textarea name="description" rows="3"
                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent"><?php echo $product ? h($product['description']) : ''; ?></textarea>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Fiyat (₺) *</label>
                        <input type="number" name="price" step="0.01" required 
                               value="<?php echo $product ? $product['price'] : '0'; ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
                    </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 $product ? $product['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">
                    </div>
                </div>

                <div class="flex items-center">
                    <input type="checkbox" name="is_active" id="is_active" 
                           <?php echo (!$product || $product['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="products.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'; ?>
