<?php
// Start session first
session_start();

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get products directly with SQL
    $query = "SELECT p.*, c.name as category_name 
              FROM products p 
              LEFT JOIN categories c ON p.category_id = c.id 
              ORDER BY p.created_at DESC";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $all_products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get categories for dropdown
    $query_cat = "SELECT * FROM categories ORDER BY name";
    $stmt_cat = $db->prepare($query_cat);
    $stmt_cat->execute();
    $all_categories = $stmt_cat->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "خطأ في الاتصال بقاعدة البيانات: " . $e->getMessage();
    $all_products = [];
    $all_categories = [];
}

$message = '';

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_product'])) {
    try {
        $product_id = $_POST['product_id'];
        $query = "DELETE FROM products WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->execute([$product_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 -->
        <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-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                    <i class="fas fa-plus ml-2"></i>
                    إضافة منتج
                </a>
            </div>
        </header>

        <!-- Content -->
        <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; ?>

            <!-- Products Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                <?php if (!empty($all_products)): ?>
                    <?php foreach ($all_products as $product): ?>
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-lg transition-shadow">
                            <!-- Image -->
                            <?php if (!empty($product['image'])): ?>
                                <img src="../../<?php echo htmlspecialchars($product['image']); ?>" 
                                     alt="<?php echo htmlspecialchars($product['name']); ?>" 
                                     class="w-full h-48 object-cover">
                            <?php else: ?>
                                <div class="w-full h-48 bg-gradient-to-br from-green-100 to-green-200 flex items-center justify-center">
                                    <i class="fas fa-image text-green-400 text-5xl"></i>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Info -->
                            <div class="p-4">
                                <h3 class="text-lg font-semibold text-gray-900 mb-1">
                                    <?php echo htmlspecialchars($product['name']); ?>
                                </h3>
                                
                                <?php if (!empty($product['category_name'])): ?>
                                    <span class="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded mb-2">
                                        <?php echo htmlspecialchars($product['category_name']); ?>
                                    </span>
                                <?php endif; ?>
                                
                                <p class="text-gray-600 text-sm mb-3 line-clamp-2">
                                    <?php echo htmlspecialchars($product['description']); ?>
                                </p>
                                
                                <!-- Price & Stock -->
                                <div class="flex items-center justify-between mb-3 pb-3 border-b">
                                    <span class="text-green-600 font-bold text-xl">
                                        <?php echo number_format($product['price'], 0); ?> ج.م
                                    </span>
                                    <span class="text-sm text-gray-500">
                                        <i class="fas fa-box ml-1"></i>
                                        <?php echo $product['stock_quantity'] ?? 0; ?>
                                    </span>
                                </div>
                                
                                <!-- Actions -->
                                <div class="flex items-center gap-2">
                                    <a href="edit.php?id=<?php echo $product['id']; ?>" 
                                       class="flex-1 bg-blue-50 text-blue-600 px-3 py-2 rounded-md text-sm text-center hover:bg-blue-100 transition">
                                        <i class="fas fa-edit ml-1"></i>تعديل
                                    </a>
                                    <form method="POST" class="flex-1" onsubmit="return confirm('هل أنت متأكد من حذف هذا المنتج؟');">
                                        <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                                        <button type="submit" name="delete_product" 
                                                class="w-full bg-red-50 text-red-600 px-3 py-2 rounded-md text-sm hover:bg-red-100 transition">
                                            <i class="fas fa-trash ml-1"></i>حذف
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <!-- Empty State -->
                    <div class="col-span-4 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-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-box-open text-4xl text-gray-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-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 transition">
                                <i class="fas fa-plus ml-2"></i>
                                إضافة منتج جديد
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>
