<?php
// Include required files
require_once '../../config/database.php';
require_once '../../models/user.php';
require_once '../../models/product.php';
require_once '../../models/order.php';
require_once '../../models/review.php';
require_once '../../models/beautyservice.php';
require_once '../../models/beautybooking.php';

// Initialize database
$database = new Database();
$db = $database->getConnection();

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// Get user data
$user_model = new User($db);
$user_data = $user_model->getUserById($_SESSION['user_id']);

// Get models
$product_model = new Product($db);
$order_model = new Order($db);
$review_model = new Review($db);
$beauty_service_model = new BeautyService($db);
$beauty_booking_model = new BeautyBooking($db);

// Handle admin actions
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['approve_review'])) {
        $review_id = $_POST['review_id'];
        if ($review_model->updateReview($review_id, ['is_approved' => 1])) {
            $message = 'تم اعتماد التقييم بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء اعتماد التقييم';
        }
    } elseif (isset($_POST['hide_review'])) {
        $review_id = $_POST['review_id'];
        if ($review_model->updateReview($review_id, ['is_visible' => 0])) {
            $message = 'تم إخفاء التقييم بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء إخفاء التقييم';
        }
    } elseif (isset($_POST['show_review'])) {
        $review_id = $_POST['review_id'];
        if ($review_model->updateReview($review_id, ['is_visible' => 1])) {
            $message = 'تم إظهار التقييم بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء إظهار التقييم';
        }
    } elseif (isset($_POST['delete_review'])) {
        $review_id = $_POST['review_id'];
        if ($review_model->deleteReview($review_id)) {
            $message = 'تم حذف التقييم بنجاح!';
        } else {
            $message = 'حدث خطأ أثناء حذف التقييم';
        }
    }
}

// Get reviews statistics
$all_reviews = $review_model->getAllReviews();
$total_reviews = count($all_reviews);
$average_rating = $total_reviews > 0 ? array_reduce($all_reviews, function($total, $review) {
    return $total + $review['rating'];
}, 0) / $total_reviews : 0;

$approved_reviews = array_filter($all_reviews, function($review) {
    return $review['is_approved'] == 1;
});
$visible_reviews = array_filter($all_reviews, function($review) {
    return $review['is_visible'] == 1;
});
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة التقييمات - لوحة تحكم المدير</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">
    <script src="https://unpkg.com/sweetalert2@11"></script>
    <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;
            direction: rtl;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen" style="background-attachment: fixed;">

    <!-- Header -->
    <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-3">
            <div class="flex items-center">
                <button onclick="window.location.href='admin.php'" class="p-2 rounded-lg text-gray-600 hover:bg-gray-100 transition-all duration-200 mr-3">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                </button>
                <div class="flex items-center ml-4">
                    <?php if ($user_data['profile_picture']): ?>
                        <img src="<?php echo htmlspecialchars($user_data['profile_picture']); ?>" alt="صورة الملف الشخصي" class="w-8 h-8 rounded-lg mr-3 object-cover">
                    <?php else: ?>
                        <div class="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white font-bold text-sm mr-3">
                            <?php echo strtoupper(substr($user_data['name'], 0, 1)); ?>
                        </div>
                    <?php endif; ?>
                    <h1 class="text-xl font-semibold text-gray-900">إدارة التقييمات</h1>
                </div>
            </div>
            <div class="flex items-center space-x-4 space-x-reverse">
                <a href="index.php" class="p-2 rounded-md text-gray-600 hover:bg-gray-100" title="المتجر">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                    </svg>
                </a>
                <a href="#" class="p-2 rounded-md text-gray-600 hover:bg-gray-100" title="الحساب">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                    </svg>
                </a>
                <a href="logout.php" class="p-2 rounded-md text-gray-600 hover:bg-gray-100" title="تسجيل الخروج">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                    </svg>
                </a>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="flex-1 flex flex-col min-w-0">
        <div class="p-4 lg:p-6 xl:p-8 flex-1 overflow-auto">

            <!-- Success/Error Message Display -->
            <?php if ($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <div class="mr-3">
                            <p class="text-sm text-green-700"><?php echo $message; ?></p>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Breadcrumb -->
            <div class="mb-6">
                <nav class="flex text-sm text-gray-500">
                    <a href="admin.php" class="hover:text-purple-600">لوحة التحكم</a>
                    <span class="mx-2">/</span>
                    <span class="text-gray-900">إدارة التقييمات</span>
                </nav>
            </div>

            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <!-- Total Reviews -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">إجمالي التقييمات</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo $total_reviews; ?></p>
                        </div>
                        <div class="bg-yellow-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-yellow-600 text-sm font-medium"><?php echo number_format($average_rating, 1); ?> ★ متوسط التقييم</span>
                    </div>
                </div>

                <!-- Approved Reviews -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">التقييمات المعتمدة</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($approved_reviews); ?></p>
                        </div>
                        <div class="bg-green-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-green-600 text-sm font-medium"><?php echo $total_reviews > 0 ? round((count($approved_reviews) / $total_reviews) * 100, 1) : 0; ?>% من الإجمالي</span>
                    </div>
                </div>

                <!-- Visible Reviews -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">التقييمات المرئية</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($visible_reviews); ?></p>
                        </div>
                        <div class="bg-blue-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-blue-600 text-sm font-medium"><?php echo $total_reviews > 0 ? round((count($visible_reviews) / $total_reviews) * 100, 1) : 0; ?>% من الإجمالي</span>
                    </div>
                </div>

                <!-- Pending Reviews -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-all duration-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">التقييمات المعلقة</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo $total_reviews - count($approved_reviews); ?></p>
                        </div>
                        <div class="bg-orange-50 p-3 rounded-lg">
                            <svg class="w-6 h-6 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-orange-600 text-sm font-medium">في انتظار المراجعة</span>
                    </div>
                </div>
            </div>

            <!-- Reviews Table -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900">جميع التقييمات</h3>
                    <p class="text-sm text-gray-600 mt-1">إجمالي التقييمات: <?php echo $total_reviews; ?> | متوسط التقييم: <?php echo number_format($average_rating, 1); ?> نجوم</p>
                </div>
                <div class="overflow-x-auto">
                    <?php if (!empty($all_reviews)): ?>
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">العميل</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">المنتج</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">التقييم</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الرأي</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الحالة</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">التاريخ</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php foreach ($all_reviews as $review): ?>
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($review['user_name']); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo htmlspecialchars($review['product_name'] ?? 'N/A'); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="flex items-center">
                                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                                    <span class="text-lg <?php echo $i <= $review['rating'] ? 'text-yellow-400' : 'text-gray-300'; ?>">★</span>
                                                <?php endfor; ?>
                                                <span class="ml-2 text-sm text-gray-600">(<?php echo $review['rating']; ?>/5)</span>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-900 max-w-xs truncate"><?php echo htmlspecialchars($review['comment']); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="flex items-center space-x-2 space-x-reverse">
                                                <?php if ($review['is_approved']): ?>
                                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">معتمد</span>
                                                <?php else: ?>
                                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">في الانتظار</span>
                                                <?php endif; ?>
                                                <?php if ($review['is_visible']): ?>
                                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">مرئي</span>
                                                <?php else: ?>
                                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">مخفي</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo date('Y-m-d H:i', strtotime($review['created_at'])); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <form method="POST" class="inline" style="display: inline;">
                                                <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                                                <?php if (!$review['is_approved']): ?>
                                                    <button type="submit" name="approve_review" class="text-green-600 hover:text-green-700 inline-flex items-center px-2 py-1 rounded-md hover:bg-green-50 transition-colors" title="اعتماد">
                                                        <i class="fas fa-check ml-1"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <?php if ($review['is_visible']): ?>
                                                    <button type="submit" name="hide_review" class="text-orange-600 hover:text-orange-700 inline-flex items-center px-2 py-1 rounded-md hover:bg-orange-50 transition-colors" title="إخفاء">
                                                        <i class="fas fa-eye-slash ml-1"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <button type="submit" name="show_review" class="text-blue-600 hover:text-blue-700 inline-flex items-center px-2 py-1 rounded-md hover:bg-blue-50 transition-colors" title="إظهار">
                                                        <i class="fas fa-eye ml-1"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <button type="submit" name="delete_review" onclick="return confirm('هل أنت متأكد من حذف هذا التقييم؟')" class="text-red-600 hover:text-red-700 inline-flex items-center px-2 py-1 rounded-md hover:bg-red-50 transition-colors" title="حذف">
                                                    <i class="fas fa-trash ml-1"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="text-center py-12">
                            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
                            </svg>
                            <h3 class="mt-2 text-sm font-medium text-gray-900">لا توجد تقييمات</h3>
                            <p class="mt-1 text-sm text-gray-500">لم يتم العثور على أي تقييمات في النظام.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

</body>
</html>