<?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> Exams Lists |  <?php echo $school_name; ?> </title>
    <?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;
    ?>

</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"; ?>

    <!-- 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">Exam Lists</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">Exam Lists</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();?>exam_form"><button class="btn btn-outline-success">Add an exam</button></a>
          </section>
       
          <section class="col-lg-12 connectedSortable">
              <?php
              $sql = "SELECT *  FROM cbt_exams WHERE class_id =:class AND section_id =:section_id ORDER BY id DESC";
              $conn->query($sql);
              $conn->bind(':class', $class_id);
              $conn->bind(':section_id', $section_id);
              $result = $conn->fetchMultiple();
              ?>
              <div class="card">
                  <div class="card-header">
                      <h3 class="card-title"> Manage Exam Lists </h3>
                  </div>
                  <!-- /.card-header -->
                  <div class="card-body">
                      <table id="teacher" class="table table-bordered table-striped">
                          <thead>
                          <tr>
                              <th>Title</th>
                              <th>Exam Code</th>
                              <th>Date</th>
                              <th>Start Time</th>
                              <th>End Time</th>
                              <th>Duration</th>
                              <th>Session</th>
                              <th>Status</th>
                              <th>Actions</th>
                          </tr>
                          </thead>
                          <tbody>
                          <?php
                          $i = 1;
                          if($conn->rowCount()){
                              foreach ($result as $exam):
                                  $exam_id = $exam->id;
                                  $exam_title = $exam->title;
                                  $exam_code = $exam->exam_code;
                                  $exam_date = date('F d, Y', strtotime($exam->exam_date));
                                  $exam_time_start = date('H:i:a', strtotime($exam->time_start));
                                  $exam_time_end = date('H:i:a', strtotime($exam->time_end));
                                  $exam_duration = $exam->duration;
                                  $exam_status = $exam->status;
                                  $academic_session = $exam->academic_session;

                                  $hours = floor($exam_duration / 60);
                                $minutes = $exam_duration % 60;
                                $formatted_duration = '';

                                if ($hours > 0) {
                                    $formatted_duration .= $hours . ' hr' . ($hours > 1 ? 's' : '');
                                }
                                if ($minutes > 0) {
                                    $formatted_duration .= ($hours > 0 ? ' ' : '') . $minutes . ' min' . ($minutes > 1 ? 's' : '');
                                }



                                  ?>
                                  <tr data-id='<?php echo $exam->id; ?>'>
                                      <td><?php echo $exam_title; ?></td>
                                      <td><?php echo $exam_code; ?></td>
                                      <td><?php echo $exam_date; ?></td>
                                      <td><?php echo $exam_time_start; ?></td>
                                      <td><?php echo $exam_time_end; ?></td>
                                      <td><?php echo $formatted_duration ?: '0 min'; ?></td>
                                      <td><?php echo $academic_session; ?></td>
                                      <td><?php echo $exam_status; ?></td>
                                      <td>
                                          <button style="background: none; border: none; display: inline-block; padding: 0;" class='btn btn-info btn-sm editExam' data-toggle="tooltip" title="Edit"><i class="fa fa-edit"></i></button>
                                          <button style="background: none; border: none; display: inline-block; padding: 0;" class='btn btn-danger btn-sm deleteExam' data-toggle="tooltip" title="Delete"><i class="fa fa-trash"></i></button>
                                        
                                      </td>
                                  </tr>

                              <?php endforeach; ?>
                              <?php
                          }else{
                              ?> <tr>
                                  <td colspan="100%" class="text-center">No Exam(s) found!</td>
                              </tr><?php
                          }

                          ?>
                          </tbody>
                      </table>
                  </div>
                  <!-- /.card-body -->
              </div>


          </section>
        </div>

          <div id="show-msg"></div>

        <!-- Modal for Editing Exam -->
<div class="modal" tabindex="-1" id="editModal">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Exam</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editExamForm">
                    <input type="hidden" id="edit_exam_id">

                    <div class="form-group">
                        <label>Title</label>
                        <input type="text" id="edit_title" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Exam Date</label>
                        <input type="date" id="edit_exam_date" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Start Time</label>
                        <input type="time" id="edit_time_start" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>End Time</label>
                        <input type="time" id="edit_time_end" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Class</label>
                        <select id="edit_class_id" class="form-control" required></select>
                    </div>

                    <div class="form-group">
                        <label>Section</label>
                        <select id="edit_section_id" class="form-control" required></select>
                    </div>

                    <div class="form-group">
                        <label>Subject</label>
                        <select id="edit_subject_id" class="form-control" required></select>
                    </div>

                    <div class="form-group">
                        <label>Term</label>
                        <select id="edit_term_id" class="form-control" required></select>
                    </div>

                    <div class="form-group">
                        <label>Status</label>
                        <select id="edit_status" class="form-control">
                            <option value="draft">Draft</option>
                            <option value="published">Published</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-success">Update Exam</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<!-- End edit cbt exams modal -->

          <!-- /.row (main row) -->
      </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() {

            // Populate select options on page load
        function loadDropdowns(selectedClassId, selectedSectionId, selectedSubjectId, selectedTermId) {
            $.get('fetch_dropdowns.php', function(data) {
                const { classes, sections, subjects, terms } = JSON.parse(data);

                $('#edit_class_id').html(classes.map(cls => `<option value="${cls.id}" ${cls.id == selectedClassId ? 'selected' : ''}>${cls.name}</option>`));
                $('#edit_subject_id').html(subjects.map(sub => `<option value="${sub.id}" ${sub.id == selectedSubjectId ? 'selected' : ''}>${sub.subject_name}</option>`));
                $('#edit_term_id').html(terms.map(term => `<option value="${term.id}" ${term.id == selectedTermId ? 'selected' : ''}>${term.name}</option>`));

                // Call section fetch based on selected class
                fetchSections(selectedClassId, selectedSectionId);

                // call subject fetch based  on selected class
                fetchSubjects(selectedClassId, selectedSubjectId);
            });
        }

        function fetchSections(classId, selectedSectionId = null) {
            $.post('fetch_sections_by_class.php', { class_id: classId }, function(data) {
                const sections = JSON.parse(data);
                const sectionOptions = sections.map(sec => `<option value="${sec.id}" ${sec.id == selectedSectionId ? 'selected' : ''}>${sec.name}</option>`);
                $('#edit_section_id').html(sectionOptions);
            });
        }

        function fetchSubjects(classId, selectedSubjectId = null) {
            $.post('fetch_subjects_by_class.php', { class_id: classId }, function(data) {
                const subjects = JSON.parse(data);
                const subjectOptions = subjects.map(sub => `<option value="${sub.id}" ${sub.id == selectedSubjectId ? 'selected' : ''}>${sub.subject_name}</option>`);
                $('#edit_subject_id').html(subjectOptions);
            });
        }

        // When class is changed manually
        $('#edit_class_id').on('change', function() {
            fetchSections(this.value);
            fetchSubjects(this.value);
        });

        // Open Edit Modal
        $('.editExam').click(function() {
            let examId = $(this).closest('tr').data('id');
            $.post('get_exam.php', { id: examId }, function(response) {
                let data = JSON.parse(response);

                $('#edit_exam_id').val(data.id);
                $('#edit_title').val(data.title);
                $('#edit_exam_date').val(data.exam_date);
                $('#edit_time_start').val(data.time_start);
                $('#edit_time_end').val(data.time_end);
                $('#edit_status').val(data.status);

                // Load all dropdowns and preselect values
                loadDropdowns(data.class_id, data.section_id, data.subject_id, data.term_id);

                $('#editModal').modal('show');
            });
        });
          

            // Close modal when clicking the close button
            $('.close, .btn-secondary').click(function() {
                $('#editModal').modal('hide');
            });

            // Submit Edit Form
            $('#editExamForm').submit(function(e) {
                e.preventDefault();
                $.ajax({
                    url: 'update_exam.php',
                    type: 'POST',
                    data: {
                        id: $('#edit_exam_id').val(),
                        title: $('#edit_title').val(),
                        exam_date: $('#edit_exam_date').val(),
                        time_start: $('#edit_time_start').val(),
                        time_end: $('#edit_time_end').val(),
                        status: $('#edit_status').val(),
                        class: $('#edit_class_id').val(),
                        section: $('#edit_section_id').val(),
                        subject: $('#edit_subject_id').val(),
                        term: $('#edit_term_id').val()

                    },
                    success: function(response) {
                        alert(response);
                        location.reload();
                    }
                });
            });

            // Delete Exam
            $('.deleteExam').click(function() {
                let examId = $(this).closest('tr').data('id');
                if (confirm('Only admins are allowed to delete exams. Do you want to continue?')) {
                }
            });
        });
    </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
    }

  ?>
