<?php
session_start();
if(isset($_SESSION['teacher'])){
$username = $_SESSION['teacher'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php include '../admin/includes/styles.php'; ?>
    <title> Manage CBT Question |    <?php echo $school_name; ?> </title>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php
    include "includes/sidebar.php";
    $sql = "SELECT * FROM teachers WHERE username =:username";
    $conn->query($sql);
    $conn->bind(":username", $username);

    $result = $conn->fetchSingle();
    $teacher_name = $result->name;

      //fetch teacher section details 
      $sql = 'SELECT * FROM sections WHERE teacher_name =:teacher_name'; 
      $conn->query($sql);
      $conn->bind(":teacher_name", $teacher_name);
      $result_details = $conn->fetchSingle();
  
      $class_id = $result_details->class;
      $section_name = $result_details->name;
      $section_id = $result_details->id;
    ?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">Manage CBT questions </h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url(); ?>">Home</a></li>
                            <li class="breadcrumb-item active">Manage CBT questions</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
            <div class="row">
          <section class="col-lg-12 connectedSortable">
           <a href="<?php echo $conn->teacher_url();?>add_question"><button class="btn btn-outline-success">Add question</button></a>
          </section>
       
          <section class="col-lg-12 connectedSortable">
              <?php
              // Fetch exams for filtering
              $conn->query("SELECT id, title FROM cbt_exams WHERE class_id =:class AND section_id =:section_id");
              $conn->bind(':class', $class_id);
              $conn->bind(':section_id', $section_id);

              $exams = $conn->fetchMultiple();

              // Fetch questions based on selected exam
              $exam_id = $_GET['exam_id'] ?? '';
              $whereClause = "WHERE class_id =:class AND section_id =:section_id";
              if (!empty($exam_id)) {
                  $whereClause = "WHERE q.exam_id = :exam_id";
              }

              $sql = "SELECT q.id, q.question_text, q.question_type, q.exam_id, e.title as exam_title 
                        FROM cbt_questions q 
                        JOIN cbt_exams e ON q.exam_id = e.id 
                        $whereClause ORDER BY q.id DESC";
              $conn->query($sql);
              if (!empty($exam_id)) {
                  $conn->bind(':exam_id', $exam_id);
              }else{
                $conn->bind(':class', $class_id);
                $conn->bind(':section_id', $section_id);
              }
             
              $questions = $conn->fetchMultiple();
              ?>
              <div class="card">
                  <div class="card-header">
                      <h3 class="card-title"> Manage Exam Lists </h3>
                  </div>
                  <!-- /.card-header -->
                  <div class="card-body">
                      <div class="mb-3">
                          <label for="examFilter" class="form-label">Filter by Exam:</label>
                          <select id="examFilter" class="form-control">
                              <option value="">All Exams</option>
                              <?php foreach ($exams as $exam): ?>
                                  <option value="<?php echo $exam->id; ?>" <?php echo ($exam_id == $exam->id) ? 'selected' : ''; ?>>
                                      <?php echo htmlspecialchars($exam->title); ?>
                                  </option>
                              <?php endforeach; ?>
                          </select>
                      </div>
                      <table id="teacher" class="table table-bordered table-striped">
                          <thead>
                          <tr>
                              <th>ID</th>
                              <th>Exam</th>
                              <th>Question</th>
                              <th>Type</th>
                              <th>Actions</th>
                          </tr>
                          </thead>
                          <tbody>
                          <?php if (!empty($questions)): ?>
                              <?php foreach ($questions as $question): ?>
                                  <tr>
                                      <td><?php echo $question->id; ?></td>
                                      <td><?php echo htmlspecialchars($question->exam_title); ?></td>
                                      <td><?php echo htmlspecialchars($question->question_text); ?></td>
                                      <td><?php echo ucfirst(str_replace('_', ' ', $question->question_type)); ?></td>
                                      <td>
                                          <a style="background: none; border: none; display: inline-block; padding: 0;" href="<?php echo $conn->teacher_url();?>edit_question.php?id=<?php echo $question->id; ?>" class="btn btn-sm btn-primary" data-toggle="tooltip" title="Edit"><i class="fa fa-edit"></i></a>
                                          <button style="background: none; border: none; display: inline-block; padding: 0;" class="btn btn-sm btn-danger delete-question" data-id="<?php echo $question->id; ?>" data-toggle="tooltip" title="Delete"><i class="fa fa-trash"></i></button>
                                      </td>
                                  </tr>
                              <?php endforeach; ?>
                          <?php else: ?>
                              <tr><td colspan="5" class="text-center">No questions found.</td></tr>
                          <?php endif; ?>
                          </tbody>
                      </table>
                  </div>
                  <!-- /.card-body -->
              </div>


          </section>
        </div>

        
                
                <!-- /.container-fluid -->
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "../admin/includes/footer.php";?>

    <script>
        $(function () {
            $("#teacher").DataTable({
                "responsive": true, "lengthChange": false, "autoWidth": false,
                "buttons": ["copy", "csv", "pdf", "print"]
            }).buttons().container().appendTo('#teacher_wrapper .col-md-6:eq(0)');
            $('#example2').DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true
            });
        });

        $(document).ready(function(){
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>


    <script>
        $(document).ready(function() {
            $('#examFilter').change(function() {
                let examId = $(this).val();
                window.location.href = 'manage_questions.php' + (examId ? '?exam_id=' + examId : '');
            });

            $('.delete-question').click(function() {
                let questionId = $(this).data('id');
                if (confirm('Are you sure you want to delete this question?')) {
                    $.ajax({
                        url: 'delete_question.php',
                        type: 'POST',
                        data: { id: questionId },
                        success: function(response) {
                            let result = JSON.parse(response);
                            if (result.status === 'success') {
                                alert('Question deleted successfully!');
                                location.reload();
                            } else {
                                alert('Error: ' + result.message);
                            }
                        }
                    });
                }
            });
        });
    </script>



    <?php
    }else{
    ?>
    <!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, maximum-scale=1, shrink-to-fit=no">

        <?php include '../admin/includes/styles.php'; ?>
        <title>Login to continue |    <?php echo $school_name; ?></title>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6> You need to login to continue </h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $teacher_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

    ?>
