<?php
session_start();
require_once '../../config/database.php';

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

$database = new Database();
$conn = $database->getConnection();

// Pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filters
$skinTypeFilter = isset($_GET['skin_type']) ? $_GET['skin_type'] : '';
$contactedFilter = isset($_GET['contacted']) ? $_GET['contacted'] : '';
$searchQuery = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query
$where = [];
$params = [];

if ($skinTypeFilter) {
    $where[] = "skin_type = ?";
    $params[] = $skinTypeFilter;
}

if ($contactedFilter !== '') {
    $where[] = "is_contacted = ?";
    $params[] = $contactedFilter;
}

if ($searchQuery) {
    $where[] = "(name LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $searchParam = "%{$searchQuery}%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$whereClause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// Get total count
$countQuery = "SELECT COUNT(*) as total FROM skin_quiz_results {$whereClause}";
$countStmt = $conn->prepare($countQuery);
$countStmt->execute($params);
$totalResults = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
$totalPages = ceil($totalResults / $perPage);

// Get results
$query = "SELECT * FROM skin_quiz_results {$whereClause} ORDER BY created_at DESC LIMIT {$perPage} OFFSET {$offset}";
$stmt = $conn->prepare($query);
$stmt->execute($params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Statistics
$statsQuery = "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN is_contacted = 1 THEN 1 ELSE 0 END) as contacted,
        AVG(score) as avg_score,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as this_week
    FROM skin_quiz_results
";
$statsStmt = $conn->query($statsQuery);
$stats = $statsStmt->fetch(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 Admin</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">
    <link rel="stylesheet" href="../assets/css/admin-layout.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
    </style>
</head>
<body class="bg-gray-50">

<?php include '../includes/sidebar.php'; ?>

<div style="margin-right: 280px; padding: 24px;">
    
    <!-- Header -->
    <header class="bg-white shadow-sm border-b border-gray-200 rounded-lg mb-6 p-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-3xl font-bold text-gray-900">🧪 نتائج اختبار البشرة</h1>
                <p class="text-sm text-gray-500 mt-1">إدارة ومتابعة نتائج اختبارات العملاء</p>
            </div>
            <div class="flex gap-3">
                <a href="analytics.php" class="bg-purple-500 text-white px-6 py-3 rounded-lg hover:bg-purple-600 transition flex items-center gap-2">
                    <i class="fas fa-chart-bar"></i>
                    <span>الإحصائيات</span>
                </a>
                <a href="questions.php" class="bg-blue-500 text-white px-6 py-3 rounded-lg hover:bg-blue-600 transition flex items-center gap-2">
                    <i class="fas fa-question-circle"></i>
                    <span>إدارة الأسئلة</span>
                </a>
            </div>
        </div>
    </header>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">إجمالي النتائج</p>
                    <p class="text-3xl font-bold text-gray-900 mt-2"><?php echo number_format($stats['total']); ?></p>
                </div>
                <div class="bg-blue-100 p-4 rounded-full">
                    <i class="fas fa-vial text-blue-600 text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">تم التواصل</p>
                    <p class="text-3xl font-bold text-green-600 mt-2"><?php echo number_format($stats['contacted']); ?></p>
                </div>
                <div class="bg-green-100 p-4 rounded-full">
                    <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">متوسط النتيجة</p>
                    <p class="text-3xl font-bold text-purple-600 mt-2"><?php echo round($stats['avg_score']); ?></p>
                </div>
                <div class="bg-purple-100 p-4 rounded-full">
                    <i class="fas fa-star text-purple-600 text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">هذا الأسبوع</p>
                    <p class="text-3xl font-bold text-orange-600 mt-2"><?php echo number_format($stats['this_week']); ?></p>
                </div>
                <div class="bg-orange-100 p-4 rounded-full">
                    <i class="fas fa-calendar-week text-orange-600 text-2xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">البحث</label>
                <input type="text" name="search" value="<?php echo htmlspecialchars($searchQuery); ?>" 
                       placeholder="اسم، إيميل، أو هاتف..." 
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">نوع البشرة</label>
                <select name="skin_type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    <option value="">الكل</option>
                    <option value="oily" <?php echo $skinTypeFilter === 'oily' ? 'selected' : ''; ?>>دهنية</option>
                    <option value="dry" <?php echo $skinTypeFilter === 'dry' ? 'selected' : ''; ?>>جافة</option>
                    <option value="combination" <?php echo $skinTypeFilter === 'combination' ? 'selected' : ''; ?>>مختلطة</option>
                    <option value="normal" <?php echo $skinTypeFilter === 'normal' ? 'selected' : ''; ?>>عادية</option>
                    <option value="sensitive" <?php echo $skinTypeFilter === 'sensitive' ? 'selected' : ''; ?>>حساسة</option>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">حالة التواصل</label>
                <select name="contacted" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    <option value="">الكل</option>
                    <option value="1" <?php echo $contactedFilter === '1' ? 'selected' : ''; ?>>تم التواصل</option>
                    <option value="0" <?php echo $contactedFilter === '0' ? 'selected' : ''; ?>>لم يتم التواصل</option>
                </select>
            </div>
            
            <div class="flex items-end gap-2">
                <button type="submit" class="flex-1 bg-purple-600 text-white px-6 py-2 rounded-lg hover:bg-purple-700 transition">
                    <i class="fas fa-search"></i> بحث
                </button>
                <a href="index.php" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition">
                    <i class="fas fa-redo"></i>
                </a>
            </div>
        </form>
    </div>

    <!-- Results Table -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
        <table class="w-full">
            <thead class="bg-gray-50 border-b border-gray-200">
                <tr>
                    <th class="px-6 py-4 text-right text-xs font-medium text-gray-500 uppercase">العميل</th>
                    <th class="px-6 py-4 text-right text-xs font-medium text-gray-500 uppercase">نوع البشرة</th>
                    <th class="px-6 py-4 text-right text-xs font-medium text-gray-500 uppercase">النتيجة</th>
                    <th class="px-6 py-4 text-right text-xs font-medium text-gray-500 uppercase">التاريخ</th>
                    <th class="px-6 py-4 text-right text-xs font-medium text-gray-500 uppercase">الحالة</th>
                    <th class="px-6 py-4 text-right text-xs font-medium text-gray-500 uppercase">إجراءات</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200">
                <?php if (empty($results)): ?>
                <tr>
                    <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                        <i class="fas fa-inbox text-4xl mb-2"></i>
                        <p>لا توجد نتائج</p>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($results as $result): 
                    $skinTypes = [
                        'oily' => ['name' => 'دهنية', 'color' => 'blue'],
                        'dry' => ['name' => 'جافة', 'color' => 'orange'],
                        'combination' => ['name' => 'مختلطة', 'color' => 'purple'],
                        'normal' => ['name' => 'عادية', 'color' => 'green'],
                        'sensitive' => ['name' => 'حساسة', 'color' => 'pink']
                    ];
                    $skinInfo = $skinTypes[$result['skin_type']] ?? ['name' => $result['skin_type'], 'color' => 'gray'];
                ?>
                <tr class="hover:bg-gray-50">
                    <td class="px-6 py-4">
                        <div class="font-medium text-gray-900"><?php echo htmlspecialchars($result['name']); ?></div>
                        <div class="text-sm text-gray-500"><?php echo htmlspecialchars($result['email']); ?></div>
                        <?php if ($result['phone']): ?>
                        <div class="text-sm text-gray-500"><?php echo htmlspecialchars($result['phone']); ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="px-6 py-4">
                        <span class="px-3 py-1 rounded-full text-xs font-semibold bg-<?php echo $skinInfo['color']; ?>-100 text-<?php echo $skinInfo['color']; ?>-800">
                            <?php echo $skinInfo['name']; ?>
                        </span>
                    </td>
                    <td class="px-6 py-4">
                        <div class="flex items-center gap-2">
                            <div class="text-2xl font-bold text-gray-900"><?php echo $result['score']; ?></div>
                            <div class="text-sm text-gray-500">/100</div>
                        </div>
                    </td>
                    <td class="px-6 py-4 text-sm text-gray-500">
                        <?php echo date('Y-m-d', strtotime($result['created_at'])); ?>
                        <br>
                        <span class="text-xs"><?php echo date('H:i', strtotime($result['created_at'])); ?></span>
                    </td>
                    <td class="px-6 py-4">
                        <?php if ($result['is_contacted']): ?>
                        <span class="px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800">
                            <i class="fas fa-check"></i> تم التواصل
                        </span>
                        <?php else: ?>
                        <span class="px-3 py-1 rounded-full text-xs font-semibold bg-yellow-100 text-yellow-800">
                            <i class="fas fa-clock"></i> قيد الانتظار
                        </span>
                        <?php endif; ?>
                    </td>
                    <td class="px-6 py-4">
                        <div class="flex gap-2">
                            <a href="view.php?id=<?php echo $result['id']; ?>" 
                               class="bg-blue-500 text-white px-3 py-1 rounded text-sm hover:bg-blue-600 transition">
                                <i class="fas fa-eye"></i> عرض
                            </a>
                            <?php if (!$result['is_contacted']): ?>
                            <button onclick="markContacted(<?php echo $result['id']; ?>)" 
                                    class="bg-green-500 text-white px-3 py-1 rounded text-sm hover:bg-green-600 transition">
                                <i class="fas fa-check"></i> تم
                            </button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <div class="mt-6 flex justify-center gap-2">
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <a href="?page=<?php echo $i; ?>&skin_type=<?php echo $skinTypeFilter; ?>&contacted=<?php echo $contactedFilter; ?>&search=<?php echo urlencode($searchQuery); ?>" 
           class="px-4 py-2 rounded-lg <?php echo $i === $page ? 'bg-purple-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-100'; ?> transition">
            <?php echo $i; ?>
        </a>
        <?php endfor; ?>
    </div>
    <?php endif; ?>
</div>

<script>
function markContacted(id) {
    if (!confirm('هل تم التواصل مع هذا العميل؟')) return;
    
    fetch('update-status.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: id, contacted: 1 })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('حدث خطأ: ' + data.message);
        }
    });
}
</script>

</body>
</html>
