<?php
session_start();

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 abandoned carts (carts older than 24 hours with no orders)
    $query = "SELECT c.*, u.name as user_name, u.phone,
              p.name as product_name, p.price, p.image,
              (c.quantity * p.price) as subtotal
              FROM cart c
              JOIN users u ON c.user_id = u.id
              JOIN products p ON c.product_id = p.id
              WHERE c.created_at < DATE_SUB(NOW(), INTERVAL 24 HOUR)
              AND c.user_id NOT IN (
                  SELECT DISTINCT user_id FROM orders 
                  WHERE created_at > c.created_at
              )
              ORDER BY c.created_at DESC";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $abandoned_carts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Group by user
    $carts_by_user = [];
    foreach ($abandoned_carts as $item) {
        $user_id = $item['user_id'];
        if (!isset($carts_by_user[$user_id])) {
            $carts_by_user[$user_id] = [
                'user_name' => $item['user_name'],
                'phone' => $item['phone'],
                'items' => [],
                'total' => 0
            ];
        }
        $carts_by_user[$user_id]['items'][] = $item;
        $carts_by_user[$user_id]['total'] += $item['subtotal'];
    }
    
} catch (Exception $e) {
    $error = "خطأ: " . $e->getMessage();
    $carts_by_user = [];
}
?>
<!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 href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
            <div class="flex items-center justify-between px-6 py-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-900">السلات المتروكة</h1>
                </div>
            </div>
        </header>

        <div class="p-6">
            <?php if (isset($error)): ?>
                <div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6">
                    <p class="text-sm text-red-700"><?php echo $error; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <?php
                $total_users = count($carts_by_user);
                $total_items = count($abandoned_carts);
                $total_value = array_sum(array_column($carts_by_user, 'total'));
            ?>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">عدد العملاء</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo $total_users; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-users text-orange-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">عدد المنتجات</p>
                            <p class="text-2xl font-bold text-blue-600"><?php echo $total_items; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-shopping-cart text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">القيمة الإجمالية</p>
                            <p class="text-2xl font-bold text-red-600">EGP <?php echo number_format($total_value, 0); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-dollar-sign text-red-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Abandoned Carts List -->
            <div class="space-y-4">
                <?php if (!empty($carts_by_user)): ?>
                    <?php foreach ($carts_by_user as $user_id => $cart): ?>
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                            <div class="bg-gray-50 px-6 py-4 border-b border-gray-200">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <h3 class="text-lg font-semibold text-gray-900"><?php echo htmlspecialchars($cart['user_name']); ?></h3>
                                        <div class="flex items-center gap-4 mt-1 text-sm text-gray-600">
                                            <?php if (!empty($cart['phone'])): ?>
                                                <a href="https://wa.me/2<?php echo ltrim($cart['phone'], '0'); ?>" target="_blank" class="text-green-600 hover:text-green-700">
                                                    <i class="fab fa-whatsapp ml-1"></i><?php echo htmlspecialchars($cart['phone']); ?>
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="text-left">
                                        <p class="text-sm text-gray-600">إجمالي السلة</p>
                                        <p class="text-2xl font-bold text-red-600">EGP <?php echo number_format($cart['total'], 0); ?></p>
                                    </div>
                                </div>
                            </div>
                            <div class="p-6">
                                <div class="space-y-3">
                                    <?php foreach ($cart['items'] as $item): ?>
                                        <div class="flex items-center gap-4 p-3 bg-gray-50 rounded-lg">
                                            <?php if (!empty($item['image'])): ?>
                                                <img src="../../<?php echo htmlspecialchars($item['image']); ?>" 
                                                     alt="<?php echo htmlspecialchars($item['product_name']); ?>" 
                                                     class="w-16 h-16 object-cover rounded">
                                            <?php else: ?>
                                                <div class="w-16 h-16 bg-gray-200 rounded flex items-center justify-center">
                                                    <i class="fas fa-box text-gray-400"></i>
                                                </div>
                                            <?php endif; ?>
                                            <div class="flex-1">
                                                <h4 class="font-semibold text-gray-900"><?php echo htmlspecialchars($item['product_name']); ?></h4>
                                                <p class="text-sm text-gray-600">الكمية: <?php echo $item['quantity']; ?> × EGP <?php echo number_format($item['price'], 0); ?></p>
                                            </div>
                                            <div class="text-left">
                                                <p class="font-bold text-gray-900">EGP <?php echo number_format($item['subtotal'], 0); ?></p>
                                                <p class="text-xs text-gray-500"><?php echo date('Y-m-d H:i', strtotime($item['created_at'])); ?></p>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
                        <div class="max-w-md mx-auto">
                            <div class="w-24 h-24 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-check-circle text-4xl text-green-400"></i>
                            </div>
                            <h3 class="text-xl font-semibold text-gray-700 mb-2">لا توجد سلات متروكة</h3>
                            <p class="text-gray-500">جميع العملاء أكملوا طلباتهم!</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>
