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

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

// تحديث وقت آخر نشاط
$_SESSION['last_activity'] = time();

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

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

// معالجة تحديث المخزون
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_stock'])) {
    $product_id = $_POST['product_id'];
    $movement_type = $_POST['movement_type'];
    $quantity = intval($_POST['quantity']);
    $notes = $_POST['notes'] ?? '';
    
    try {
        $conn->beginTransaction();
        
        // الحصول على الكمية الحالية
        $stmt = $conn->prepare("SELECT stock_quantity FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $current_stock = $stmt->fetchColumn();
        
        // حساب الكمية الجديدة
        $new_quantity = $current_stock;
        if ($movement_type === 'in' || $movement_type === 'return') {
            $new_quantity += $quantity;
        } elseif ($movement_type === 'out' || $movement_type === 'adjustment') {
            $new_quantity -= $quantity;
        }
        
        // تحديث المخزون
        $stmt = $conn->prepare("UPDATE products SET stock_quantity = ? WHERE id = ?");
        $stmt->execute([$new_quantity, $product_id]);
        
        // تسجيل الحركة
        $stmt = $conn->prepare("INSERT INTO inventory_movements (product_id, movement_type, quantity, previous_quantity, new_quantity, notes, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$product_id, $movement_type, $quantity, $current_stock, $new_quantity, $notes, $_SESSION['user_id']]);
        
        // التحقق من التنبيهات
        $stmt = $conn->prepare("SELECT low_stock_alert FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $low_stock_alert = $stmt->fetchColumn();
        
        if ($new_quantity <= 0) {
            $stmt = $conn->prepare("INSERT INTO inventory_alerts (product_id, alert_type, current_quantity, threshold_quantity) VALUES (?, 'out_of_stock', ?, ?)");
            $stmt->execute([$product_id, $new_quantity, $low_stock_alert]);
        } elseif ($new_quantity <= $low_stock_alert) {
            $stmt = $conn->prepare("INSERT INTO inventory_alerts (product_id, alert_type, current_quantity, threshold_quantity) VALUES (?, 'low_stock', ?, ?)");
            $stmt->execute([$product_id, $new_quantity, $low_stock_alert]);
        }
        
        $conn->commit();
        $message = 'تم تحديث المخزون بنجاح';
    } catch (Exception $e) {
        $conn->rollBack();
        $error = 'حدث خطأ: ' . $e->getMessage();
    }
}

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

$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;

// الحصول على المنتجات
$search = $_GET['search'] ?? '';
$filter = $_GET['filter'] ?? 'all';

$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";

if ($search) {
    $sql .= " AND (p.name LIKE :search OR p.sku LIKE :search)";
}

if ($filter === 'low_stock') {
    $sql .= " AND p.stock_quantity <= p.low_stock_alert AND p.stock_quantity > 0";
} elseif ($filter === 'out_of_stock') {
    $sql .= " AND p.stock_quantity <= 0";
}

$sql .= " ORDER BY p.stock_quantity ASC";

$stmt = $conn->prepare($sql);
if ($search) {
    $stmt->bindValue(':search', "%$search%");
}
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// الحصول على آخر الحركات
$stmt = $conn->query("SELECT im.*, p.name as product_name, u.name as user_name 
                      FROM inventory_movements im 
                      LEFT JOIN products p ON im.product_id = p.id 
                      LEFT JOIN users u ON im.created_by = u.id 
                      ORDER BY im.created_at DESC LIMIT 10");
$recent_movements = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!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">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <!-- Header -->
        <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">
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="text-3xl font-bold mb-2">📦 إدارة المخزون</h1>
                        <p class="text-purple-100">تتبع وإدارة مخزون المنتجات</p>
                    </div>
                    <a href="../dashboard.php" class="bg-white text-purple-600 px-6 py-2 rounded-lg hover:bg-purple-50 transition">
                        <i class="fas fa-arrow-right ml-2"></i> العودة
                    </a>
                </div>
            </div>
        </div>

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

            <?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 p-6 mb-6">
                <form method="GET" class="flex gap-4">
                    <div class="flex-1">
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                               placeholder="بحث بالاسم أو SKU..." 
                               class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                    <select name="filter" class="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="all" <?php echo $filter === 'all' ? 'selected' : ''; ?>>جميع المنتجات</option>
                        <option value="low_stock" <?php echo $filter === 'low_stock' ? 'selected' : ''; ?>>مخزون منخفض</option>
                        <option value="out_of_stock" <?php echo $filter === 'out_of_stock' ? 'selected' : ''; ?>>نفذ من المخزون</option>
                    </select>
                    <button type="submit" class="bg-purple-600 text-white px-6 py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-search ml-2"></i> بحث
                    </button>
                </form>
            </div>

            <!-- جدول المنتجات -->
            <div class="bg-white rounded-lg shadow-md overflow-hidden mb-6">
                <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">SKU</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>
                                <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 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 = 'منخفض';
                                }
                                
                                $total_value = $product['stock_quantity'] * $product['price'];
                            ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4">
                                    <div class="flex items-center">
                                        <?php if ($product['image']): ?>
                                            <img src="../../<?php echo htmlspecialchars($product['image']); ?>" 
                                                 class="w-10 h-10 rounded object-cover ml-3">
                                        <?php endif; ?>
                                        <span class="font-medium"><?php echo htmlspecialchars($product['name']); ?></span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <?php echo htmlspecialchars($product['sku'] ?? '-'); ?>
                                </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 text-gray-500">
                                    <?php echo $product['low_stock_alert']; ?>
                                </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>
                                <td class="px-6 py-4 text-sm">
                                    <?php echo number_format($product['price'], 2); ?> ج.م
                                </td>
                                <td class="px-6 py-4 text-sm font-medium">
                                    <?php echo number_format($total_value, 2); ?> ج.م
                                </td>
                                <td class="px-6 py-4">
                                    <button onclick="openStockModal(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars($product['name']); ?>', <?php echo $product['stock_quantity']; ?>)" 
                                            class="bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700 text-sm">
                                        <i class="fas fa-edit ml-1"></i> تحديث
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- آخر الحركات -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-bold mb-4">
                    <i class="fas fa-history ml-2 text-purple-600"></i> آخر حركات المخزون
                </h2>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500">المنتج</th>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500">النوع</th>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500">الكمية</th>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500">قبل</th>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500">بعد</th>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500">الملاحظات</th>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500">بواسطة</th>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500">التاريخ</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($recent_movements as $movement): 
                                $type_colors = [
                                    'in' => 'bg-green-100 text-green-800',
                                    'out' => 'bg-red-100 text-red-800',
                                    'adjustment' => 'bg-blue-100 text-blue-800',
                                    'return' => 'bg-purple-100 text-purple-800'
                                ];
                                $type_names = [
                                    'in' => 'إضافة',
                                    'out' => 'صرف',
                                    'adjustment' => 'تعديل',
                                    'return' => 'إرجاع'
                                ];
                            ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-4 py-3 text-sm"><?php echo htmlspecialchars($movement['product_name']); ?></td>
                                <td class="px-4 py-3">
                                    <span class="px-2 py-1 rounded text-xs <?php echo $type_colors[$movement['movement_type']]; ?>">
                                        <?php echo $type_names[$movement['movement_type']]; ?>
                                    </span>
                                </td>
                                <td class="px-4 py-3 font-bold"><?php echo $movement['quantity']; ?></td>
                                <td class="px-4 py-3 text-sm text-gray-500"><?php echo $movement['previous_quantity']; ?></td>
                                <td class="px-4 py-3 text-sm text-gray-500"><?php echo $movement['new_quantity']; ?></td>
                                <td class="px-4 py-3 text-sm text-gray-500"><?php echo htmlspecialchars($movement['notes'] ?? '-'); ?></td>
                                <td class="px-4 py-3 text-sm"><?php echo htmlspecialchars($movement['user_name'] ?? '-'); ?></td>
                                <td class="px-4 py-3 text-sm text-gray-500"><?php echo date('Y-m-d H:i', strtotime($movement['created_at'])); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal تحديث المخزون -->
    <div id="stockModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg p-8 max-w-md w-full mx-4">
            <h3 class="text-2xl font-bold mb-4">تحديث المخزون</h3>
            <form method="POST">
                <input type="hidden" name="product_id" id="modal_product_id">
                
                <div class="mb-4">
                    <label class="block text-gray-700 font-medium mb-2">المنتج</label>
                    <p id="modal_product_name" class="text-lg font-bold text-purple-600"></p>
                    <p class="text-sm text-gray-500">الكمية الحالية: <span id="modal_current_stock" class="font-bold"></span></p>
                </div>

                <div class="mb-4">
                    <label class="block text-gray-700 font-medium mb-2">نوع الحركة</label>
                    <select name="movement_type" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="in">إضافة للمخزون</option>
                        <option value="out">صرف من المخزون</option>
                        <option value="adjustment">تعديل المخزون</option>
                        <option value="return">إرجاع للمخزون</option>
                    </select>
                </div>

                <div class="mb-4">
                    <label class="block text-gray-700 font-medium mb-2">الكمية</label>
                    <input type="number" name="quantity" required min="1" 
                           class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>

                <div class="mb-6">
                    <label class="block text-gray-700 font-medium mb-2">ملاحظات</label>
                    <textarea name="notes" rows="3" 
                              class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500"></textarea>
                </div>

                <div class="flex gap-4">
                    <button type="submit" name="update_stock" 
                            class="flex-1 bg-purple-600 text-white px-6 py-3 rounded-lg hover:bg-purple-700 font-medium">
                        <i class="fas fa-save ml-2"></i> حفظ
                    </button>
                    <button type="button" onclick="closeStockModal()" 
                            class="flex-1 bg-gray-300 text-gray-700 px-6 py-3 rounded-lg hover:bg-gray-400 font-medium">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openStockModal(productId, productName, currentStock) {
            document.getElementById('modal_product_id').value = productId;
            document.getElementById('modal_product_name').textContent = productName;
            document.getElementById('modal_current_stock').textContent = currentStock;
            document.getElementById('stockModal').classList.remove('hidden');
        }

        function closeStockModal() {
            document.getElementById('stockModal').classList.add('hidden');
        }

        <?php if ($message): ?>
        Swal.fire({
            icon: 'success',
            title: 'نجح!',
            text: '<?php echo $message; ?>',
            timer: 2000,
            showConfirmButton: false
        });
        <?php endif; ?>
    </script>
</body>
</html>
