<?php
include 'config.php';

// Handle new category creation
$category_message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_category'])) {
    $new_category_name = $_POST['new_category_name'];
    if (!empty($new_category_name)) {
        $sql = "INSERT INTO categories (category_name) VALUES (?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $new_category_name);
        if ($stmt->execute()) {
            $category_message = "New category created successfully";
            header("Location: " . $_SERVER['PHP_SELF'] . "?message=" . urlencode($category_message) . "&status=success");
            exit();
        } else {
            $category_message = "Error: " . $stmt->error;
            header("Location: " . $_SERVER['PHP_SELF'] . "?message=" . urlencode($category_message) . "&status=error");
            exit();
        }
        $stmt->close();
    } else {
        $category_message = "Category name cannot be empty";
        header("Location: " . $_SERVER['PHP_SELF'] . "?message=" . urlencode($category_message) . "&status=error");
        exit();
    }
}

// Fetch categories
$sql_categories = "SELECT category_id, category_name FROM categories";
$result_categories = $conn->query($sql_categories);
$categories = [];
while ($row = $result_categories->fetch_assoc()) {
    $categories[] = $row;
}

$topic_message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_topic'])) {
    $new_topic_name = $_POST['new_topic_name'];
    $category_id = $_POST['category_id'];
    if (!empty($new_topic_name) && !empty($category_id)) {
        $sql = "INSERT INTO topics (topic_name, category_id) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $new_topic_name, $category_id);
        if ($stmt->execute()) {
            $topic_message = "New topic created successfully";
            header("Location: " . $_SERVER['PHP_SELF'] . "?message=" . urlencode($topic_message) . "&status=success");
            exit();
        } else {
            $topic_message = "Error: " . $stmt->error;
            header("Location: " . $_SERVER['PHP_SELF'] . "?message=" . urlencode($topic_message) . "&status=error");
            exit();
        }
        $stmt->close();
    } else {
        $topic_message = "Topic name and category cannot be empty";
        header("Location: " . $_SERVER['PHP_SELF'] . "?message=" . urlencode($topic_message) . "&status=error");
        exit();
    }
}

// Fetch topics
$sql_topics = "SELECT topic_id, topic_name, category_id FROM topics";
$result_topics = $conn->query($sql_topics);
$topics = [];
while ($row = $result_topics->fetch_assoc()) {
    $topics[] = $row;
}

// Show message if available
if (isset($_GET['message']) && isset($_GET['status'])) {
    $message = $_GET['message'];
    $status = $_GET['status'];
    echo "<script>alert('$message');</script>";
}

// Handle question creation
$question_message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_question'])) {
    $question_text = $_POST['question_text'];
    $options = $_POST['options'];
    $correct_option = $_POST['correct_option'];
    $topic_id = $_POST['topic_id'];

    if (!empty($question_text) && !empty($options) && isset($correct_option) && !empty($topic_id)) {
        $sql = "INSERT INTO questions (question_text, topic_id) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $question_text, $topic_id);

        if ($stmt->execute()) {
            $question_id = $stmt->insert_id;

            foreach ($options as $key => $option_text) {
                $is_correct = ($key == $correct_option) ? 1 : 0;
                $sql = "INSERT INTO options (question_id, option_text, is_correct) VALUES (?, ?, ?)";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("isi", $question_id, $option_text, $is_correct);
                $stmt->execute();
            }

            $question_message = "<script>alert('New question and options created successfully');</script>";
        } else {
            $question_message = "<script>alert('Error: " . $stmt->error . "');</script>";
        }

        $stmt->close();
    } else {
        $question_message = "<script>alert('All fields are required');</script>";
    }
}


$conn->close();
?>


<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">
    <title>Create Question</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function () {
            const topics = <?= json_encode($topics); ?>;
            $('#category_id_question').change(function () {
                const categoryId = $(this).val();
                const filteredTopics = topics.filter(topic => topic.category_id == categoryId);
                $('#topic_id').empty().append('<option value="">Select Topic</option>');
                filteredTopics.forEach(topic => {
                    $('#topic_id').append(`<option value="${topic.topic_id}">${topic.topic_name}</option>`);
                });
            });
        });
    </script>
    <script src="https://unpkg.com/@dotlottie/player-component@latest/dist/dotlottie-player.mjs" type="module"></script>
    <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 &amp; 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 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">
    <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>
        @keyframes spin {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }

        .fa-spin {
            animation: spin 2s infinite linear;
        }
    </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 active">
                        <a class="sidebar-link" href="create_questions.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="view_results.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">view quiz Results</span>
                        </a>
                    </li>
                    
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="edit_questions.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">Edit Quiz</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="users.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">Users</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="bulk_upload.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">Bulk upload</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/avatar.jpg" class="avatar img-fluid rounded me-1"
                                    alt="Charles Hall" /> <span class="text-dark">user</span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-end">
                                <a class="dropdown-item" href="pages-profile.html"><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="index.html"><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">

				

                    <div class="row">
                        <div class="col-xl-12  col-xxl-12 col-md-12 d-flex ">


                            <div class="container-fluid     col-md-12">
                                
							<h1 class="h2 mb-3  card-title "><strong>create quizz</strong><i class="fas fa-question-square"></i>
							</h1>

<div class="card bg-white mb-4 col-md-11 p-1 ml-md-5 mr-md-5">

                                <!-- Create Category Section -->
                               <!-- Button to trigger the New Category modal -->
                                <div class="row justify-content-center">
                                    <div class="col-md-4 p-2 mb-4 ml-1">
<button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#createCategoryModal"><i class="fas fa-folder-plus"></i> Create Category Form
</button>

<!-- Modal structure for Create Category -->
<div class="modal fade" id="createCategoryModal" tabindex="-1" aria-labelledby="createCategoryModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="createCategoryModalLabel">Create New Category</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="card bg-white mb-4 p-1">
          <div class="card-header">
            <div class="container">
              <div class="row align-items-center">
                <div class="col-md-4">
                  <h4 class="card-title mb-0">Category</h4>
                </div>
                 
              </div>
            </div>
          </div>
          <div class="card-body">
            <form method="post" action="">
              <div class="form-group mb-3">
                <label for="new_category_name" class="card-text">New Category Name:</label>
                <input type="text" id="new_category_name" name="new_category_name" class="form-control" required>
              </div>
              <button type="submit" name="create_category" class="btn btn-info">Create Category</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
    </div>
<!-- Include Bootstrap JS and dependencies (Popper.js) if not already included -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js"></script>

      <div class="col-md-6 p-2 mb-4">                      <!-- Button to trigger the Create Topic modal -->
<button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#createTopicModal"><i class="fas fa-pencil"></i>
   Create Topic Form
</button>

<!-- Modal structure for Create Topic -->
<div class="modal fade" id="createTopicModal" tabindex="-1" aria-labelledby="createTopicModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="createTopicModalLabel">Create New Topic</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="card bg-white mb-4 p-2">
          <div class="container">
            <div class="row align-items-center">
              <div class="col-md-4">
                <h4 class="card-title mb-0">Topic</h4>
              </div>
              
            </div>
            <div class="card-body">
              <form method="post" action="">
                <div class="form-group mb-3">
                  <label for="new_topic_name" class="card-text">New Topic Name:</label>
                  <input type="text" id="new_topic_name" name="new_topic_name" class="form-control" required>
                </div>
                <div class="form-group mb-3">
                  <label for="category_id">Select Category:</label>
                  <select id="category_id" name="category_id" class="form-control" required>
                    <option value="">Select Category</option>
                    <?php foreach ($categories as $category): ?>
                      <option value="<?= $category['category_id']; ?>">
                        <?= htmlspecialchars($category['category_name']); ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <button type="submit" name="create_topic" class="btn btn-info">Create Topic</button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div></div>
                    </div>
<!-- Include Bootstrap JS and dependencies (Popper.js) if not already included -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js"></script>
<div>
                    </div>
                    </div>
                                <!-- Create Question Section -->
                                <?= $question_message ?>
                                <div class="card bg-white mb-4 col-md-11 p-1 ml-md-5 mr-md-5">
                                    <div class="card-header">
                                        <div class="container">
                                            <div class="row align-items-center">
                                                <div class="col-md-2">
                                                    <h4 class="card-title mb-0"> Question</h4>
                                                </div>
                                                 
                                            </div>
                                        </div>



                                        <div class="card-body">
                                            <form method="post" action="">
                                                <div class="form-group">
                                                    <label for="question_text">Question:</label>
                                                    <input type="text" id="question_text" name="question_text"
                                                        class="form-control" required>
                                                </div>
                                                <div class="form-group">
                                                    <label for="category_id_question">Select Category:</label>
                                                    <select id="category_id_question" name="category_id_question"
                                                        class="form-control" required>
                                                        <option value="">Select Category</option>
                                                        <?php foreach ($categories as $category): ?>
                                                            <option value="<?= $category['category_id']; ?>">
                                                                <?= htmlspecialchars($category['category_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="form-group">
                                                    <label for="topic_id">Select Topic:</label>
                                                    <select id="topic_id" name="topic_id" class="form-control" required>
                                                        <option value="">Select Topic</option>
                                                    </select>
                                                </div>
                                                <div class="form-group">
                                                    <label>Options:</label>
                                                    <div class="input-group mb-2">
                                                        <input type="text" name="options[]" class="form-control"
                                                            required>
                                                        <div class="input-group-append">
                                                            <div class="input-group-text">
                                                                <input type="radio" name="correct_option" value="0"
                                                                    required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="input-group mb-2">
                                                        <input type="text" name="options[]" class="form-control"
                                                            required>
                                                        <div class="input-group-append">
                                                            <div class="input-group-text">
                                                                <input type="radio" name="correct_option" value="1"
                                                                    required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="input-group mb-2">
                                                        <input type="text" name="options[]" class="form-control"
                                                            required>
                                                        <div class="input-group-append">
                                                            <div class="input-group-text">
                                                                <input type="radio" name="correct_option" value="2"
                                                                    required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="input-group mb-2">
                                                        <input type="text" name="options[]" class="form-control"
                                                            required>
                                                        <div class="input-group-append">
                                                            <div class="input-group-text">
                                                                <input type="radio" name="correct_option" value="3"
                                                                    required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <button type="submit" name="create_question"
                                                    class="btn btn-info">Create
                                                    Question</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>

                                <!--  -->
                            </div>


                        </div>

                         
                    </div>
            </main>

            <footer class="footer">
                <div class="container-fluid">
                    <div class="row text-muted">
                        <div class="col-6 text-start">
                            <p class="mb-0">
                                <a class="text-muted" href="https://adminkit.io/" target="_blank"><strong>kijani
                                        forestry</strong></a> - <a class="text-muted" href="https://adminkit.io/"
                                    target="_blank"><strong>jonathan</strong></a> &copy;
                            </p>
                        </div>
                        <div class="col-6 text-end">
                            <ul class="list-inline">
                                <li class="list-inline-item">
                                    <a class="text-muted" href="https://adminkit.io/" target="_blank">Support</a>
                                </li>
                                <li class="list-inline-item">
                                    <a class="text-muted" href="https://adminkit.io/" target="_blank">Help Center</a>
                                </li>
                                <li class="list-inline-item">
                                    <a class="text-muted" href="https://adminkit.io/" target="_blank">Privacy</a>
                                </li>
                                <li class="list-inline-item">
                                    <a class="text-muted" href="https://adminkit.io/" target="_blank">Terms</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </footer>
        </div>
    </div>

    <script src="js/app.js"></script>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            var ctx = document.getElementById("chartjs-dashboard-line").getContext("2d");
            var gradient = ctx.createLinearGradient(0, 0, 0, 225);
            gradient.addColorStop(0, "rgba(215, 227, 244, 1)");
            gradient.addColorStop(1, "rgba(215, 227, 244, 0)");
            // Line chart
            new Chart(document.getElementById("chartjs-dashboard-line"), {
                type: "line",
                data: {
                    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                    datasets: [{
                        label: "Sales ($)",
                        fill: true,
                        backgroundColor: gradient,
                        borderColor: window.theme.primary,
                        data: [
                            2115,
                            1562,
                            1584,
                            1892,
                            1587,
                            1923,
                            2566,
                            2448,
                            2805,
                            3438,
                            2917,
                            3327
                        ]
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    legend: {
                        display: false
                    },
                    tooltips: {
                        intersect: false
                    },
                    hover: {
                        intersect: true
                    },
                    plugins: {
                        filler: {
                            propagate: false
                        }
                    },
                    scales: {
                        xAxes: [{
                            reverse: true,
                            gridLines: {
                                color: "rgba(0,0,0,0.0)"
                            }
                        }],
                        yAxes: [{
                            ticks: {
                                stepSize: 1000
                            },
                            display: true,
                            borderDash: [3, 3],
                            gridLines: {
                                color: "rgba(0,0,0,0.0)"
                            }
                        }]
                    }
                }
            });
        });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            // Pie chart
            new Chart(document.getElementById("chartjs-dashboard-pie"), {
                type: "pie",
                data: {
                    labels: ["Chrome", "Firefox", "IE"],
                    datasets: [{
                        data: [4306, 3801, 1689],
                        backgroundColor: [
                            window.theme.primary,
                            window.theme.warning,
                            window.theme.danger
                        ],
                        borderWidth: 5
                    }]
                },
                options: {
                    responsive: !window.MSInputMethodContext,
                    maintainAspectRatio: false,
                    legend: {
                        display: false
                    },
                    cutoutPercentage: 75
                }
            });
        });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            // Bar chart
            new Chart(document.getElementById("chartjs-dashboard-bar"), {
                type: "bar",
                data: {
                    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                    datasets: [{
                        label: "This year",
                        backgroundColor: window.theme.primary,
                        borderColor: window.theme.primary,
                        hoverBackgroundColor: window.theme.primary,
                        hoverBorderColor: window.theme.primary,
                        data: [54, 67, 41, 55, 62, 45, 55, 73, 60, 76, 48, 79],
                        barPercentage: .75,
                        categoryPercentage: .5
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    legend: {
                        display: false
                    },
                    scales: {
                        yAxes: [{
                            gridLines: {
                                display: false
                            },
                            stacked: false,
                            ticks: {
                                stepSize: 20
                            }
                        }],
                        xAxes: [{
                            stacked: false,
                            gridLines: {
                                color: "transparent"
                            }
                        }]
                    }
                }
            });
        });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            var markers = [{
                coords: [31.230391, 121.473701],
                name: "Shanghai"
            },
            {
                coords: [28.704060, 77.102493],
                name: "Delhi"
            },
            {
                coords: [6.524379, 3.379206],
                name: "Lagos"
            },
            {
                coords: [35.689487, 139.691711],
                name: "Tokyo"
            },
            {
                coords: [23.129110, 113.264381],
                name: "Guangzhou"
            },
            {
                coords: [40.7127837, -74.0059413],
                name: "New York"
            },
            {
                coords: [34.052235, -118.243683],
                name: "Los Angeles"
            },
            {
                coords: [41.878113, -87.629799],
                name: "Chicago"
            },
            {
                coords: [51.507351, -0.127758],
                name: "London"
            },
            {
                coords: [40.416775, -3.703790],
                name: "Madrid "
            }
            ];
            var map = new jsVectorMap({
                map: "world",
                selector: "#world_map",
                zoomButtons: true,
                markers: markers,
                markerStyle: {
                    initial: {
                        r: 9,
                        strokeWidth: 7,
                        stokeOpacity: .4,
                        fill: window.theme.primary
                    },
                    hover: {
                        fill: window.theme.primary,
                        stroke: window.theme.primary
                    }
                },
                zoomOnScroll: false
            });
            window.addEventListener("resize", () => {
                map.updateSize();
            });
        });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            var date = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000);
            var defaultDate = date.getUTCFullYear() + "-" + (date.getUTCMonth() + 1) + "-" + date.getUTCDate();
            document.getElementById("datetimepicker-dashboard").flatpickr({
                inline: true,
                prevArrow: "<span title=\"Previous month\">&laquo;</span>",
                nextArrow: "<span title=\"Next month\">&raquo;</span>",
                defaultDate: defaultDate
            });
        });
    </script>

</body>

</html>