<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
  mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

error_reporting(0);

include('includes/dbconnection.php');

require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName = $stResult['term_name'];

if (strlen($_SESSION['sid']) == 0) {

  header('location:logout.php');

  exit();

}

?>



<!DOCTYPE html>

<html>

<?php @include("includes/head.php"); ?>



<body class="hold-transition sidebar-mini layout-fixed">

  <div class="wrapper">

    <?php @include("includes/header.php"); ?>

    <?php @include("includes/sidebar.php"); ?>



    <div class="content-wrapper">

      <section class="content-header premium-header">

        <div class="container-fluid">

          <div class="header-glass-card">

            <div class="row align-items-center">

              <div class="col-md-8">

                <div class="title-section">

                  <div class="icon-box bg-primary-gradient shadow-sm">

                    <i class="fas fa-user-tie"></i>

                  </div>

                  <div>

                    <h1 class="premium-title text-primary">

                      Teacher Information Management

                      <span class="premium-subtitle text-secondary">Manage Teacher's Assignment</span>

                    </h1>
                    <div class="mt-1">
                      <?php if ($currentSessionName): ?>
                        <span class="badge badge-primary mr-1">
                          <i class="fas fa-calendar-alt"></i>
                          <?= htmlspecialchars($currentSessionName) ?>
                        </span>
                      <?php endif; ?>
                      <?php if ($currentTermName): ?>
                        <span class="badge badge-success">
                          <i class="fas fa-bookmark"></i>
                          <?= htmlspecialchars($currentTermName) ?>
                        </span>
                      <?php else: ?>
                        <span class="badge badge-warning">
                          <i class="fas fa-exclamation-triangle"></i> No active term
                        </span>
                      <?php endif; ?>
                    </div>

                  </div>

                </div>

              </div>

              <div class="col-md-4">

                <nav aria-label="breadcrumb">

                  <ol class="breadcrumb premium-breadcrumb">

                    <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>

                    <li class="breadcrumb-item active" aria-current="page">Assign Teacher</li>

                  </ol>

                </nav>

              </div>

            </div>

          </div>

        </div>

      </section>



      <section class="content">

        <div class="container-fluid">

          <div class="row">

            <div class="col-12">



              <div class="card card-primary">

                <div class="card-header">

                  <h5 class="card-title font-weight-bold">

                    <i class="fas fa-chalkboard-teacher"></i> Teacher's Assignments

                  </h5>

                </div>

                <div class="card-body">

                  <div class="row">

                    <div class="col-md-6">

                      <div class="form-group">

                        <label for="teacherSelect">Search by Teacher:</label>

                        <select id="teacherSelect" class="form-control select2" style="width: 100%;">

                          <option value="">-- Select Teacher --</option>

                          <?php

                          $teacherQuery = mysqli_query($con, "SELECT id, name, lastname, title FROM tblusers WHERE status=2 ORDER BY name ASC");

                          while ($row = mysqli_fetch_assoc($teacherQuery)) {

                            echo '<option value="' . $row['id'] . '">' . htmlentities($row['title'] . ' ' . $row['name'] . ' ' . $row['lastname']) . '</option>';

                          }

                          ?>

                        </select>

                      </div>

                    </div>



                    <div class="col-md-6">

                      <div class="form-group">

                        <label for="subjectSelect">Search by Subject:</label>

                        <select id="subjectSelect" class="form-control select2" style="width: 100%;">

                          <option value="">-- Select Subject --</option>

                          <?php

                          $subjectQuery = mysqli_query($con, "SELECT DISTINCT Subject_name FROM subjectcombination ORDER BY Subject_name ASC");

                          while ($row = mysqli_fetch_assoc($subjectQuery)) {

                            echo '<option value="' . htmlentities($row['Subject_name']) . '">' . htmlentities($row['Subject_name']) . '</option>';

                          }

                          ?>

                        </select>

                      </div>

                    </div>

                    <div class="mb-3">

                      <button id="showClassTeachers" class="btn btn-primary">

                        <i class="fas fa-users"></i> Show All Class Teachers

                      </button>

                    </div>



                  </div>

                </div>

              </div>



              <div class="card card-outline card-info" id="assignmentCard" style="display:none;">

                <div class="card-header bg-info text-white">

                  <h5 class="mb-0">

                    <i class="fas fa-list"></i> Assigned Classes & Subjects for

                    <span id="selectedTeacher" class="font-weight-bold text-warning"></span>

                  </h5>

                </div>

                <div class="card-body">

                  <table class="table table-bordered table-hover" id="example1">

                    <thead class="bg-primary text-white">

                      <tr>

                        <th>#</th>

                        <th>Teacher</th>

                        <th>Class</th>

                        <th>Subject</th>

                        <th>Class Teacher</th>

                      </tr>

                    </thead>

                    <tbody id="assignmentTable"></tbody>

                  </table>

                </div>

              </div>



            </div>

          </div>

        </div>

      </section>

    </div>



    <?php @include("includes/footer.php"); ?>

  </div>



  <?php @include("includes/foot.php"); ?>

  <script src="dist/js/select2.min.js"></script>



  <script>

    $(document).ready(function () {

      $('#teacherSelect, #subjectSelect').select2();



      // suppress prevents double-calls when we programmatically clear the other select

      let suppress = false;



      function fetchAssignments() {

        var teacherId = $('#teacherSelect').val() ? $('#teacherSelect').val() : '';

        var teacherName = $('#teacherSelect option:selected').text() ? $('#teacherSelect option:selected').text() : '';

        var subjectName = $('#subjectSelect').val() ? $('#subjectSelect').val() : '';



        // nothing selected => hide card

        if (teacherId === "" && subjectName === "") {

          $('#assignmentCard').hide();

          $('#assignmentTable').html("");

          $('#selectedTeacher').text("");

          return;

        }



        // update header text

        if (teacherId !== "") {

          $('#selectedTeacher').text(teacherName);

        } else if (subjectName !== "") {

          $('#selectedTeacher').text('Subject: ' + subjectName);

        }



        $.ajax({

          url: 'fetch_teacher_assignments.php',

          type: 'POST',

          data: { teacher_id: teacherId, subject_name: subjectName },

          dataType: 'html',

          success: function (response) {

            $('#assignmentCard').show();

            $('#assignmentTable').html(response);

          },

          error: function (xhr, status, err) {

            console.error('AJAX Error:', status, err);

            console.error(xhr.responseText);

            $('#assignmentCard').show();

            $('#assignmentTable').html('<tr><td colspan="6" class="text-center text-danger">An error occurred while fetching data. Check console.</td></tr>');

          }

        });

      }

      $('#showClassTeachers').on('click', function () {

        suppress = true;

        $('#teacherSelect').val('').trigger('change.select2');

        $('#subjectSelect').val('').trigger('change.select2');

        setTimeout(function () { suppress = false; }, 50);



        $.ajax({

          url: 'fetch_teacher_assignments.php',

          type: 'POST',

          data: { show_all_class_teachers: 1 },

          dataType: 'html',

          success: function (response) {

            // Hide the Subject column

            $('#example1 th:nth-child(4), #example1 td:nth-child(4)').hide();



            $('#assignmentCard').show();

            $('#selectedTeacher').text('All Class Teachers');

            $('#assignmentTable').html(response);

          },

          error: function (xhr, status, err) {

            console.error('AJAX Error:', status, err);

            $('#assignmentCard').show();

            $('#selectedTeacher').text('All Class Teachers');

            $('#assignmentTable').html('<tr><td colspan="5" class="text-center text-danger">Failed to fetch class teachers.</td></tr>');

          }

        });

      });



      // When selecting teacher or subject manually → re-show the Subject column

      $('#teacherSelect, #subjectSelect').on('change', function () {

        $('#example1 th:nth-child(4), #example1 td:nth-child(4)').show();

      });







      $('#teacherSelect').on('change', function () {

        if (suppress) return;

        // clear subject (do not trigger its handler)

        suppress = true;

        $('#subjectSelect').val('').trigger('change.select2'); // update UI state

        setTimeout(function () { suppress = false; fetchAssignments(); }, 50);

      });



      $('#subjectSelect').on('change', function () {

        if (suppress) return;

        // clear teacher (do not trigger its handler)

        suppress = true;

        $('#teacherSelect').val('').trigger('change.select2'); // update UI state

        setTimeout(function () { suppress = false; fetchAssignments(); }, 50);

      });



      // If you want to allow user clearing both selects manually via the X on select2, handle that as well:

      $('#teacherSelect, #subjectSelect').on('select2:unselecting', function (e) {

        // let the normal change handler handle things

      });

    });

  </script>

</body>

</html>