<?php
include 'includes/header.php';
require_once 'db/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "<div class='alert alert-danger'>Invalid request method. Please submit the quiz.</div>";
    include 'includes/footer.php';
    exit;
}

$user_name = isset($_POST['user_name']) ? htmlspecialchars($_POST['user_name']) : 'Guest';

$scores = [
    'v' => 0, // Visual
    'a' => 0, // Auditory
    'r' => 0, // Read/Write
    'k' => 0, // Kinesthetic
];

// Loop through 20 questions
for ($i = 0; $i < 20; $i++) {
    if (isset($_POST['q' . $i])) {
        $answer = $_POST['q' . $i];
        if (array_key_exists($answer, $scores)) {
            $scores[$answer]++;
        }
    }
}

// Find the primary learning style
arsort($scores); // Sort scores in descending order
$primary_style_key = key($scores);

$styles_info = [
    'v' => ['name' => 'Visual', 'icon' => 'bi-eye-fill'],
    'a' => ['name' => 'Auditory', 'icon' => 'bi-ear-fill'],
    'r' => ['name' => 'Read/Write', 'icon' => 'bi-pencil-fill'],
    'k' => ['name' => 'Kinesthetic', 'icon' => 'bi-hand-index-thumb-fill'],
];

$primary_style_name = $styles_info[$primary_style_key]['name'];
$primary_style_icon = $styles_info[$primary_style_key]['icon'];

// --- Store results in the database ---
try {
    $pdo = db();
    $stmt = $pdo->prepare("INSERT INTO quiz_attempts (v_score, a_score, r_score, k_score, primary_style) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$scores['v'], $scores['a'], $scores['r'], $scores['k'], $primary_style_key]);
} catch (PDOException $e) {
    // For development, you might want to log the error.
    // For production, you could show a generic error message.
    error_log("Database error: " . $e->getMessage());
}

?>

<div class="container mt-5">
    <div class="card shadow-sm p-4 p-md-5 mx-auto" style="max-width: 800px;">
        <div class="text-center">
            <i class="<?php echo $primary_style_icon; ?> text-primary" style="font-size: 4rem;"></i>
            <h2 class="mt-3">Your Primary Learning Style is:</h2>
            <h1 class="display-3 fw-bold text-primary"><?php echo $primary_style_name; ?></h1>
            <p class="mt-4 fs-5">This suggests you learn best when you can see information. Look for diagrams, videos, and charts to help you study.</p>
        </div>

        <hr class="my-5">

        <h4 class="mb-4 text-center">Your Score Breakdown</h4>
        <div class="px-lg-5">
            <?php
            $max_score = max($scores) > 0 ? max($scores) : 1; // Avoid division by zero
            foreach ($scores as $key => $score):
                $percentage = ($score / 20) * 100;
            ?>
            <div class="mb-3">
                <div class="d-flex justify-content-between">
                    <span><?php echo $styles_info[$key]['name']; ?></span>
                    <span><?php echo $score; ?> / 20</span>
                </div>
                <div class="progress" style="height: 25px;">
                    <div class="progress-bar" role="progressbar" style="width: <?php echo $percentage; ?>%;" aria-valuenow="<?php echo $percentage; ?>" aria-valuemin="0" aria-valuemax="100"><?php echo round($percentage); ?>%</div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <hr class="my-5">

        <h4 class="mb-4 text-center">Recommended Tools</h4>
        <div class="px-lg-5">
            <?php
            $tools = [
                'Visual' => [
                    'Canva' => 'Create diagrams and infographics to visualize concepts.',
                    'MindMeister' => 'Build mind maps to connect ideas and see the big picture.',
                    'Draw.io' => 'Free tool for creating flowcharts, diagrams, and network charts.',
                ],
                'Auditory' => [
                    'Spotify (for podcasts)' => 'Listen to educational podcasts to learn on the go.',
                    'Audible' => 'Use audiobooks to absorb content without reading.',
                    'Google Podcasts' => 'Discover and listen to lectures and talks on various subjects.',
                ],
                'Read/Write' => [
                    'Notion' => 'Organize notes, create summaries, and build a personal knowledge base.',
                    'Evernote' => 'Capture and organize notes, articles, and documents in one place.',
                    'Google Docs' => 'Write, edit, and collaborate on notes and essays.',
                ],
                'Kinesthetic' => [
                    'Google Colab' => 'Write and execute Python code to experiment with data and algorithms.',
                    'Tinkercad' => 'Design and build 3D models to understand spatial concepts.',
                    'PhET Simulations' => 'Engage with interactive simulations for science and math.',
                ],
            ];
            $recommended_tools = $tools[$primary_style_name] ?? [];
            ?>
            <ul class="list-group">
                <?php foreach ($recommended_tools as $tool => $description): ?>
                    <li class="list-group-item">
                        <strong><?php echo $tool; ?>:</strong>
                        <?php echo $description; ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>

        <hr class="my-5">

        <h4 class="mb-4 text-center">Personalized Study Time Allocation (60-Min Model)</h4>
        <div class="px-lg-5">
            <?php
            $study_plans = [
                'Visual' => [
                    ['Activity' => 'Watch educational videos/documentaries', 'Time' => '20 mins'],
                    ['Activity' => 'Create mind maps and diagrams', 'Time' => '15 mins'],
                    ['Activity' => 'Use color-coded notes', 'Time' => '15 mins'],
                    ['Activity' => 'Review and summarize', 'Time' => '10 mins'],
                ],
                'Auditory' => [
                    ['Activity' => 'Listen to a podcast or lecture recording', 'Time' => '20 mins'],
                    ['Activity' => 'Discuss concepts with a study partner', 'Time' => '20 mins'],
                    ['Activity' => 'Read notes aloud', 'Time' => '10 mins'],
                    ['Activity' => 'Summarize key points verbally', 'Time' => '10 mins'],
                ],
                'Read/Write' => [
                    ['Activity' => 'Read a chapter or article', 'Time' => '20 mins'],
                    ['Activity' => 'Write a summary of what you read', 'Time' => '20 mins'],
                    ['Activity' => 'Create outlines and lists', 'Time' => '10 mins'],
                    ['Activity' => 'Review and rewrite notes', 'Time' => '10 mins'],
                ],
                'Kinesthetic' => [
                    ['Activity' => 'Engage in a hands-on activity or simulation', 'Time' => '25 mins'],
                    ['Activity' => 'Take short, active breaks', 'Time' => '5 mins'],
                    ['Activity' => 'Use flashcards and manipulate them', 'Time' => '20 mins'],
                    ['Activity' => 'Apply concepts to a real-world problem', 'Time' => '10 mins'],
                ],
            ];
            $study_plan = $study_plans[$primary_style_name] ?? [];
            ?>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Activity</th>
                        <th>Time</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($study_plan as $item): ?>
                        <tr>
                            <td><?php echo $item['Activity']; ?></td>
                            <td><?php echo $item['Time']; ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <hr class="my-5">

        <h4 class="mb-4 text-center">Stability Score</h4>
        <div class="px-lg-5 text-center">
            <?php
            // --- Stability Score Calculation ---
            $sorted_scores = $scores;
            arsort($sorted_scores);
            $primary_score = reset($sorted_scores);
            $secondary_score = next($sorted_scores);

            // Calculate the difference and normalize it.
            // A larger difference means a more pronounced primary style.
            $difference = $primary_score - $secondary_score;
            // Normalize to a scale of 0-10. Max possible difference is 20.
            $stability_score = round(($difference / 20) * 10);
            
            $stability_messages = [
                'high' => 'You have a strong and consistent learning preference. This clear focus can make it easier to find effective study strategies.',
                'medium' => 'You have a primary learning style, but you also show tendencies in other areas. This flexibility can be an advantage.',
                'low' => 'You are a versatile learner with a balanced mix of styles. You can adapt to various learning environments, which is a great strength.',
            ];

            if ($stability_score >= 7) {
                $stability_level = 'high';
                $stability_message = $stability_messages['high'];
            } elseif ($stability_score >= 4) {
                $stability_level = 'medium';
                $stability_message = $stability_messages['medium'];
            } else {
                $stability_level = 'low';
                $stability_message = $stability_messages['low'];
            }
            ?>
            <div class="display-4 fw-bold"><?php echo $stability_score; ?>/10</div>
            <p class="fs-5 mt-2"><?php echo $stability_message; ?></p>
        </div>

        <hr class="my-5">

        <div class="text-center">
            <form action="generate-pdf.php" method="post" target="_blank" class="d-inline">
                <input type="hidden" name="user_name" value="<?php echo htmlspecialchars($user_name); ?>">
                <input type="hidden" name="primary_style_name" value="<?php echo htmlspecialchars($primary_style_name); ?>">
                <input type="hidden" name="primary_style_icon" value="<?php echo htmlspecialchars($primary_style_icon); ?>">
                <?php foreach ($scores as $key => $score) {
                    echo '<input type="hidden" name="scores[' . $key . ']" value="' . $score . '">';
                } ?>
                <?php foreach ($recommended_tools as $tool => $description) {
                    echo '<input type="hidden" name="tools[' . htmlspecialchars($tool) . ']" value="' . htmlspecialchars($description) . '">';
                } ?>
                <?php foreach ($study_plan as $i => $item) {
                    echo '<input type="hidden" name="study_plan[' . $i . '][Activity]" value="' . htmlspecialchars($item['Activity']) . '">';
                    echo '<input type="hidden" name="study_plan[' . $i . '][Time]" value="' . htmlspecialchars($item['Time']) . '">';
                } ?>
                <button type="submit" class="btn btn-primary btn-lg">Download PDF Report</button>
                <input type="hidden" name="stability_score" value="<?php echo $stability_score; ?>">
                <input type="hidden" name="stability_message" value="<?php echo htmlspecialchars($stability_message); ?>">
            </form>
            <a href="index.php" class="btn btn-secondary btn-lg ms-2">Take Quiz Again</a>
        </div>
    </div>
</div>

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