<?php
include 'db.php';

// Fetch categories for dropdown
$categories = $pdo->query("SELECT * FROM categories ORDER BY name")->fetchAll();

// Handle updating correct option
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_correct_option'])) {
    $question_id = $_POST['question_id'];
    $new_correct_option_id = $_POST['correct_option_id'];

    // Start a transaction to ensure atomic updates
    $pdo->beginTransaction();
    try {
        // Reset all options for this question to not correct
        $stmt = $pdo->prepare("UPDATE options SET is_correct = 0 WHERE question_id = ?");
        $stmt->execute([$question_id]);

        // Set the selected option as correct
        $stmt = $pdo->prepare("UPDATE options SET is_correct = 1 WHERE id = ? AND question_id = ?");
        $stmt->execute([$new_correct_option_id, $question_id]);

        $pdo->commit();
        echo '<div class="alert alert-success" role="alert">Correct option updated successfully!</div>';
    } catch (Exception $e) {
        $pdo->rollBack();
        echo '<div class="alert alert-danger" role="alert">Error updating correct option: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="Responsive Admin & Dashboard Template based on Bootstrap 5">
    <meta name="author" content="AdminKit">
    <meta name="keywords" content="adminkit, bootstrap, bootstrap 5, admin, dashboard, template, responsive, css, sass, html, theme, front-end, ui kit, web">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="shortcut icon" href="img/icons/icon-48x48.png" />
    <link rel="canonical" href="https://demo-basic.adminkit.io/" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <title>kijani quizes</title>
    <link href="css/app.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap" rel="stylesheet">

    <style>
        .chart-container {
            max-width: 600px;
            margin: auto;
            margin-bottom: 50px;
            height: 400px;
        }
        .correct-option-select {
            width: 200px;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <nav id="sidebar" class="sidebar js-sidebar">
            <div class="sidebar-content js-simplebar">
                <a class="sidebar-brand" href="index.php">
                    <span class="align-middle">Kijani Admin</span>
                </a>
                <ul class="sidebar-nav">
                    <li class="sidebar-header">Pages</li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="index.php">
                            <i class="align-middle" data-feather="sliders"></i>
                            <span class="align-middle">Dashboard</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="categoriesandtopic.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">add category and topic</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="add_question.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">create questions</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="viewusersscores.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">view quiz Results</span>
                        </a>
                    </li>
                    <li class="sidebar-item active">
                        <a class="sidebar-link" href="all_questions.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">View Questions</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="add_user.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">Add Users</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="viewusers.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">view Users</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="quiz_management.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">Quiz management</span>
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <div class="main">
            <nav class="navbar navbar-expand navbar-light navbar-bg">
                <a class="sidebar-toggle js-sidebar-toggle">
                    <i class="hamburger align-self-center"></i>
                </a>
                <div class="navbar-collapse collapse">
                    <ul class="navbar-nav navbar-align">
                        <li class="nav-item dropdown">
                            <a class="nav-icon dropdown-toggle d-inline-block d-sm-none" href="#" data-bs-toggle="dropdown">
                                <i class="align-middle" data-feather="settings"></i>
                            </a>
                            <a class="nav-link dropdown-toggle d-none d-sm-inline-block" href="#" data-bs-toggle="dropdown">
                                <img src="img/avatars/kijanilogo.png" class="avatar img-fluid rounded me-1" alt=" " />
                                <span class="text-dark">kijani admin</span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-end">
                                <a class="dropdown-item" href="profile.php">
                                    <i class="align-middle me-1" data-feather="user"></i>
                                    Profile
                                </a>
                                <a class="dropdown-item" href="#">
                                    <i class="align-middle me-1" data-feather="pie-chart"></i> Analytics
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="settings.php">
                                    <i class="align-middle me-1" data-feather="settings"></i> Settings & Privacy
                                </a>
                                <a class="dropdown-item" href="#">
                                    <i class="align-middle me-1" data-feather="help-circle"></i> Help Center
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="#">Log out</a>
                            </div>
                        </li>
                    </ul>
                </div>
            </nav>

            <main class="content">
                <div class="container-fluid p-0">
                    <h1 class="h3 mb-3">View Questions</h1>
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" action="">
                                        <div class="form-row">
                                            <div class="form-group col-md-4">
                                                <label for="category">Select Category</label>
                                                <select id="category" name="category_id" class="form-control">
                                                    <option value="">Choose Category</option>
                                                    <?php foreach ($categories as $category): ?>
                                                        <option value="<?= $category['id'] ?>" <?= isset($_GET['category_id']) && $_GET['category_id'] == $category['id'] ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($category['name']) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-4">
                                                <label for="topic">Select Topic</label>
                                                <select id="topic" name="topic_id" class="form-control">
                                                    <option value="">Choose Topic</option>
                                                    <?php
                                                    if (isset($_GET['category_id']) && !empty($_GET['category_id'])) {
                                                        $stmt = $pdo->prepare("SELECT id, name FROM topics WHERE category_id = ? ORDER BY name");
                                                        $stmt->execute([$_GET['category_id']]);
                                                        $topics = $stmt->fetchAll();
                                                        foreach ($topics as $topic) {
                                                            echo '<option value="' . $topic['id'] . '" ' . (isset($_GET['topic_id']) && $_GET['topic_id'] == $topic['id'] ? 'selected' : '') . '>' . htmlspecialchars($topic['name']) . '</option>';
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-2 align-self-end">
                                                <button type="submit" class="btn btn-primary mt-2">Search</button>
                                            </div>
                                        </div>
                                    </form>

                                    <?php
                                    if (isset($_GET['topic_id']) && !empty($_GET['topic_id'])) {
                                        $topic_id = $_GET['topic_id'];

                                        // Fetch questions and their options for the selected topic
                                        $stmt = $pdo->prepare("
                                            SELECT 
                                                q.id AS question_id, 
                                                q.question_text, 
                                                o.id AS option_id, 
                                                o.option_text, 
                                                o.is_correct 
                                            FROM questions q
                                            LEFT JOIN options o ON q.id = o.question_id
                                            WHERE q.topic_id = ?
                                            ORDER BY q.id, o.id
                                        ");
                                        $stmt->execute([$topic_id]);
                                        $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

                                        if (!empty($questions)) {
                                            echo '<table class="table table-bordered table-hover mt-4">';
                                            echo '<thead class="thead-dark">';
                                            echo '<tr>';
                                            echo '<th>Question</th>';
                                            echo '<th>Options</th>';
                                            echo '<th>Correct Answer</th>';
                                            echo '<th>Action</th>';
                                            echo '</tr>';
                                            echo '</thead>';
                                            echo '<tbody>';

                                            $current_question_id = null;
                                            $options = [];
                                            $correct_option = '';

                                            foreach ($questions as $row) {
                                                if ($current_question_id !== $row['question_id']) {
                                                    // Close previous question row
                                                    if ($current_question_id !== null) {
                                                        echo '<td><ul>';
                                                        foreach ($options as $opt) {
                                                            echo '<li>' . htmlspecialchars($opt['option_text']) . '</li>';
                                                        }
                                                        echo '</ul></td>';
                                                        echo '<td>' . htmlspecialchars($correct_option) . '</td>';
                                                        echo '<td>';
                                                        echo '<form method="POST" class="form-inline">';
                                                        echo '<input type="hidden" name="question_id" value="' . $current_question_id . '">';
                                                        echo '<select name="correct_option_id" class="form-control correct-option-select">';
                                                        foreach ($options as $opt) {
                                                            echo '<option value="' . $opt['option_id'] . '" ' . ($opt['is_correct'] ? 'selected' : '') . '>' . htmlspecialchars($opt['option_text']) . '</option>';
                                                        }
                                                        echo '</select>';
                                                        echo '<button type="submit" name="update_correct_option" class="btn btn-primary btn-sm ml-2">Update</button>';
                                                        echo '</form>';
                                                        echo '</td>';
                                                        echo '</tr>';
                                                    }

                                                    // Start new question row
                                                    echo '<tr>';
                                                    echo '<td>' . htmlspecialchars($row['question_text']) . '</td>';
                                                    $current_question_id = $row['question_id'];
                                                    $options = [];
                                                    $correct_option = '';
                                                }

                                                // Collect option data
                                                if ($row['option_id']) {
                                                    $options[] = [
                                                        'option_id' => $row['option_id'],
                                                        'option_text' => $row['option_text'],
                                                        'is_correct' => $row['is_correct']
                                                    ];
                                                    if ($row['is_correct']) {
                                                        $correct_option = $row['option_text'];
                                                    }
                                                }
                                            }

                                            // Close the last question row
                                            if ($current_question_id !== null) {
                                                echo '<td><ul>';
                                                foreach ($options as $opt) {
                                                    echo '<li>' . htmlspecialchars($opt['option_text']) . '</li>';
                                                }
                                                echo '</ul></td>';
                                                echo '<td>' . htmlspecialchars($correct_option) . '</td>';
                                                echo '<td>';
                                                echo '<form method="POST" class="form-inline">';
                                                echo '<input type="hidden" name="question_id" value="' . $current_question_id . '">';
                                                echo '<select name="correct_option_id" class="form-control correct-option-select">';
                                                foreach ($options as $opt) {
                                                    echo '<option value="' . $opt['option_id'] . '" ' . ($opt['is_correct'] ? 'selected' : '') . '>' . htmlspecialchars($opt['option_text']) . '</option>';
                                                }
                                                echo '</select>';
                                                echo '<button type="submit" name="update_correct_option" class="btn btn-primary btn-sm ml-2">Update</button>';
                                                echo '</form>';
                                                echo '</td>';
                                                echo '</tr>';
                                            }

                                            echo '</tbody>';
                                            echo '</table>';
                                        } else {
                                            echo '<div class="alert alert-warning mt-4">No questions found for the selected topic.</div>';
                                        }
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script>
        // Load topics based on selected category using AJAX
        document.getElementById('category').addEventListener('change', function() {
            var categoryId = this.value;
            var topicSelect = document.getElementById('topic');
            topicSelect.innerHTML = '<option value="">Loading...</option>';

            if (categoryId) {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', 'get_topics.php?category_id=' + categoryId, true);
                xhr.onload = function() {
                    if (this.status === 200) {
                        topicSelect.innerHTML = this.responseText;
                    } else {
                        topicSelect.innerHTML = '<option value="">Choose Topic</option>';
                    }
                };
                xhr.send();
            } else {
                topicSelect.innerHTML = '<option value="">Choose Topic</option>';
            }
        });
    </script>
</body>
</html>