<?php

session_name('small_admin_session');

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

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

session_start();

error_reporting(0);

include('includes/dbconnection.php');
include('includes/flash.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:logoutsmall.php');

}

if (isset($_GET['del'])) {

  $id = intval($_GET['id']); // Securely get the teacher ID



  // Step 1: Backup the teacher data

  $backupQuery = "INSERT INTO deleted_teachers (original_id, name, lastname, username, email, mobile, userimage, sex, permission, password, deleted_by)

                    SELECT id, name, lastname, username, email, mobile, userimage, sex, permission, password, ? FROM tblusers WHERE id = ?";



  if ($stmtBackup = mysqli_prepare($con, $backupQuery)) {

    mysqli_stmt_bind_param($stmtBackup, "ii", $_SESSION['sid'], $id);

    if (mysqli_stmt_execute($stmtBackup)) {



      // Step 2: Soft delete teacher (update status instead of delete)

      $softDelete = "UPDATE tblusers SET status = 0 WHERE id = ?";

      if ($stmtSoft = mysqli_prepare($con, $softDelete)) {

        mysqli_stmt_bind_param($stmtSoft, "i", $id);

        if (mysqli_stmt_execute($stmtSoft)) {



          // ✅ Step 3: Hard delete teacher assignments

          $deleteAssign = "DELETE FROM teacher_assignments WHERE teacher_id = ?";

          if ($stmtAssign = mysqli_prepare($con, $deleteAssign)) {

            mysqli_stmt_bind_param($stmtAssign, "i", $id);

            mysqli_stmt_execute($stmtAssign);

          }



          flash_alert('Teacher deactivated and all related assignments deleted successfully.');

          header('Location: teacher_list.php');
          exit;

        } else {

          flash_alert('Error updating teacher status.');

        }

      } else {

        flash_alert('Error preparing soft delete query.');

      }



    } else {

      flash_alert('Failed to backup teacher data.');

    }

  } else {

    flash_alert('Error preparing backup query.');

  }

}







?>

<!DOCTYPE html>

<html>

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



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

  <div class="wrapper">

    <!-- Navbar -->

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

    <!-- /.navbar -->



    <!-- Main Sidebar Container -->

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



    <!-- Content Wrapper. Contains page content -->

    <div class="content-wrapper">

      <!-- Content Header (Page header) -->

      <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</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="dashboard2.php" class="text-primary">Home</a></li>

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

                  </ol>

                </nav>

              </div>

            </div>

          </div>

        </div>

      </section>





      <!-- Main content -->

      <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-list"></i> Teacher's List</h5>

                  <div class="card-tools">

                  </div>

                </div>



                <div id="editData" class="modal fade">

                  <div class="modal-dialog modal-xl">

                    <div class="modal-content">

                      <div class="modal-header bg-primary">

                        <h5 class="modal-title"><i class="fas fa-user-tie"></i> Teacher details</h5>

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">

                          <span aria-hidden="true">&times;</span>

                        </button>

                      </div>

                      <div class="modal-body" id="info_update">
                        <!-- loaded via AJAX -->
                      </div>

                      <div class="modal-footer ">

                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                      </div>

                      <!-- /.modal-content -->

                    </div>

                    <!-- /.modal-dialog -->

                  </div>

                  <!-- /.modal -->

                </div>

                <!--   end modal -->











                <div class="card-body mt-2 ">

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

                    <thead>

                      <tr>

                        <th>#</th>

                        <th>Image</th>

                        <th>Title</th>

                        <th>Firstname</th>

                        <th>Lastname</th>

                        <th>View More</th>

                      </tr>

                    </thead>

                    <tbody>

                      <?php $query = mysqli_query($con, "select * from tblusers where status = 2 AND name !='Developer' AND lastname !='Account' AND username !='Developer'");

                      $cnt = 1;

                      while ($row = mysqli_fetch_array($query)) {

                        ?>

                        <tr>

                          <td><?php echo htmlentities($cnt); ?></td>

                          <td class="align-middle"><a href="#"><img src="staff_images/<?php echo $row['userimage']; ?>"
                                width="40" height="40"> </a></td>

                          <td><?php echo htmlentities($row['title']); ?></td>

                          <td><?php echo htmlentities($row['name']); ?></td>

                          <td><?php echo htmlentities($row['lastname']); ?></td>

                          <td>

                            <button class="btn btn-primary btn-xs edit_data" id="<?php echo $row['id']; ?>"
                              title="click for view"><i class=" fas fa-eye"></i> View More</button>

                          </td>

                        </tr>

                        <?php $cnt = $cnt + 1;

                      } ?>

                    </tbody>

                  </table>

                </div>

                <!-- /.card-body -->

              </div>

              <!-- /.card -->

            </div>

            <!-- /.col -->

          </div>

          <!-- /.row -->

        </div>

        <!-- /.container-fluid -->

      </section>

      <!-- /.content -->

    </div>

    <!-- /.content-wrapper -->

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



    <!-- Control Sidebar -->

    <aside class="control-sidebar control-sidebar-dark">

      <!-- Control sidebar content goes here -->

    </aside>

    <!-- /.control-sidebar -->

  </div>



  <!-- ./wrapper -->

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

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

  <script>

    // In your Javascript (external .js resource or <script> tag)

    $(document).ready(function () {

      $('#class').select2();

    });

    $(document).ready(function () {

      $('#arm').select2();

    });

  </script>

  <script type="text/javascript">

    $(document).ready(function () {

      $(document).on('click', '.edit_data', function () {

        var edit_id = $(this).attr('id');

        $.ajax({

          url: "edit_teacher11.php",

          type: "post",

          data: {

            edit_id: edit_id

          },

          success: function (data) {

            $("#info_update").html(data);

            $("#editData").data('ajax-src', 'edit_teacher11.php').modal('show');
            $("#editData").find('form:not([action])').attr('data-ajax-action', 'edit_teacher11.php');

          }

        });

      });

    });

  </script>

  <script type="text/javascript">

    $(document).ready(function () {

      $(document).on('click', '.edit_data2', function () {

        var edit_id2 = $(this).attr('id');

        $.ajax({

          url: "view_teacher_info.php",

          type: "post",

          data: {

            edit_id2: edit_id2

          },

          success: function (data) {

            $("#info_update2").html(data);

            $("#editData2").data('ajax-src', 'view_teacher_info.php').modal('show');
            $("#editData2").find('form:not([action])').attr('data-ajax-action', 'view_teacher_info.php');

          }

        });

      });

    });

  </script>



  <script>

    function fetchArms() {

      var classSelected = document.getElementById("class").value;

      var armDropdown = document.getElementById("arm");



      // Clear previous options

      armDropdown.innerHTML = '<option value="">Select Arm</option>';



      if (classSelected) {

        fetch("fetch_arms.php?class=" + classSelected)

          .then(response => response.json())

          .then(data => {

            data.forEach(arm => {

              let option = document.createElement("option");

              option.value = arm;

              option.textContent = arm;

              armDropdown.appendChild(option);

            });

          })

          .catch(error => console.error("Error fetching arms:", error));

      }

    }



    function downloadFilteredPDF() {

      var selectedClass = document.getElementById("class").value;

      var selectedArm = document.getElementById("arm").value;



      if (selectedClass) {

        var url = "generate_pdf11.php?class=" + selectedClass + "&arm=" + selectedArm;

        window.location.href = url;

      } else {

        alert("Please select a class.");

      }

    }

  </script>

</body>



</html>