<?php
/**
 * التحقق من وجود جداول اختبار البشرة
 */

require_once __DIR__ . '/../config/database.php';

header('Content-Type: text/html; charset=utf-8');

echo "<!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>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f5f5; padding: 40px; }
        .container { max-width: 900px; margin: 0 auto; background: white; border-radius: 20px; padding: 40px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); }
        h1 { color: #667eea; text-align: center; margin-bottom: 30px; }
        .status { padding: 15px; margin: 15px 0; border-radius: 10px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        .warning { background: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { padding: 12px; text-align: right; border-bottom: 1px solid #ddd; }
        th { background: #667eea; color: white; }
        .btn { display: inline-block; background: #667eea; color: white; padding: 12px 30px; border-radius: 8px; text-decoration: none; margin: 10px 5px; }
        .btn:hover { background: #5568d3; }
        .btn-success { background: #28a745; }
        .btn-success:hover { background: #218838; }
    </style>
</head>
<body>
<div class='container'>";

echo "<h1>🔍 التحقق من جداول اختبار البشرة</h1>";

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    if (!$conn) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    echo "<div class='status success'>✅ تم الاتصال بقاعدة البيانات بنجاح</div>";
    
    // التحقق من الجداول
    $tables = ['skin_quiz_results', 'skin_quiz_questions'];
    $tablesStatus = [];
    
    foreach ($tables as $table) {
        $stmt = $conn->query("SHOW TABLES LIKE '{$table}'");
        $exists = $stmt->rowCount() > 0;
        
        $tablesStatus[$table] = [
            'exists' => $exists,
            'count' => 0,
            'structure' => []
        ];
        
        if ($exists) {
            // عد الصفوف
            $countStmt = $conn->query("SELECT COUNT(*) as count FROM {$table}");
            $tablesStatus[$table]['count'] = $countStmt->fetch(PDO::FETCH_ASSOC)['count'];
            
            // الحصول على بنية الجدول
            $structStmt = $conn->query("DESCRIBE {$table}");
            $tablesStatus[$table]['structure'] = $structStmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
    
    // عرض النتائج
    echo "<h2>📊 حالة الجداول</h2>";
    
    $allTablesExist = true;
    foreach ($tablesStatus as $tableName => $status) {
        if ($status['exists']) {
            echo "<div class='status success'>";
            echo "<strong>✅ جدول {$tableName}</strong><br>";
            echo "عدد الصفوف: <strong>{$status['count']}</strong><br>";
            echo "عدد الأعمدة: <strong>" . count($status['structure']) . "</strong>";
            echo "</div>";
            
            // عرض بنية الجدول
            echo "<details style='margin: 10px 0 20px 0;'>";
            echo "<summary style='cursor: pointer; padding: 10px; background: #f8f9fa; border-radius: 5px;'>عرض بنية الجدول</summary>";
            echo "<table>";
            echo "<tr><th>اسم العمود</th><th>النوع</th><th>Null</th><th>Key</th><th>Default</th></tr>";
            foreach ($status['structure'] as $column) {
                echo "<tr>";
                echo "<td>{$column['Field']}</td>";
                echo "<td>{$column['Type']}</td>";
                echo "<td>{$column['Null']}</td>";
                echo "<td>{$column['Key']}</td>";
                echo "<td>" . ($column['Default'] ?? 'NULL') . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            echo "</details>";
        } else {
            echo "<div class='status error'>";
            echo "<strong>❌ جدول {$tableName} غير موجود</strong>";
            echo "</div>";
            $allTablesExist = false;
        }
    }
    
    // عرض بيانات الأسئلة إذا كانت موجودة
    if ($tablesStatus['skin_quiz_questions']['exists'] && $tablesStatus['skin_quiz_questions']['count'] > 0) {
        echo "<h2>📝 الأسئلة المتاحة</h2>";
        
        $questionsStmt = $conn->query("
            SELECT 
                category,
                COUNT(*) as count,
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_count
            FROM skin_quiz_questions
            GROUP BY category
            ORDER BY order_position
        ");
        $categories = $questionsStmt->fetchAll(PDO::FETCH_ASSOC);
        
        $categoryNames = [
            'skin_type' => 'نوع البشرة',
            'concerns' => 'المشاكل',
            'routine' => 'الروتين',
            'lifestyle' => 'نمط الحياة',
            'goals' => 'الأهداف'
        ];
        
        echo "<table>";
        echo "<tr><th>الفئة</th><th>عدد الأسئلة</th><th>النشطة</th></tr>";
        $totalQuestions = 0;
        $totalActive = 0;
        foreach ($categories as $cat) {
            $catName = $categoryNames[$cat['category']] ?? $cat['category'];
            echo "<tr>";
            echo "<td>{$catName}</td>";
            echo "<td>{$cat['count']}</td>";
            echo "<td>{$cat['active_count']}</td>";
            echo "</tr>";
            $totalQuestions += $cat['count'];
            $totalActive += $cat['active_count'];
        }
        echo "<tr style='background: #f8f9fa; font-weight: bold;'>";
        echo "<td>الإجمالي</td>";
        echo "<td>{$totalQuestions}</td>";
        echo "<td>{$totalActive}</td>";
        echo "</tr>";
        echo "</table>";
        
        echo "<div class='status info'>";
        echo "📌 يوجد <strong>{$totalActive}</strong> سؤال نشط جاهز للاستخدام";
        echo "</div>";
    }
    
    // عرض إحصائيات النتائج إذا كانت موجودة
    if ($tablesStatus['skin_quiz_results']['exists'] && $tablesStatus['skin_quiz_results']['count'] > 0) {
        echo "<h2>📈 إحصائيات النتائج</h2>";
        
        $statsStmt = $conn->query("
            SELECT 
                skin_type,
                COUNT(*) as count,
                AVG(score) as avg_score
            FROM skin_quiz_results
            GROUP BY skin_type
            ORDER BY count DESC
        ");
        $stats = $statsStmt->fetchAll(PDO::FETCH_ASSOC);
        
        $skinTypeNames = [
            'oily' => 'دهنية',
            'dry' => 'جافة',
            'combination' => 'مختلطة',
            'normal' => 'عادية',
            'sensitive' => 'حساسة'
        ];
        
        echo "<table>";
        echo "<tr><th>نوع البشرة</th><th>عدد النتائج</th><th>متوسط النتيجة</th></tr>";
        foreach ($stats as $stat) {
            $typeName = $skinTypeNames[$stat['skin_type']] ?? $stat['skin_type'];
            echo "<tr>";
            echo "<td>{$typeName}</td>";
            echo "<td>{$stat['count']}</td>";
            echo "<td>" . round($stat['avg_score'], 1) . "/100</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
    // الإجراءات المقترحة
    echo "<h2>🎯 الإجراءات</h2>";
    
    if ($allTablesExist) {
        echo "<div class='status success'>";
        echo "<strong>✅ جميع الجداول موجودة وجاهزة للاستخدام!</strong>";
        echo "</div>";
        
        echo "<div style='text-align: center; margin-top: 30px;'>";
        echo "<a href='../public/skin-quiz.php' class='btn btn-success'>🧪 تجربة الاختبار</a>";
        echo "<a href='../admin/skin-quiz/index.php' class='btn'>📊 لوحة التحكم</a>";
        echo "</div>";
    } else {
        echo "<div class='status warning'>";
        echo "<strong>⚠️ بعض الجداول غير موجودة</strong><br>";
        echo "يجب تنفيذ سكريبت الإعداد لإنشاء الجداول";
        echo "</div>";
        
        echo "<div style='text-align: center; margin-top: 30px;'>";
        echo "<a href='run_skin_quiz_setup.php' class='btn btn-success'>▶️ تنفيذ سكريبت الإعداد</a>";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<div class='status error'>";
    echo "<h3>❌ حدث خطأ</h3>";
    echo "<p>" . $e->getMessage() . "</p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
    echo "</div>";
}

echo "</div>
</body>
</html>";
?>
