<?php
// نسخة مؤقتة بدون فحص صلاحيات للاختبار
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once '../../config/database.php';

// تعطيل فحص الصلاحيات مؤقتاً للاختبار
// if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
//     header('Location: ../login.php');
//     exit;
// }

$database = new Database();
$conn = $database->getConnection();

$message = '';
$error = '';

// الحصول على إحصائيات المخزون
$stats = [
    'total_products' => 0,
    'low_stock' => 0,
    'out_of_stock' => 0,
    'total_value' => 0
];

try {
    $stmt = $conn->query("SELECT COUNT(*) FROM products WHERE track_inventory = 1");
    $stats['total_products'] = $stmt->fetchColumn();

    $stmt = $conn->query("SELECT COUNT(*) FROM products WHERE stock_quantity <= low_stock_alert AND stock_quantity > 0 AND track_inventory = 1");
    $stats['low_stock'] = $stmt->fetchColumn();

    $stmt = $conn->query("SELECT COUNT(*) FROM products WHERE stock_quantity <= 0 AND track_inventory = 1");
    $stats['out_of_stock'] = $stmt->fetchColumn();

    $stmt = $conn->query("SELECT SUM(stock_quantity * price) FROM products WHERE track_inventory = 1");
    $stats['total_value'] = $stmt->fetchColumn() ?? 0;
} catch (Exception $e) {
    $error = "خطأ في الاتصال بقاعدة البيانات: " . $e->getMessage();
}

// الحصول على المنتجات
$products = [];
try {
    $sql = "SELECT p.*, c.name as category_name FROM products p 
            LEFT JOIN categories c ON p.category_id = c.id 
            WHERE p.track_inventory = 1
            ORDER BY p.stock_quantity ASC
            LIMIT 20";
    
    $stmt = $conn->query($sql);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $error .= "<br>خطأ في جلب المنتجات: " . $e->getMessage();
}
?>
<!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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <div class="bg-gradient-to-r from-purple-600 to-purple-800 text-white p-6 shadow-lg">
            <div class="max-w-7xl mx-auto">
                <h1 class="text-3xl font-bold mb-2">📦 اختبار نظام المخزون</h1>
                <p class="text-purple-100">نسخة تجريبية بدون فحص صلاحيات</p>
            </div>
        </div>

        <div class="max-w-7xl mx-auto p-6">
            <?php if ($error): ?>
                <div class="bg-red-100 border-r-4 border-red-500 text-red-700 p-4 rounded mb-6">
                    <i class="fas fa-exclamation-circle ml-2"></i> <?php echo $error; ?>
                </div>
            <?php endif; ?>

            <!-- إحصائيات -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">إجمالي المنتجات</p>
                            <p class="text-3xl font-bold text-gray-800"><?php echo $stats['total_products']; ?></p>
                        </div>
                        <div class="bg-blue-100 p-4 rounded-full">
                            <i class="fas fa-boxes text-blue-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">مخزون منخفض</p>
                            <p class="text-3xl font-bold text-yellow-600"><?php echo $stats['low_stock']; ?></p>
                        </div>
                        <div class="bg-yellow-100 p-4 rounded-full">
                            <i class="fas fa-exclamation-triangle text-yellow-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">نفذ من المخزون</p>
                            <p class="text-3xl font-bold text-red-600"><?php echo $stats['out_of_stock']; ?></p>
                        </div>
                        <div class="bg-red-100 p-4 rounded-full">
                            <i class="fas fa-times-circle text-red-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">قيمة المخزون</p>
                            <p class="text-3xl font-bold text-green-600"><?php echo number_format($stats['total_value'], 2); ?> ج.م</p>
                        </div>
                        <div class="bg-green-100 p-4 rounded-full">
                            <i class="fas fa-dollar-sign text-green-600 text-2xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- جدول المنتجات -->
            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                <div class="p-4 bg-gray-50 border-b">
                    <h2 class="text-xl font-bold">المنتجات (أول 20)</h2>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">المنتج</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الفئة</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الكمية</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">السعر</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الحالة</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php if (count($products) > 0): ?>
                                <?php foreach ($products as $product): 
                                    $stock_status = 'normal';
                                    $status_class = 'bg-green-100 text-green-800';
                                    $status_text = 'متوفر';
                                    
                                    if ($product['stock_quantity'] <= 0) {
                                        $stock_status = 'out';
                                        $status_class = 'bg-red-100 text-red-800';
                                        $status_text = 'نفذ';
                                    } elseif ($product['stock_quantity'] <= $product['low_stock_alert']) {
                                        $stock_status = 'low';
                                        $status_class = 'bg-yellow-100 text-yellow-800';
                                        $status_text = 'منخفض';
                                    }
                                ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 font-medium"><?php echo htmlspecialchars($product['name']); ?></td>
                                    <td class="px-6 py-4 text-sm"><?php echo htmlspecialchars($product['category_name'] ?? '-'); ?></td>
                                    <td class="px-6 py-4">
                                        <span class="text-lg font-bold"><?php echo $product['stock_quantity']; ?></span>
                                    </td>
                                    <td class="px-6 py-4 text-sm"><?php echo number_format($product['price'], 2); ?> ج.م</td>
                                    <td class="px-6 py-4">
                                        <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $status_class; ?>">
                                            <?php echo $status_text; ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="px-6 py-8 text-center text-gray-500">
                                        لا توجد منتجات مع تتبع المخزون
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="mt-6 bg-blue-100 border-r-4 border-blue-500 text-blue-700 p-4 rounded">
                <p class="font-bold">ملاحظة:</p>
                <p>هذه نسخة تجريبية بدون فحص صلاحيات. إذا ظهرت البيانات هنا، فالمشكلة في Session أو تسجيل الدخول.</p>
                <p class="mt-2">
                    <a href="../login.php" class="text-blue-800 underline">سجل دخول كـ Admin</a> ثم جرب 
                    <a href="index.php" class="text-blue-800 underline">الصفحة الأصلية</a>
                </p>
            </div>
        </div>
    </div>
</body>
</html>
