<?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();

// تقرير حركات المخزون
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');

$stmt = $conn->prepare("SELECT 
    im.*,
    p.name as product_name,
    p.sku,
    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
WHERE DATE(im.created_at) BETWEEN ? AND ?
ORDER BY im.created_at DESC");
$stmt->execute([$date_from, $date_to]);
$movements = $stmt->fetchAll(PDO::FETCH_ASSOC);

// إحصائيات الحركات
$stmt = $conn->prepare("SELECT 
    movement_type,
    COUNT(*) as count,
    SUM(quantity) as total_quantity
FROM inventory_movements
WHERE DATE(created_at) BETWEEN ? AND ?
GROUP BY movement_type");
$stmt->execute([$date_from, $date_to]);
$movement_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);

// المنتجات الأكثر حركة
$stmt = $conn->prepare("SELECT 
    p.name,
    p.sku,
    COUNT(im.id) as movement_count,
    SUM(CASE WHEN im.movement_type IN ('in', 'return') THEN im.quantity ELSE 0 END) as total_in,
    SUM(CASE WHEN im.movement_type IN ('out', 'adjustment') THEN im.quantity ELSE 0 END) as total_out
FROM inventory_movements im
LEFT JOIN products p ON im.product_id = p.id
WHERE DATE(im.created_at) BETWEEN ? AND ?
GROUP BY im.product_id
ORDER BY movement_count DESC
LIMIT 10");
$stmt->execute([$date_from, $date_to]);
$top_products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// التنبيهات النشطة
$stmt = $conn->query("SELECT 
    ia.*,
    p.name as product_name,
    p.sku,
    p.stock_quantity
FROM inventory_alerts ia
LEFT JOIN products p ON ia.product_id = p.id
WHERE ia.is_resolved = 0
ORDER BY ia.created_at DESC");
$active_alerts = $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/chart.js"></script>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <div class="bg-gradient-to-r from-teal-600 to-teal-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-teal-100">تحليلات وتقارير شاملة لحركة المخزون</p>
                    </div>
                    <a href="index.php" class="bg-white text-teal-600 px-6 py-2 rounded-lg hover:bg-teal-50">
                        <i class="fas fa-arrow-right ml-2"></i> العودة
                    </a>
                </div>
            </div>
        </div>

        <div class="max-w-7xl mx-auto p-6">
            <!-- فلتر التاريخ -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <form method="GET" class="flex gap-4 items-end">
                    <div class="flex-1">
                        <label class="block text-gray-700 font-medium mb-2">من تاريخ</label>
                        <input type="date" name="date_from" value="<?php echo $date_from; ?>" 
                               class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-teal-500">
                    </div>
                    <div class="flex-1">
                        <label class="block text-gray-700 font-medium mb-2">إلى تاريخ</label>
                        <input type="date" name="date_to" value="<?php echo $date_to; ?>" 
                               class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-teal-500">
                    </div>
                    <button type="submit" class="bg-teal-600 text-white px-6 py-2 rounded-lg hover:bg-teal-700">
                        <i class="fas fa-filter ml-2"></i> تطبيق
                    </button>
                    <button type="button" onclick="window.print()" class="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700">
                        <i class="fas fa-print ml-2"></i> طباعة
                    </button>
                </form>
            </div>

            <!-- إحصائيات الحركات -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                <?php
                $stats_display = [
                    'in' => ['name' => 'إضافات', 'icon' => 'fa-plus-circle', 'color' => 'green'],
                    'out' => ['name' => 'صرف', 'icon' => 'fa-minus-circle', 'color' => 'red'],
                    'adjustment' => ['name' => 'تعديلات', 'icon' => 'fa-edit', 'color' => 'blue'],
                    'return' => ['name' => 'إرجاع', 'icon' => 'fa-undo', 'color' => 'purple']
                ];
                
                foreach ($stats_display as $type => $info):
                    $stat = array_filter($movement_stats, fn($s) => $s['movement_type'] === $type);
                    $stat = reset($stat);
                    $count = $stat['count'] ?? 0;
                    $quantity = $stat['total_quantity'] ?? 0;
                ?>
                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between mb-2">
                        <div>
                            <p class="text-gray-500 text-sm"><?php echo $info['name']; ?></p>
                            <p class="text-2xl font-bold text-<?php echo $info['color']; ?>-600"><?php echo $count; ?></p>
                        </div>
                        <div class="bg-<?php echo $info['color']; ?>-100 p-3 rounded-full">
                            <i class="fas <?php echo $info['icon']; ?> text-<?php echo $info['color']; ?>-600 text-xl"></i>
                        </div>
                    </div>
                    <p class="text-sm text-gray-500">الكمية: <?php echo $quantity; ?></p>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- الرسم البياني -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <h2 class="text-xl font-bold mb-4">
                    <i class="fas fa-chart-bar ml-2 text-teal-600"></i> توزيع حركات المخزون
                </h2>
                <canvas id="movementChart" height="80"></canvas>
            </div>

            <!-- المنتجات الأكثر حركة -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <h2 class="text-xl font-bold mb-4">
                    <i class="fas fa-fire ml-2 text-orange-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">SKU</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 ($top_products as $product): 
                                $net = $product['total_in'] - $product['total_out'];
                            ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-4 py-3 font-medium"><?php echo htmlspecialchars($product['name']); ?></td>
                                <td class="px-4 py-3 text-sm text-gray-500"><?php echo htmlspecialchars($product['sku'] ?? '-'); ?></td>
                                <td class="px-4 py-3 text-center">
                                    <span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium">
                                        <?php echo $product['movement_count']; ?>
                                    </span>
                                </td>
                                <td class="px-4 py-3 text-center text-green-600 font-medium">+<?php echo $product['total_in']; ?></td>
                                <td class="px-4 py-3 text-center text-red-600 font-medium">-<?php echo $product['total_out']; ?></td>
                                <td class="px-4 py-3 text-center font-bold <?php echo $net >= 0 ? 'text-green-600' : 'text-red-600'; ?>">
                                    <?php echo $net >= 0 ? '+' : ''; ?><?php echo $net; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- التنبيهات النشطة -->
            <?php if (count($active_alerts) > 0): ?>
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <h2 class="text-xl font-bold mb-4">
                    <i class="fas fa-bell ml-2 text-red-600"></i> التنبيهات النشطة
                </h2>
                <div class="space-y-3">
                    <?php foreach ($active_alerts as $alert): ?>
                    <div class="flex items-center justify-between p-4 <?php echo $alert['alert_type'] === 'out_of_stock' ? 'bg-red-50 border-r-4 border-red-500' : 'bg-yellow-50 border-r-4 border-yellow-500'; ?> rounded">
                        <div class="flex items-center gap-4">
                            <i class="fas fa-exclamation-triangle text-2xl <?php echo $alert['alert_type'] === 'out_of_stock' ? 'text-red-600' : 'text-yellow-600'; ?>"></i>
                            <div>
                                <p class="font-bold"><?php echo htmlspecialchars($alert['product_name']); ?></p>
                                <p class="text-sm text-gray-600">
                                    <?php if ($alert['alert_type'] === 'out_of_stock'): ?>
                                        نفذ من المخزون
                                    <?php else: ?>
                                        مخزون منخفض (<?php echo $alert['current_quantity']; ?> / <?php echo $alert['threshold_quantity']; ?>)
                                    <?php endif; ?>
                                </p>
                            </div>
                        </div>
                        <span class="text-sm text-gray-500"><?php echo date('Y-m-d', strtotime($alert['created_at'])); ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- تفاصيل الحركات -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-bold mb-4">
                    <i class="fas fa-list ml-2 text-teal-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">SKU</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 ($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 date('Y-m-d H:i', strtotime($movement['created_at'])); ?></td>
                                <td class="px-4 py-3 text-sm font-medium"><?php echo htmlspecialchars($movement['product_name']); ?></td>
                                <td class="px-4 py-3 text-sm text-gray-500"><?php echo htmlspecialchars($movement['sku'] ?? '-'); ?></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 text-center font-bold"><?php echo $movement['quantity']; ?></td>
                                <td class="px-4 py-3 text-center text-sm text-gray-500"><?php echo $movement['previous_quantity']; ?></td>
                                <td class="px-4 py-3 text-center 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>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        // رسم بياني لحركات المخزون
        const ctx = document.getElementById('movementChart').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['إضافات', 'صرف', 'تعديلات', 'إرجاع'],
                datasets: [{
                    label: 'عدد الحركات',
                    data: [
                        <?php 
                        foreach (['in', 'out', 'adjustment', 'return'] as $type) {
                            $stat = array_filter($movement_stats, fn($s) => $s['movement_type'] === $type);
                            $stat = reset($stat);
                            echo ($stat['count'] ?? 0) . ',';
                        }
                        ?>
                    ],
                    backgroundColor: [
                        'rgba(34, 197, 94, 0.8)',
                        'rgba(239, 68, 68, 0.8)',
                        'rgba(59, 130, 246, 0.8)',
                        'rgba(168, 85, 247, 0.8)'
                    ],
                    borderColor: [
                        'rgb(34, 197, 94)',
                        'rgb(239, 68, 68)',
                        'rgb(59, 130, 246)',
                        'rgb(168, 85, 247)'
                    ],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>
