<?php
$pageTitle = 'تقرير المخزون الحالي';
include __DIR__ . '/../../includes/header.php';

// التحقق من الصلاحيات
checkLogin();
if (!hasPermission('view_inventory_reports')) {
    header('Location: ' . SITE_URL . '/pages/errors/access_denied.php');
    exit();
}

$db = getDB();

$category_filter = $_GET['category'] ?? '';
$low_stock_only = isset($_GET['low_stock_only']);

$sql = "SELECT p.*, 
                COALESCE(SUM(CASE WHEN im.movement_type = 'in' THEN im.quantity ELSE -im.quantity END), 0) as current_stock
        FROM products p
        LEFT JOIN inventory_movements im ON p.id = im.product_id
        WHERE 1=1";

$params = [];

if (!empty($category_filter)) {
    $sql .= " AND p.category = ?";
    $params[] = $category_filter;
}

$sql .= " GROUP BY p.id";

if ($low_stock_only) {
    $sql .= " HAVING current_stock <= p.minimum_stock";
}

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

$inventory_data = $db->select($sql, $params);

// جلب الفئات المتاحة
$categories = $db->select("SELECT DISTINCT category FROM products WHERE category IS NOT NULL AND category != '' ORDER BY category ASC");

// --- التعديل الأساسي لحل المشكلة ---
// إحصائيات عامة
$total_products = 0;
$low_stock_products = 0;

$total_products_data = $db->selectOne("SELECT COUNT(*) as count FROM products");
if ($total_products_data !== false) {
    $total_products = $total_products_data['count'];
}

$low_stock_products_data = $db->selectOne("
    SELECT COUNT(*) as count 
    FROM (
        SELECT p.id, COALESCE(SUM(CASE WHEN im.movement_type = 'in' THEN im.quantity ELSE -im.quantity END), 0) as current_stock
        FROM products p
        LEFT JOIN inventory_movements im ON p.id = im.product_id
        GROUP BY p.id
        HAVING current_stock <= p.minimum_stock
    ) as low_stock_items
");
if ($low_stock_products_data !== false) {
    $low_stock_products = $low_stock_products_data['count'];
}
// ------------------------------------
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><?php echo $pageTitle; ?></h3>
                </div>
                <div class="card-body">
                    <form action="" method="GET" class="row g-3 align-items-center mb-4">
                        <div class="col-md-4">
                            <label for="category" class="form-label">الفئة:</label>
                            <select class="form-select" id="category" name="category">
                                <option value="">جميع الفئات</option>
                                <?php if (is_array($categories)): // تأكد من أن $categories مصفوفة ?>
                                <?php foreach ($categories as $category): ?>
                                    <option value="<?php echo htmlspecialchars($category['category']); ?>" <?php echo ($category_filter == $category['category']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($category['category']); ?>
                                    </option>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="low_stock_only" name="low_stock_only" <?php echo $low_stock_only ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="low_stock_only">
                                    عرض المنتجات منخفضة المخزون فقط
                                </label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <button type="submit" class="btn btn-primary mt-4">
                                <i class="fas fa-filter me-2"></i>تصفية التقرير
                            </button>
                        </div>
                    </form>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card bg-light mb-3">
                                <div class="card-body">
                                    <h5 class="card-title">إجمالي المنتجات</h5>
                                    <p class="card-text fs-4"><?php echo $total_products; ?></p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card bg-warning text-white mb-3">
                                <div class="card-body">
                                    <h5 class="card-title">منتجات منخفضة المخزون</h5>
                                    <p class="card-text fs-4"><?php echo $low_stock_products; ?></p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (empty($inventory_data) || $inventory_data === false): ?>
                        <div class="alert alert-info text-center" role="alert">
                            لا توجد منتجات لعرضها.
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>اسم المنتج</th>
                                        <th>الفئة</th>
                                        <th>المخزون الحالي</th>
                                        <th>الحد الأدنى للمخزون</th>
                                        <th>الحالة</th>
                                        <th>السعر</th>
                                        <th>قيمة المخزون</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($inventory_data as $item): ?>
                                        <tr class="<?php echo ($item['current_stock'] <= $item['minimum_stock']) ? 'table-warning' : ''; ?>">
                                            <td><?php echo htmlspecialchars($item['product_name']); ?></td>
                                            <td><?php echo htmlspecialchars($item['category'] ?? 'غير محدد'); ?></td>
                                            <td><?php echo htmlspecialchars($item['current_stock']); ?></td>
                                            <td><?php echo htmlspecialchars($item['minimum_stock']); ?></td>
                                            <td>
                                                <?php if ($item['current_stock'] <= $item['minimum_stock']): ?>
                                                    <span class="badge bg-warning">مخزون منخفض</span>
                                                <?php elseif ($item['current_stock'] == 0): ?>
                                                    <span class="badge bg-danger">نفد المخزون</span>
                                                <?php else: ?>
                                                    <span class="badge bg-success">متوفر</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>SAR <?php echo htmlspecialchars(number_format($item['price'], 2)); ?></td>
                                            <td>SAR <?php echo htmlspecialchars(number_format($item['current_stock'] * $item['price'], 2)); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>

                    <div class="mt-4">
                        <a href="<?php echo SITE_URL; ?>/pages/reports/index.php" class="btn btn-secondary">
                            <i class="fas fa-arrow-left me-2"></i>العودة للتقارير
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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