<?php
require_once '../../config/database.php';
require_once '../../models/user.php';
require_once '../../models/order.php';

session_start();

// Check admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$database = new Database();
$db = $database->getConnection();
$user_model = new User($db);
$order_model = new Order($db);

$all_users = $user_model->getAllUsers() ?? [];
$all_orders = $order_model->getAllOrders();

// Calculate customer statistics
$customer_stats = [];
foreach ($all_users as $user) {
    $user_orders = array_filter($all_orders, function($order) use ($user) {
        return $order['user_id'] == $user['id'];
    });
    
    $total_spent = array_reduce($user_orders, function($total, $order) {
        return $total + $order['total_amount'];
    }, 0);
    
    $customer_stats[$user['id']] = [
        'total_orders' => count($user_orders),
        'total_spent' => $total_spent,
        'last_order' => !empty($user_orders) ? max(array_column($user_orders, 'created_at')) : null
    ];
}

// Get search and filter parameters
$search = $_GET['search'] ?? '';
$filter_verified = $_GET['verified'] ?? '';

// Filter users
if ($search) {
    $all_users = array_filter($all_users, function($user) use ($search) {
        return stripos($user['name'], $search) !== false || 
               stripos($user['phone'], $search) !== false;
    });
}

if ($filter_verified !== '') {
    $all_users = array_filter($all_users, function($user) use ($filter_verified) {
        return $user['is_verified'] == $filter_verified;
    });
}

// Statistics
$total_customers = count(array_filter($all_users, fn($u) => $u['role'] !== 'admin'));
$verified_customers = count(array_filter($all_users, fn($u) => $u['role'] !== 'admin' && $u['is_verified']));
$total_revenue = array_sum(array_column($customer_stats, 'total_spent'));
?>
<!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>
                    <div>
                        <h1 class="text-2xl font-bold text-gray-900">إدارة العملاء</h1>
                        <p class="text-sm text-gray-500">عرض وإدارة بيانات العملاء</p>
                    </div>
                </div>
                <div class="flex items-center space-x-3 space-x-reverse">
                    <button onclick="window.print()" class="bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-print ml-2"></i>طباعة
                    </button>
                </div>
            </div>
        </header>

        <div class="p-6">
            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">إجمالي العملاء</p>
                            <p class="text-3xl font-bold text-gray-900"><?php echo $total_customers; ?></p>
                        </div>
                        <div class="bg-blue-50 p-3 rounded-lg">
                            <i class="fas fa-users text-blue-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">عملاء موثقين</p>
                            <p class="text-3xl font-bold text-green-600"><?php echo $verified_customers; ?></p>
                        </div>
                        <div class="bg-green-50 p-3 rounded-lg">
                            <i class="fas fa-user-check text-green-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">إجمالي الإيرادات</p>
                            <p class="text-3xl font-bold text-purple-600"><?php echo number_format($total_revenue, 0); ?></p>
                        </div>
                        <div class="bg-purple-50 p-3 rounded-lg">
                            <i class="fas fa-dollar-sign text-purple-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">متوسط الإنفاق</p>
                            <p class="text-3xl font-bold text-orange-600">
                                <?php echo $total_customers > 0 ? number_format($total_revenue / $total_customers, 0) : 0; ?>
                            </p>
                        </div>
                        <div class="bg-orange-50 p-3 rounded-lg">
                            <i class="fas fa-chart-line text-orange-600 text-2xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Search and Filter -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
                <form method="GET" class="flex flex-wrap items-center gap-4">
                    <div class="flex-1 min-w-[200px]">
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                               placeholder="بحث بالاسم أو رقم الهاتف..."
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <select name="verified" class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">جميع العملاء</option>
                            <option value="1" <?php echo $filter_verified === '1' ? 'selected' : ''; ?>>موثقين فقط</option>
                            <option value="0" <?php echo $filter_verified === '0' ? 'selected' : ''; ?>>غير موثقين</option>
                        </select>
                    </div>
                    <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-search ml-2"></i>بحث
                    </button>
                    <?php if ($search || $filter_verified !== ''): ?>
                        <a href="index.php" class="bg-gray-100 text-gray-700 px-6 py-2 rounded-lg hover:bg-gray-200">
                            <i class="fas fa-times ml-2"></i>إلغاء
                        </a>
                    <?php endif; ?>
                </form>
            </div>
            <!-- Customers Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php if (!empty($all_users)): ?>
                    <?php foreach ($all_users as $user): ?>
                        <?php if ($user['role'] !== 'admin'): ?>
                            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-lg transition-shadow">
                                <!-- Header with Profile Picture -->
                                <div class="bg-gradient-to-br from-blue-500 to-purple-600 p-6 text-white relative">
                                    <?php if ($user['is_verified']): ?>
                                        <div class="absolute top-3 left-3">
                                            <span class="bg-green-500 text-white px-2 py-1 rounded-full text-xs flex items-center">
                                                <i class="fas fa-check-circle ml-1"></i>موثق
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="flex items-center">
                                        <?php if (!empty($user['profile_picture'])): ?>
                                            <img src="../../<?php echo htmlspecialchars($user['profile_picture']); ?>" 
                                                 alt="<?php echo htmlspecialchars($user['name']); ?>"
                                                 class="w-16 h-16 rounded-full border-4 border-white object-cover">
                                        <?php else: ?>
                                            <div class="w-16 h-16 bg-white rounded-full flex items-center justify-center text-blue-600 font-bold text-2xl border-4 border-white">
                                                <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <div class="mr-4 flex-1">
                                            <h3 class="text-xl font-bold"><?php echo htmlspecialchars($user['name']); ?></h3>
                                            <?php if (!empty($user['age'])): ?>
                                                <p class="text-sm opacity-90"><?php echo $user['age']; ?> سنة</p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>

                                <!-- Contact Info -->
                                <div class="p-6">
                                    <div class="space-y-3 mb-4">
                                        <?php if (!empty($user['phone'])): ?>
                                            <div class="flex items-center text-sm">
                                                <i class="fas fa-phone text-blue-600 w-5"></i>
                                                <span class="text-gray-700 mr-2"><?php echo htmlspecialchars($user['phone']); ?></span>
                                                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $user['phone']); ?>" 
                                                   target="_blank" class="text-green-600 hover:text-green-700 mr-auto">
                                                    <i class="fab fa-whatsapp"></i>
                                                </a>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($user['address'])): ?>
                                            <div class="flex items-start text-sm">
                                                <i class="fas fa-map-marker-alt text-red-600 w-5 mt-1"></i>
                                                <span class="text-gray-700 mr-2"><?php echo htmlspecialchars($user['address']); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <?php if (!empty($user['bio'])): ?>
                                        <div class="bg-gray-50 rounded-lg p-3 mb-4">
                                            <p class="text-sm text-gray-600 italic">"<?php echo htmlspecialchars($user['bio']); ?>"</p>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Social Stats -->
                                    <div class="grid grid-cols-3 gap-2 mb-4 pb-4 border-b">
                                        <div class="text-center">
                                            <div class="text-lg font-bold text-blue-600"><?php echo $user['total_followers'] ?? 0; ?></div>
                                            <div class="text-xs text-gray-500">متابعين</div>
                                        </div>
                                        <div class="text-center">
                                            <div class="text-lg font-bold text-purple-600"><?php echo $user['total_following'] ?? 0; ?></div>
                                            <div class="text-xs text-gray-500">يتابع</div>
                                        </div>
                                        <div class="text-center">
                                            <div class="text-lg font-bold text-pink-600"><?php echo $user['total_likes'] ?? 0; ?></div>
                                            <div class="text-xs text-gray-500">إعجاب</div>
                                        </div>
                                    </div>

                                    <!-- Order Stats -->
                                    <div class="space-y-2 mb-4">
                                        <div class="flex items-center justify-between text-sm">
                                            <span class="text-gray-600">عدد الطلبات:</span>
                                            <span class="font-semibold text-gray-900"><?php echo $customer_stats[$user['id']]['total_orders']; ?></span>
                                        </div>
                                        <div class="flex items-center justify-between text-sm">
                                            <span class="text-gray-600">إجمالي الإنفاق:</span>
                                            <span class="font-semibold text-green-600"><?php echo number_format($customer_stats[$user['id']]['total_spent'], 0); ?> ج.م</span>
                                        </div>
                                        <?php if ($customer_stats[$user['id']]['last_order']): ?>
                                            <div class="flex items-center justify-between text-sm">
                                                <span class="text-gray-600">آخر طلب:</span>
                                                <span class="text-gray-900"><?php echo date('Y-m-d', strtotime($customer_stats[$user['id']]['last_order'])); ?></span>
                                            </div>
                                        <?php endif; ?>
                                        <div class="flex items-center justify-between text-sm">
                                            <span class="text-gray-600">تاريخ التسجيل:</span>
                                            <span class="text-gray-900"><?php echo date('Y-m-d', strtotime($user['created_at'])); ?></span>
                                        </div>
                                    </div>

                                    <!-- Actions -->
                                    <div class="flex items-center gap-2">
                                        <a href="view.php?id=<?php echo $user['id']; ?>" 
                                           class="flex-1 bg-blue-50 text-blue-600 px-3 py-2 rounded-md text-sm text-center hover:bg-blue-100 transition">
                                            <i class="fas fa-eye ml-1"></i>عرض
                                        </a>
                                        <a href="edit.php?id=<?php echo $user['id']; ?>" 
                                           class="flex-1 bg-green-50 text-green-600 px-3 py-2 rounded-md text-sm text-center hover:bg-green-100 transition">
                                            <i class="fas fa-edit ml-1"></i>تعديل
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-span-3 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-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-users text-4xl text-gray-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>
