<?php
session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $query = "SELECT * FROM categories ORDER BY name";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $all_categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "خطأ: " . $e->getMessage();
    $all_categories = [];
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete_category'])) {
        try {
            $category_id = $_POST['category_id'];
            $query = "DELETE FROM categories WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$category_id]);
            
            header("Location: index.php?deleted=1");
            exit;
        } catch (Exception $e) {
            $message = "خطأ في الحذف: " . $e->getMessage();
        }
    }
}

if (isset($_GET['deleted'])) {
    $message = 'تم حذف الفئة بنجاح!';
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة الفئات - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
            <div class="flex items-center justify-between px-6 py-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-900">إدارة الفئات</h1>
                </div>
                <a href="add.php" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                    <i class="fas fa-plus ml-2"></i>
                    إضافة فئة
                </a>
            </div>
        </header>

        <div class="p-6">
            <?php if (isset($error)): ?>
                <div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6">
                    <p class="text-sm text-red-700"><?php echo $error; ?></p>
                </div>
            <?php endif; ?>

            <?php if ($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <p class="text-sm text-green-700"><?php echo $message; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <?php
                $stats = [
                    'total' => count($all_categories),
                    'products' => count(array_filter($all_categories, fn($c) => $c['type'] === 'product')),
                    'services' => count(array_filter($all_categories, fn($c) => $c['type'] === 'service')),
                    'active' => count(array_filter($all_categories, fn($c) => $c['is_active']))
                ];
            ?>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي الفئات</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo $stats['total']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-tags text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">فئات المنتجات</p>
                            <p class="text-2xl font-bold text-blue-600"><?php echo $stats['products']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-box text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">فئات الخدمات</p>
                            <p class="text-2xl font-bold text-purple-600"><?php echo $stats['services']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-spa text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">الفئات النشطة</p>
                            <p class="text-2xl font-bold text-green-600"><?php echo $stats['active']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php if (!empty($all_categories)): ?>
                    <?php foreach ($all_categories as $category): ?>
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-lg transition-shadow">
                            <?php if (!empty($category['image'])): ?>
                                <img src="../../<?php echo htmlspecialchars($category['image']); ?>" 
                                     alt="<?php echo htmlspecialchars($category['name']); ?>" 
                                     class="w-full h-48 object-cover"
                                     onerror="this.parentElement.innerHTML='<div class=/'w-full h-48 bg-gradient-to-br from-purple-100 to-purple-200 flex items-center justify-center\'><i class=/'fas fa-tags text-purple-400 text-5xl\'></i></div>'">
                            <?php else: ?>
                                <div class="w-full h-48 bg-gradient-to-br from-purple-100 to-purple-200 flex items-center justify-center">
                                    <i class="fas fa-tags text-purple-400 text-5xl"></i>
                                </div>
                            <?php endif; ?>
                            
                            <div class="p-4">
                                <div class="flex items-center justify-between mb-2">
                                    <h3 class="text-xl font-semibold text-gray-900">
                                        <?php echo htmlspecialchars($category['name']); ?>
                                    </h3>
                                    <?php if ($category['is_active']): ?>
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                            <i class="fas fa-check-circle ml-1"></i>نشط
                                        </span>
                                    <?php else: ?>
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                            <i class="fas fa-times-circle ml-1"></i>معطل
                                        </span>
                                    <?php endif; ?>
                                </div>
                                
                                <p class="text-gray-600 text-sm mb-2">
                                    <?php echo htmlspecialchars($category['description'] ?? ''); ?>
                                </p>
                                
                                <div class="flex items-center gap-2 mb-4">
                                    <?php if ($category['type'] === 'product'): ?>
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                            <i class="fas fa-box ml-1"></i>منتجات
                                        </span>
                                    <?php else: ?>
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                                            <i class="fas fa-spa ml-1"></i>خدمات
                                        </span>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="flex items-center gap-2">
                                    <a href="add.php?id=<?php echo $category['id']; ?>" 
                                       class="flex-1 bg-blue-50 text-blue-600 px-3 py-2 rounded-md text-sm text-center hover:bg-blue-100">
                                        <i class="fas fa-edit ml-1"></i>تعديل
                                    </a>
                                    <form method="POST" class="flex-1" onsubmit="return confirm('هل أنت متأكد من حذف هذه الفئة؟');">
                                        <input type="hidden" name="category_id" value="<?php echo $category['id']; ?>">
                                        <button type="submit" name="delete_category" 
                                                class="w-full bg-red-50 text-red-600 px-3 py-2 rounded-md text-sm hover:bg-red-100">
                                            <i class="fas fa-trash ml-1"></i>حذف
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-span-3 bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
                        <div class="max-w-md mx-auto">
                            <div class="w-24 h-24 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-tags text-4xl text-purple-400"></i>
                            </div>
                            <h3 class="text-xl font-semibold text-gray-700 mb-2">لا توجد فئات</h3>
                            <p class="text-gray-500 mb-6">ابدأ بإضافة فئات لتنظيم منتجاتك</p>
                            <a href="add.php" class="inline-flex items-center bg-purple-600 text-white px-6 py-3 rounded-lg hover:bg-purple-700">
                                <i class="fas fa-plus ml-2"></i>
                                إضافة فئة جديدة
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>
