<?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();

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


include('includes/flash.php');



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

  header('location:logout.php');

  exit();

}



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

  // Securely cast ID to integer to prevent injection and logic errors

  $id = intval($_GET['id']);



  // Build backup query using only columns that exist in BOTH tables,
  // excluding deleted_at from students (we supply it via NOW()).
  $studentsColsRes = mysqli_query($con, "SHOW COLUMNS FROM students");
  $deletedColsRes  = mysqli_query($con, "SHOW COLUMNS FROM deleted_students");

  $studentsCols = [];
  while ($c = mysqli_fetch_assoc($studentsColsRes)) $studentsCols[] = $c['Field'];

  $deletedCols = [];
  while ($c = mysqli_fetch_assoc($deletedColsRes))  $deletedCols[]  = $c['Field'];

  // Columns to copy: present in deleted_students, present in students, but NOT deleted_at
  // (deleted_at is supplied by NOW() below)
  $commonCols = array_intersect(
      array_diff($deletedCols, ['deleted_at']),
      $studentsCols
  );
  $colList = implode(', ', array_map(fn($c) => "`$c`", $commonCols));

  $backupQuery = "INSERT INTO deleted_students ($colList, `deleted_at`)
                  SELECT $colList, NOW() FROM students WHERE id = ?";



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

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



    if (mysqli_stmt_execute($stmt)) {

      // Proceed to SOFT DELETE the student (setting status to 5)

      $deleteQuery = "UPDATE students SET deleted_at = NOW(), status = 5 WHERE id = ?";



      if ($stmtDelete = mysqli_prepare($con, $deleteQuery)) {

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

        if (mysqli_stmt_execute($stmtDelete)) {

          flash_alert('Student deleted and backup successfully.');

        } else {

          flash_alert('Error updating student status.');

        }

        mysqli_stmt_close($stmtDelete);

      } else {

        flash_alert('Error preparing delete query.');

      }

    } else {

      flash_alert('Error during backup: A database constraint was hit.');

    }

    mysqli_stmt_close($stmt);

  } else {

    flash_alert('Error preparing backup statement.');

  }

  header('Location: student_list.php');

  exit;

}



// --- PAGINATION & FILTER LOGIC ---

$classFilter = isset($_GET['class']) ? mysqli_real_escape_string($con, $_GET['class']) : '';

$armFilter = isset($_GET['arm']) ? mysqli_real_escape_string($con, $_GET['arm']) : '';

$streamFilter = isset($_GET['stream']) ? mysqli_real_escape_string($con, $_GET['stream']) : '';

$scholarshipFilter = isset($_GET['scholarship']) ? mysqli_real_escape_string($con, $_GET['scholarship']) : '';



// 1. Set pagination variables

$limit = 100;

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;

if ($page < 1)

  $page = 1;

$offset = ($page - 1) * $limit;



// 2. Build the WHERE clause for both Count and Data queries

$where = " WHERE status = 1";

if (!empty($classFilter))

  $where .= " AND class = '$classFilter'";

if (!empty($armFilter))

  $where .= " AND section = '$armFilter'";

if (!empty($streamFilter))

  $where .= " AND stream = '$streamFilter'";

if (!empty($scholarshipFilter))

  $where .= " AND scholarship = '$scholarshipFilter'";



// 3. Count total records for pagination

$count_result = mysqli_query($con, "SELECT COUNT(*) as total FROM students $where");

$total_rows = mysqli_fetch_assoc($count_result)['total'];

$total_pages = ceil($total_rows / $limit);



// 4. Fetch the actual data with LIMIT and OFFSET

$sql = "SELECT * FROM students $where ORDER BY class ASC LIMIT $limit OFFSET $offset";

$Fetchquery = mysqli_query($con, $sql);



// Helper function to build pagination links while keeping filters

function getPageUrl($p)

{

  $params = $_GET;

  $params['page'] = $p;

  return "student_list.php?" . http_build_query($params);

}

?>

<!DOCTYPE html>

<html>

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



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

  <div class="wrapper">

    <!-- Navbar -->

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

    <!-- /.navbar -->



    <!-- Main Sidebar Container -->

    <?php @include("includes/sidebar.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-graduate"></i>

                  </div>

                  <div>

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

                      Student Information Management

                      <span class="premium-subtitle text-secondary">Manage Student</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">Student 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-users"></i> Manage Students (Admitted

                    Students Only)</h5>

                  <div class="card-tools">

                    <a href="restore_student.php"><button type="button" class="btn btn-sm btn-primary"><span

                          style="color: #fff;"><i class="fas fa-undo"></i> Restore Student</span>

                      </button></a>

                    <a href="add_student.php"><button type="button" class="btn btn-sm btn-primary"><span

                          style="color: #fff;"><i class="fas fa-user-plus"></i> Add New Student</span>

                      </button> </a>

                  </div>

                </div>



                <div class="card-body">

                  <!-- Date filter form -->

                  <form method="GET" action="student_list.php">

                    <div class="row p-0 m-0">

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

                        <label for="class">Class</label>

                        <select name="class" id="class" class="form-control" onchange="fetchArms()">

                          <option value="">Select Class</option>

                          <?php

                          $query = "SELECT DISTINCT class FROM class_section ORDER BY class";

                          $result = $con->query($query);

                          while ($row = $result->fetch_assoc()) {

                            $selected = ($classFilter == $row['class']) ? 'selected' : '';

                            echo "<option value='{$row['class']}' $selected>{$row['class']}</option>";

                          }

                          ?>

                        </select>

                      </div>



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

                        <label for="arm">Arm</label>

                        <select name="arm" id="arm" class="form-control">

                          <option value="">Select Arm</option>

                        </select>

                      </div>

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

                        <label for="stream">School Type</label>

                        <select name="stream" id="stream" class="form-control">

                          <option value="">Select School Type</option>

                          <option value="Day">Day</option>

                          <option value="Boarding">Boarding</option>



                        </select>

                      </div>

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

                        <label for="scholarship">Scholarship Status</label>

                        <select name="scholarship" id="scholarship" class="form-control">

                          <option value="">Select Scholarship Status</option>

                          <option value="Yes">On Scholarship</option>

                          <option value="No">Off Scholarship</option>



                        </select>

                      </div>





                      <div class="form-group col-md-12">

                        <center><button type="submit" class="btn btn-primary">

                            <i class="fas fa-search"></i> Search

                          </button>



                          <button type="button" class="btn btn-success" onclick="downloadFilteredPDF()"><i

                              class="fas fa-download"></i> Download</button>

                        </center>

                      </div>

                    </div>

                  </form>

                </div>

                <!-- /.card-header -->

                <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-graduate"></i> Student 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 id="editData2" class="modal fade">

                  <div class="modal-dialog ">

                    <div class="modal-content">

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

                        <h5 class="modal-title"><i class="fas fa-user-graduate"></i> Student 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_update2">

                        <!-- 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>Student Image</th>

                        <th>Admission No.</th>

                        <th>Fullname</th>

                        <th>Class </th>

                        <th>Arm </th>

                        <th>School Type </th>

                        <th>Action</th>

                      </tr>

                    </thead>

                    <tbody>

                      <?php

                      $cnt = $offset + 1; // Start counting from the correct offset

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

                        ?>

                        <tr>

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

                          <td class="align-middle">

                            <img src="studentimages/<?php echo htmlentities($row['studentImage']); ?>" width="40"

                              height="40">

                          </td>

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

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

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

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

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

                          <td>

                            <button class="btn btn-primary btn-xs edit_data" id="<?php echo $row['id']; ?>"

                              title="click for edit"><i class=" fas fa-edit"></i></button>

                            <button class="btn btn-success btn-xs edit_data2" id="<?php echo $row['id']; ?>"

                              title="click to view"><i class=" fas fa-eye"></i></button>

                            <a href="print_profile.php?student_id=<?php echo $row['id']; ?>" target="_blank"

                              title="click to print" class=" btn btn-warning btn-xs "><i

                                class=" fas fa-print"></i></a><br>

                            <a href="student_list.php?id=<?php echo $row['id'] ?>&del=delete" title="click to delete"

                              class="btn btn-danger btn-xs delete-student-btn"><i class=" fas fa-trash"></i></a>

                            <button class="btn btn-xs btn-secondary view-subjects-btn"

                              data-student-id="<?= $row['id']; ?>" title="click to view student subjects"

                              data-student-name="<?= htmlspecialchars($row['studentName']); ?>">

                              <i class="fas fa-book"></i>

                            </button>

                          </td>

                        </tr>

                        <?php $cnt++;

                      } ?>

                    </tbody>

                  </table>

                </div>

                <div class="card-footer clearfix">

                  <div class="float-left">

                    <p class="text-muted small">

                      Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_rows); ?> of

                      <?php echo $total_rows; ?> students

                    </p>

                  </div>

                  <ul class="pagination pagination-sm m-0 float-right">

                    <li class="page-item <?php if ($page <= 1)

                      echo 'disabled'; ?>">

                      <a class="page-link" href="<?php echo getPageUrl($page - 1); ?>">« Previous</a>

                    </li>



                    <?php

                    for ($i = 1; $i <= $total_pages; $i++):

                      // Only show page numbers near the current page to prevent a massive list

                      if ($i == 1 || $i == $total_pages || ($i >= $page - 2 && $i <= $page + 2)):

                        ?>

                        <li class="page-item <?php if ($page == $i)

                          echo 'active'; ?>">

                          <a class="page-link" href="<?php echo getPageUrl($i); ?>"><?php echo $i; ?></a>

                        </li>

                      <?php elseif ($i == $page - 3 || $i == $page + 3): ?>

                        <li class="page-item disabled"><span class="page-link">...</span></li>

                      <?php endif; endfor; ?>



                    <li class="page-item <?php if ($page >= $total_pages)

                      echo 'disabled'; ?>">

                      <a class="page-link" href="<?php echo getPageUrl($page + 1); ?>">Next »</a>

                    </li>

                  </ul>

                </div>

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

              </div>

              <!-- /.card -->

            </div>

            <!-- /.col -->

          </div>

          <!-- /.row -->

        </div>

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

      </section>

      <!-- /.content -->

    </div>

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

    <!-- Modal -->

    <div class="modal fade" id="studentSubjectsModal" tabindex="-1" role="dialog" aria-labelledby="studentSubjectsLabel"

      aria-hidden="true">

      <div class="modal-dialog modal-lg modal-dialog-centered" role="document">

        <div class="modal-content">

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

            <h5 class="modal-title" id="studentSubjectsLabel">

              <i class="fas fa-book-open"></i> Allocated Subjects

            </h5>

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

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

            </button>

          </div>

          <div class="modal-body">

            <h6 id="studentName" class="text-center mb-3"></h6>

            <div id="subjectsTableContainer" class="table-responsive text-center">

              <p class="text-muted">Loading subjects...</p>

            </div>

          </div>

          <div class="modal-footer">

            <button type="button" class="btn btn-secondary" data-dismiss="modal">

              <i class="fas fa-times"></i> Close

            </button>

          </div>

        </div>

      </div>

    </div>



    <?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();

    });

    $(document).ready(function () {

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

    });

    $(document).ready(function () {

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

    });

    // Fetch and display allocated subjects dynamically

    $(document).on("click", ".view-subjects-btn", function () {

      var studentId = $(this).data("student-id");

      var studentName = $(this).data("student-name");



      $("#studentSubjectsLabel").html("<i class='fas fa-book-open'></i> Subjects for " + studentName);

      $("#subjectsTableContainer").html("<p class='text-muted'>Loading...</p>");

      $("#studentSubjectsModal").modal("show");



      $.ajax({

        url: "fetch_student_subjects.php",

        type: "GET",

        data: { student_id: studentId },

        success: function (response) {

          $("#subjectsTableContainer").html(response);

        },

        error: function () {

          $("#subjectsTableContainer").html("<div class='alert alert-danger'>Error loading subjects.</div>");

        }

      });

    });

  </script>

  <script type="text/javascript">

    $(document).ready(function () {

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

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

        $.ajax({

          url: "edit_student.php",

          type: "post",

          data: {

            edit_id: edit_id

          },

          success: function (data) {

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

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

          }

        });

      });

    });

  </script>

  <script type="text/javascript">

    $(document).ready(function () {

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

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

        $.ajax({

          url: "view_student_info.php",

          type: "post",

          data: {

            edit_id2: edit_id2

          },

          success: function (data) {

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

            $("#editData2").data('ajax-src', 'view_student_info.php').modal('show');
            $("#editData2").find('form:not([action])').attr('data-ajax-action', 'view_student_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;

              if (arm === "<?php echo $armFilter; ?>") {

                option.selected = true;

              }

              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>

  <script type="text/javascript">

    $(document).ready(function () {

      $(document).on('click', '.delete-student-btn', function (e) {

        e.preventDefault();

        if (confirm('Are you sure you want to delete this student?')) {

          window.location.href = $(this).attr('href');

        }

      });

    });

  </script>

</body>



</html>