<?php
session_start();
require_once '../config/database.php';

$database = new Database();
$conn = $database->getConnection();

// جلب الأسئلة النشطة
$stmt = $conn->query("SELECT * FROM skin_quiz_questions WHERE is_active = 1 ORDER BY order_position ASC");
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// جلب عدد من أجرى الاختبار
$count_stmt = $conn->query("SELECT COUNT(*) as total FROM skin_quiz_results");
$total_users = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#667eea">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>اختبار روتين البشرة المثالي - Roz Skin</title>
    <meta name="description" content="اكتشفي نوع بشرتك واحصلي على توصيات مخصصة لروتين العناية المثالي">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* Skin Quiz - Modern Mobile-First Design */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            font-family: 'Tajawal', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #1a1a2e;
            min-height: 100vh;
            overflow-x: hidden;
            position: relative;
        }

        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
                linear-gradient(135deg, rgba(236, 72, 153, 0.15) 0%, rgba(168, 85, 247, 0.15) 100%),
                url('https://i.pinimg.com/736x/62/83/cc/6283cc73418a5b87dfad4fd56fe2e9f0.jpg');
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            filter: blur(8px);
            z-index: 0;
        }

        body::after {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(26, 26, 46, 0.85);
            z-index: 0;
        }

        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 16px;
            position: relative;
            z-index: 1;
        }

        /* Hero Section */
        .hero-section {
            min-height: 100vh;
            display: flex;
            align-items: center;
            padding: 40px 0;
            position: relative;
            z-index: 1;
        }

        .hero-content {
            text-align: center;
            max-width: 700px;
            margin: 0 auto;
        }

        .badge {
            display: inline-block;
            background: linear-gradient(135deg, rgba(236, 72, 153, 0.25) 0%, rgba(168, 85, 247, 0.25) 100%);
            color: #ffffff;
            padding: 8px 20px;
            border-radius: 50px;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 24px;
            border: 1px solid rgba(236, 72, 153, 0.4);
            backdrop-filter: blur(10px);
        }

        .hero-title {
            font-size: 48px;
            font-weight: 900;
            color: #ffffff;
            margin-bottom: 20px;
            line-height: 1.2;
            text-shadow: 0 4px 20px rgba(236, 72, 153, 0.5);
        }

        .hero-subtitle {
            font-size: 18px;
            color: rgba(255, 255, 255, 0.85);
            line-height: 1.6;
            margin-bottom: 40px;
        }

        .stats {
            display: flex;
            justify-content: center;
            gap: 40px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }

        .stat-item {
            text-align: center;
        }

        .stat-number {
            font-size: 36px;
            font-weight: 900;
            background: linear-gradient(135deg, #ec4899 0%, #a855f7 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 8px;
        }

        .stat-label {
            font-size: 14px;
            color: rgba(255, 255, 255, 0.7);
            font-weight: 600;
        }

        .start-btn {
            background: linear-gradient(135deg, #ec4899 0%, #a855f7 50%, #8b5cf6 100%);
            color: white;
            border: none;
            padding: 18px 48px;
            border-radius: 50px;
            font-size: 18px;
            font-weight: 700;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 12px;
            box-shadow: 0 12px 40px rgba(236, 72, 153, 0.4);
            transition: all 0.3s ease;
            margin-bottom: 32px;
        }

        .start-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 16px 50px rgba(236, 72, 153, 0.5);
        }

        .features {
            display: flex;
            justify-content: center;
            gap: 32px;
            flex-wrap: wrap;
        }

        .feature {
            display: flex;
            align-items: center;
            gap: 8px;
            color: rgba(255, 255, 255, 0.8);
            font-size: 14px;
            font-weight: 600;
        }

        .feature i {
            color: #ec4899;
            font-size: 18px;
        }

        .hero-image {
            position: relative;
            margin-top: 60px;
            height: 200px;
        }

        .floating-card {
            position: absolute;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(20px);
            padding: 16px 24px;
            border-radius: 16px;
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.3);
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
            animation: float 3s ease-in-out infinite;
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
        }

        .floating-card i {
            font-size: 24px;
            color: #ec4899;
        }

        .card-1 {
            top: 0;
            left: 10%;
            animation-delay: 0s;
        }

        .card-2 {
            top: 50px;
            right: 10%;
            animation-delay: 1s;
        }

        .card-3 {
            top: 100px;
            left: 50%;
            transform: translateX(-50%);
            animation-delay: 2s;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-20px); }
        }

        /* Quiz Container */
        .quiz-container {
            min-height: 100vh;
            padding: 40px 0;
            position: relative;
            z-index: 1;
        }

        .quiz-wrapper {
            background: rgba(255, 255, 255, 0.12);
            backdrop-filter: blur(30px);
            border-radius: 24px;
            padding: 32px 24px;
            margin: 0 auto;
            max-width: 700px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        /* Progress Section */
        .progress-section {
            margin-bottom: 32px;
        }

        .progress-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .progress-text {
            font-size: 14px;
            color: rgba(255, 255, 255, 0.8);
            font-weight: 600;
        }

        .progress-percentage {
            font-size: 14px;
            color: #ec4899;
            font-weight: 700;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: rgba(236, 72, 153, 0.2);
            border-radius: 10px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(135deg, #ec4899 0%, #a855f7 50%, #8b5cf6 100%);
            transition: width 0.5s ease;
            border-radius: 10px;
        }

        /* Questions Wrapper */
        .questions-wrapper {
            margin-bottom: 24px;
        }

        /* Question Card */
        .question-card {
            animation: fadeIn 0.5s ease;
        }

        .question-header {
            text-align: center;
            margin-bottom: 32px;
        }

        .question-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }

        .question-title {
            font-size: 24px;
            font-weight: 800;
            color: #ffffff;
            line-height: 1.4;
            margin-bottom: 8px;
        }

        .question-subtitle {
            font-size: 14px;
            color: rgba(255, 255, 255, 0.7);
            margin-top: 8px;
        }

        /* Options Grid */
        .options-grid {
            display: grid;
            gap: 12px;
        }

        .options-grid.multiple {
            grid-template-columns: 1fr;
        }

        .option-card {
            position: relative;
            cursor: pointer;
        }

        .option-card input {
            position: absolute;
            opacity: 0;
            pointer-events: none;
        }

        .option-content {
            background: rgba(255, 255, 255, 0.08);
            border: 2px solid rgba(255, 255, 255, 0.15);
            border-radius: 16px;
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 16px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(10px);
        }

        .option-icon {
            font-size: 32px;
            flex-shrink: 0;
        }

        .option-text {
            flex: 1;
            font-size: 16px;
            font-weight: 600;
            color: rgba(255, 255, 255, 0.9);
            text-align: right;
        }

        .option-check {
            width: 24px;
            height: 24px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            flex-shrink: 0;
        }

        .option-check i {
            font-size: 12px;
            color: white;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .option-card:hover .option-content {
            border-color: #ec4899;
            background: rgba(236, 72, 153, 0.2);
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(236, 72, 153, 0.4);
        }

        .option-card input:checked ~ .option-content {
            border-color: #ec4899;
            background: linear-gradient(135deg, rgba(236, 72, 153, 0.3) 0%, rgba(168, 85, 247, 0.3) 100%);
        }

        .option-card input:checked ~ .option-content .option-text {
            color: #ffffff;
        }

        .option-card input:checked ~ .option-content .option-check {
            background: linear-gradient(135deg, #ec4899 0%, #a855f7 100%);
            border-color: #ec4899;
        }

        .option-card input:checked ~ .option-content .option-check i {
            opacity: 1;
        }

        /* Personal Form */
        .personal-form {
            max-width: 500px;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: rgba(255, 255, 255, 0.9);
            margin-bottom: 8px;
            text-align: right;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 14px 16px;
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: 12px;
            font-size: 16px;
            font-family: 'Tajawal', sans-serif;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.08);
            color: white;
            backdrop-filter: blur(10px);
        }

        .form-group input::placeholder {
            color: rgba(255, 255, 255, 0.5);
        }

        .form-group select option {
            background: #1a1a2e;
            color: white;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #ec4899;
            box-shadow: 0 0 0 3px rgba(236, 72, 153, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .checkbox-group label {
            display: flex;
            align-items: start;
            gap: 12px;
            cursor: pointer;
        }

        .checkbox-group input[type="checkbox"] {
            width: auto;
            margin-top: 4px;
            cursor: pointer;
        }

        .checkbox-group span {
            font-size: 14px;
            color: rgba(255, 255, 255, 0.8);
            line-height: 1.5;
        }

        .checkbox-group a {
            color: #ec4899;
            text-decoration: none;
            font-weight: 600;
        }

        .checkbox-group a:hover {
            text-decoration: underline;
        }

        /* Quiz Navigation */
        .quiz-navigation {
            display: flex;
            gap: 12px;
            margin-top: 32px;
        }

        .nav-btn {
            flex: 1;
            padding: 16px 24px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-family: 'Tajawal', sans-serif;
        }

        .prev-btn {
            background: rgba(255, 255, 255, 0.1);
            color: rgba(255, 255, 255, 0.9);
            border: 2px solid rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(10px);
        }

        .prev-btn:hover {
            background: rgba(255, 255, 255, 0.15);
            border-color: rgba(255, 255, 255, 0.3);
        }

        .next-btn,
        .submit-btn {
            background: linear-gradient(135deg, #ec4899 0%, #a855f7 50%, #8b5cf6 100%);
            color: white;
            box-shadow: 0 8px 24px rgba(236, 72, 153, 0.4);
        }

        .next-btn:hover,
        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 32px rgba(236, 72, 153, 0.5);
        }

        .next-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        /* Loading Overlay */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(10px);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }

        .loading-content {
            text-align: center;
            color: white;
        }

        .loading-spinner {
            width: 64px;
            height: 64px;
            border: 4px solid rgba(255, 255, 255, 0.2);
            border-top-color: #ec4899;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 24px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .loading-content h3 {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .loading-content p {
            font-size: 16px;
            opacity: 0.8;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .hero-title {
                font-size: 36px;
            }
            
            .hero-subtitle {
                font-size: 16px;
            }
            
            .stats {
                gap: 24px;
            }
            
            .stat-number {
                font-size: 28px;
            }
            
            .start-btn {
                padding: 16px 40px;
                font-size: 16px;
            }
            
            .features {
                gap: 20px;
            }
            
            .floating-card {
                padding: 12px 16px;
                font-size: 14px;
            }
            
            .floating-card i {
                font-size: 20px;
            }
            
            .card-1 {
                left: 5%;
            }
            
            .card-2 {
                right: 5%;
            }
        }

        @media (max-width: 640px) {
            .container {
                padding: 0 12px;
            }
            
            .hero-section {
                padding: 20px 0;
            }
            
            .hero-title {
                font-size: 28px;
            }
            
            .hero-subtitle {
                font-size: 15px;
                margin-bottom: 32px;
            }
            
            .stats {
                gap: 20px;
            }
            
            .stat-number {
                font-size: 24px;
            }
            
            .stat-label {
                font-size: 12px;
            }
            
            .start-btn {
                padding: 14px 32px;
                font-size: 15px;
                width: 100%;
                max-width: 300px;
            }
            
            .features {
                flex-direction: column;
                gap: 12px;
            }
            
            .hero-image {
                height: 150px;
                margin-top: 40px;
            }
            
            .floating-card {
                padding: 10px 14px;
                font-size: 12px;
            }
            
            .floating-card i {
                font-size: 18px;
            }
            
            .quiz-container {
                padding: 20px 0;
            }
            
            .quiz-wrapper {
                padding: 24px 16px;
                border-radius: 20px;
                margin: 0 12px;
            }
            
            .question-title {
                font-size: 20px;
            }
            
            .question-icon {
                font-size: 40px;
            }
            
            .option-content {
                padding: 16px;
            }
            
            .option-icon {
                font-size: 28px;
            }
            
            .option-text {
                font-size: 15px;
            }
            
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .nav-btn {
                padding: 14px 20px;
                font-size: 15px;
            }
            
            .quiz-navigation {
                flex-direction: column-reverse;
            }
            
            .prev-btn {
                order: 2;
            }
        }

        /* Animations */
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>

<!-- Hero Section -->
<section class="hero-section">
    <div class="container">
        <div class="hero-content">
            <div class="badge">✨ اختبار مجاني</div>
            <h1 class="hero-title">اكتشفي روتين بشرتك المثالي</h1>
            <p class="hero-subtitle">
                أجيبي على 15 سؤال بسيط واحصلي على تحليل شامل لبشرتك مع توصيات مخصصة من منتجاتنا
            </p>
            
            <div class="stats">
                <div class="stat-item">
                    <div class="stat-number"><?php echo number_format($total_users); ?>+</div>
                    <div class="stat-label">أجرت الاختبار</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">15</div>
                    <div class="stat-label">سؤال فقط</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">3</div>
                    <div class="stat-label">دقائق</div>
                </div>
            </div>
            
            <button onclick="startQuiz()" class="start-btn">
                <span>ابدأي الاختبار الآن</span>
                <i class="fas fa-arrow-left"></i>
            </button>
            
            <div class="features">
                <div class="feature">
                    <i class="fas fa-check-circle"></i>
                    <span>نتيجة فورية</span>
                </div>
                <div class="feature">
                    <i class="fas fa-gift"></i>
                    <span>توصيات مخصصة</span>
                </div>
                <div class="feature">
                    <i class="fas fa-lock"></i>
                    <span>خصوصية تامة</span>
                </div>
            </div>
        </div>
        
        <div class="hero-image">
            <div class="floating-card card-1">
                <i class="fas fa-spa"></i>
                <span>بشرة صحية</span>
            </div>
            <div class="floating-card card-2">
                <i class="fas fa-heart"></i>
                <span>روتين مثالي</span>
            </div>
            <div class="floating-card card-3">
                <i class="fas fa-star"></i>
                <span>نتائج مضمونة</span>
            </div>
        </div>
    </div>
</section>

<!-- Quiz Container (Hidden Initially) -->
<div id="quizContainer" class="quiz-container" style="display: none;">
    <div class="quiz-wrapper">
        <!-- Progress Bar -->
        <div class="progress-section">
            <div class="progress-info">
                <span class="progress-text">السؤال <span id="currentQuestion">1</span> من <span id="totalQuestions"><?php echo count($questions); ?></span></span>
                <span class="progress-percentage" id="progressPercentage">0%</span>
            </div>
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
        </div>
        
        <!-- Questions -->
        <div class="questions-wrapper" id="questionsWrapper">
            <?php foreach ($questions as $index => $question): 
                $options = json_decode($question['options'], true);
            ?>
            <div class="question-card" data-question="<?php echo $index + 1; ?>" style="display: <?php echo $index === 0 ? 'block' : 'none'; ?>">
                <div class="question-header">
                    <?php if ($question['icon']): ?>
                    <div class="question-icon"><?php echo $question['icon']; ?></div>
                    <?php endif; ?>
                    <h2 class="question-title"><?php echo htmlspecialchars($question['question_ar']); ?></h2>
                </div>
                
                <div class="options-grid <?php echo $question['question_type'] === 'multiple' ? 'multiple' : ''; ?>">
                    <?php foreach ($options as $opt_index => $option): ?>
                    <label class="option-card">
                        <input 
                            type="<?php echo $question['question_type'] === 'multiple' ? 'checkbox' : 'radio'; ?>" 
                            name="question_<?php echo $question['id']; ?>" 
                            value="<?php echo htmlspecialchars($option['value']); ?>"
                            data-question-id="<?php echo $question['id']; ?>"
                            data-category="<?php echo $question['category']; ?>"
                            data-score="<?php echo isset($option['score']) ? $option['score'] : 0; ?>"
                        >
                        <div class="option-content">
                            <?php if (isset($option['icon'])): ?>
                            <div class="option-icon"><?php echo $option['icon']; ?></div>
                            <?php endif; ?>
                            <div class="option-text"><?php echo htmlspecialchars($option['label']); ?></div>
                        </div>
                        <div class="option-check">
                            <i class="fas fa-check"></i>
                        </div>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endforeach; ?>
            
            <!-- Personal Info Form -->
            <div class="question-card" id="personalInfoCard" style="display: none;">
                <div class="question-header">
                    <div class="question-icon">👤</div>
                    <h2 class="question-title">معلوماتك الشخصية</h2>
                    <p class="question-subtitle">لنرسل لك النتيجة ونتواصل معك</p>
                </div>
                
                <form id="personalInfoForm" class="personal-form">
                    <div class="form-group">
                        <label>الاسم الكامل *</label>
                        <input type="text" name="name" required placeholder="أدخلي اسمك">
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>العمر *</label>
                            <input type="number" name="age" required min="13" max="100" placeholder="25">
                        </div>
                        
                        <div class="form-group">
                            <label>الجنس *</label>
                            <select name="gender" required>
                                <option value="female">أنثى</option>
                                <option value="male">ذكر</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>البريد الإلكتروني *</label>
                        <input type="email" name="email" required placeholder="example@email.com">
                    </div>
                    
                    <div class="form-group">
                        <label>رقم الهاتف (اختياري)</label>
                        <input type="tel" name="phone" placeholder="01xxxxxxxxx">
                    </div>
                    
                    <div class="form-group checkbox-group">
                        <label>
                            <input type="checkbox" name="agree_terms" required>
                            <span>أوافق على <a href="#">سياسة الخصوصية</a> واستخدام بياناتي للحصول على توصيات مخصصة</span>
                        </label>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Navigation Buttons -->
        <div class="quiz-navigation">
            <button type="button" id="prevBtn" class="nav-btn prev-btn" onclick="previousQuestion()" style="display: none;">
                <i class="fas fa-arrow-right"></i>
                <span>السابق</span>
            </button>
            
            <button type="button" id="nextBtn" class="nav-btn next-btn" onclick="nextQuestion()" disabled>
                <span>التالي</span>
                <i class="fas fa-arrow-left"></i>
            </button>
            
            <button type="button" id="submitBtn" class="nav-btn submit-btn" onclick="submitQuiz()" style="display: none;">
                <span>احصلي على النتيجة</span>
                <i class="fas fa-check"></i>
            </button>
        </div>
    </div>
</div>

<!-- Loading Overlay -->
<div id="loadingOverlay" class="loading-overlay" style="display: none;">
    <div class="loading-content">
        <div class="loading-spinner"></div>
        <h3>جاري تحليل إجاباتك...</h3>
        <p>يرجى الانتظار قليلاً</p>
    </div>
</div>

<script>
const questions = <?php echo json_encode($questions); ?>;
const totalQuestions = questions.length;
let currentQuestionIndex = 0;
let answers = {};

function startQuiz() {
    document.querySelector('.hero-section').style.display = 'none';
    document.getElementById('quizContainer').style.display = 'block';
    updateProgress();
}

function updateProgress() {
    const progress = ((currentQuestionIndex) / (totalQuestions + 1)) * 100;
    document.getElementById('progressFill').style.width = progress + '%';
    document.getElementById('currentQuestion').textContent = currentQuestionIndex + 1;
    document.getElementById('progressPercentage').textContent = Math.round(progress) + '%';
}

function nextQuestion() {
    // Save current answer
    const currentCard = document.querySelector(`.question-card[data-question="${currentQuestionIndex + 1}"]`);
    const currentQuestionId = questions[currentQuestionIndex].id;
    const inputs = currentCard.querySelectorAll('input[type="radio"]:checked, input[type="checkbox"]:checked');
    
    if (inputs.length === 0) {
        alert('الرجاء اختيار إجابة');
        return;
    }
    
    // Save answers
    answers[currentQuestionId] = Array.from(inputs).map(input => ({
        value: input.value,
        category: input.dataset.category,
        score: input.dataset.score
    }));
    
    // Hide current question
    currentCard.style.display = 'none';
    
    // Move to next
    currentQuestionIndex++;
    
    if (currentQuestionIndex < totalQuestions) {
        // Show next question
        document.querySelector(`.question-card[data-question="${currentQuestionIndex + 1}"]`).style.display = 'block';
        document.getElementById('prevBtn').style.display = 'flex';
    } else {
        // Show personal info form
        document.getElementById('personalInfoCard').style.display = 'block';
        document.getElementById('nextBtn').style.display = 'none';
        document.getElementById('submitBtn').style.display = 'flex';
    }
    
    updateProgress();
    
    // Smooth scroll to top with mobile optimization
    const quizContainer = document.getElementById('quizContainer');
    if (quizContainer) {
        quizContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
}

function previousQuestion() {
    if (currentQuestionIndex === 0) return;
    
    // Hide current
    if (currentQuestionIndex < totalQuestions) {
        document.querySelector(`.question-card[data-question="${currentQuestionIndex + 1}"]`).style.display = 'none';
    } else {
        document.getElementById('personalInfoCard').style.display = 'none';
        document.getElementById('nextBtn').style.display = 'flex';
        document.getElementById('submitBtn').style.display = 'none';
    }
    
    // Move back
    currentQuestionIndex--;
    
    // Show previous
    document.querySelector(`.question-card[data-question="${currentQuestionIndex + 1}"]`).style.display = 'block';
    
    if (currentQuestionIndex === 0) {
        document.getElementById('prevBtn').style.display = 'none';
    }
    
    updateProgress();
    
    // Smooth scroll to top
    const quizContainer = document.getElementById('quizContainer');
    if (quizContainer) {
        quizContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
}

// Enable/disable next button based on selection
document.addEventListener('change', function(e) {
    if (e.target.type === 'radio' || e.target.type === 'checkbox') {
        const questionCard = e.target.closest('.question-card');
        if (questionCard && !questionCard.id) {
            const hasSelection = questionCard.querySelector('input:checked');
            document.getElementById('nextBtn').disabled = !hasSelection;
        }
    }
});

async function submitQuiz() {
    const form = document.getElementById('personalInfoForm');
    
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const formData = new FormData(form);
    const personalInfo = Object.fromEntries(formData);
    
    // Show loading
    document.getElementById('loadingOverlay').style.display = 'flex';
    
    // Prepare data
    const quizData = {
        answers: answers,
        personalInfo: personalInfo
    };
    
    try {
        const response = await fetch('../api/skin-quiz-submit.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(quizData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            // Redirect to result page
            window.location.href = 'skin-quiz-result.php?id=' + result.result_id;
        } else {
            alert('حدث خطأ: ' + result.message);
            document.getElementById('loadingOverlay').style.display = 'none';
        }
    } catch (error) {
        console.error('Error:', error);
        alert('حدث خطأ في الاتصال. يرجى المحاولة مرة أخرى.');
        document.getElementById('loadingOverlay').style.display = 'none';
    }
}
</script>

</body>
</html>
