<?php
session_start();

// Check admin access
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();
    
    // Get products
    $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
    $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);
    
    // Get statistics
    $total_products = count($all_products);
    $active_products = count(array_filter($all_products, fn($p) => $p['status'] === 'active'));
    $low_stock = count(array_filter($all_products, fn($p) => isset($p['stock']) && $p['stock'] < 10));
    $total_value = array_sum(array_map(fn($p) => $p['price'] * ($p['stock'] ?? 0), $all_products));
    
} catch (Exception $e) {
    $error = "خطأ في الاتصال بقاعدة البيانات: " . $e->getMessage();
    $all_products = [];
    $all_categories = [];
}

// 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-new.php?deleted=1");
        exit;
    } catch (Exception $e) {
        $error = "خطأ في حذف المنتج: " . $e->getMessage();
    }
}

$page_title = 'إدارة المنتجات';
$breadcrumb = [
    ['title' => 'الرئيسية', 'url' => '../dashboard.php'],
    ['title' => 'المنتجات']
];

include '../includes/header.php';
?>

<!-- Statistics Cards -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6 animate-fade-in">
    <div class="card">
        <div class="card-body">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-600 mb-1">إجمالي المنتجات</p>
                    <p class="text-3xl font-bold text-gray-900"><?php echo $total_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>
    
    <div class="card">
        <div class="card-body">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-600 mb-1">منتجات نشطة</p>
                    <p class="text-3xl font-bold text-green-600"><?php echo $active_products; ?></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="card">
        <div class="card-body">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-600 mb-1">تنبيهات المخزون</p>
                    <p class="text-3xl font-bold text-orange-600"><?php echo $low_stock; ?></p>
                </div>
                <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-exclamation-triangle text-orange-600 text-xl"></i>
                </div>
            </div>
        </div>
    </div>
    
    <div class="card">
        <div class="card-body">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-600 mb-1">قيمة المخزون</p>
                    <p class="text-2xl font-bold text-purple-600">EGP <?php echo number_format($total_value, 0); ?></p>
                </div>
                <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-dollar-sign text-purple-600 text-xl"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Products Table -->
<div class="card animate-fade-in">
    <div class="card-header">
        <h2 class="card-title">قائمة المنتجات</h2>
        <div class="flex items-center gap-3">
            <button onclick="window.location.href='add.php'" 
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2">
                <i class="fas fa-plus"></i>
                <span>إضافة منتج جديد</span>
            </button>
            <button class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                <i class="fas fa-filter"></i>
            </button>
            <button class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                <i class="fas fa-download"></i>
            </button>
        </div>
    </div>
    
    <div class="card-body p-0">
        <?php if (isset($_GET['deleted'])): ?>
            <div class="mx-6 mt-6 p-4 bg-green-50 border border-green-200 rounded-lg text-green-800">
                <i class="fas fa-check-circle ml-2"></i>
                تم حذف المنتج بنجاح
            </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="mx-6 mt-6 p-4 bg-red-50 border border-red-200 rounded-lg text-red-800">
                <i class="fas fa-exclamation-circle ml-2"></i>
                <?php echo $error; ?>
            </div>
        <?php endif; ?>
        
        <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-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" class="rounded">
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            المنتج
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            الفئة
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            السعر
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            المخزون
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            الحالة
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            الإجراءات
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($all_products)): ?>
                        <tr>
                            <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-box-open text-4xl mb-3 text-gray-300"></i>
                                <p>لا توجد منتجات حالياً</p>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($all_products as $product): ?>
                            <tr class="hover:bg-gray-50 transition-colors">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="checkbox" class="rounded">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center">
                                        <div class="flex-shrink-0 h-12 w-12">
                                            <?php if (!empty($product['image'])): ?>
                                                <img class="h-12 w-12 rounded-lg object-cover" 
                                                     src="../../uploads/products/<?php echo htmlspecialchars($product['image']); ?>" 
                                                     alt="<?php echo htmlspecialchars($product['name']); ?>">
                                            <?php else: ?>
                                                <div class="h-12 w-12 rounded-lg bg-gray-200 flex items-center justify-center">
                                                    <i class="fas fa-image text-gray-400"></i>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="mr-4">
                                            <div class="text-sm font-medium text-gray-900">
                                                <?php echo htmlspecialchars($product['name']); ?>
                                            </div>
                                            <div class="text-sm text-gray-500">
                                                #<?php echo $product['id']; ?>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                        <?php echo htmlspecialchars($product['category_name'] ?? 'غير محدد'); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-semibold">
                                    EGP <?php echo number_format($product['price'], 2); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php 
                                    $stock = $product['stock'] ?? 0;
                                    $stock_class = $stock < 10 ? 'text-red-600 bg-red-100' : 'text-green-600 bg-green-100';
                                    ?>
                                    <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $stock_class; ?>">
                                        <?php echo $stock; ?> قطعة
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php 
                                    $status_class = $product['status'] === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800';
                                    $status_text = $product['status'] === 'active' ? 'نشط' : 'غير نشط';
                                    ?>
                                    <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $status_class; ?>">
                                        <?php echo $status_text; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <div class="flex items-center gap-2">
                                        <a href="edit.php?id=<?php echo $product['id']; ?>" 
                                           class="text-blue-600 hover:text-blue-900 p-2 hover:bg-blue-50 rounded transition-colors"
                                           title="تعديل">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="../../public/product.php?id=<?php echo $product['id']; ?>" 
                                           class="text-green-600 hover:text-green-900 p-2 hover:bg-green-50 rounded transition-colors"
                                           title="عرض"
                                           target="_blank">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <form method="POST" class="inline" onsubmit="return confirm('هل أنت متأكد من حذف هذا المنتج؟');">
                                            <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                                            <button type="submit" name="delete_product" 
                                                    class="text-red-600 hover:text-red-900 p-2 hover:bg-red-50 rounded transition-colors"
                                                    title="حذف">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
body.dark-mode .bg-gray-50 { background-color: #1e293b !important; }
body.dark-mode .text-gray-900 { color: #e2e8f0 !important; }
body.dark-mode .text-gray-600 { color: #94a3b8 !important; }
body.dark-mode .text-gray-500 { color: #64748b !important; }
body.dark-mode .divide-gray-200 { border-color: #334155 !important; }
body.dark-mode .hover\:bg-gray-50:hover { background-color: #1e293b !important; }
</style>

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