<?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');
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:logout.php');

}

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

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



  // Backup student details with a prepared statement

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

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

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

    if (mysqli_stmt_execute($stmt)) {

      // Proceed to delete the student after backup with a prepared statement

      $deleteQuery = "DELETE FROM students 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 sucessfully.');

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

        } else {

          flash_alert('Error deleting student from database.');

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

        }

      } else {

        flash_alert('Error preparing delete query.');

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

      }

    } else {

      flash_alert('Error backing up student details.');

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

    }

    mysqli_stmt_close($stmt);

  } else {

    flash_alert('Error preparing backup query.');

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

  }

}





$section = isset($_GET['section']) ? $_GET['section'] : '';



?>

<!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 (Non-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="studentlist.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>Form No.</th>

                        <th>Fullname</th>

                        <th>Class </th>

                        <th>School Type </th>

                        <th>Session / Term to Resume</th>

                        <th>Select All <input type="checkbox" id="select_all"></th>

                        <th>Action</th>

                      </tr>

                    </thead>

                    <tbody>

                      <?php





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

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

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

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





                      $sql = "SELECT * FROM students WHERE status = 4";



                      if (!empty($classFilter)) {

                        $sql .= " AND class = '" . mysqli_real_escape_string($con, $classFilter) . "'";

                      }

                      if (!empty($armFilter)) {

                        $sql .= " AND section = '" . mysqli_real_escape_string($con, $armFilter) . "'";

                      }

                      if (!empty($streamFilter)) {

                        $sql .= " AND stream = '" . mysqli_real_escape_string($con, $streamFilter) . "'";

                      }

                      if (!empty($scholarshipFilter)) {

                        $sql .= " AND scholarship = '" . mysqli_real_escape_string($con, $scholarshipFilter) . "'";

                      }



                      $sql .= " ORDER BY class ASC";

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





                      $cnt = 1;

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

                        ?>

                        <tr>

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

                          <td class="align-middle"><a href="#"><img
                                src="studentimages/<?php echo htmlentities($row['studentImage']); ?>" width="40"
                                height="40"> </a></td>

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

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

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

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

                          <td>
                            <?php
                              $termRanksMap = ['First Term' => 1, 'Second Term' => 2, 'Third Term' => 3];
                              $rowSession  = trim($row['academic_session'] ?? '');
                              $rowTerm     = trim($row['admission_term']   ?? '');
                              $rowRank     = (int) substr($rowSession, 0, 4);
                              $curRank     = (int) substr($currentSessionName ?? '', 0, 4);
                              $rowTermRank = $termRanksMap[$rowTerm]        ?? 0;
                              $curTermRank = $termRanksMap[$currentTermName] ?? 0;

                              // Resolve to current if empty, past session, or same session but past term
                              $isPast = $rowSession === '' || $rowTerm === ''
                                  || $rowRank < $curRank
                                  || ($rowRank === $curRank && $rowTermRank < $curTermRank);

                              if ($isPast) {
                                  $rowSession  = $currentSessionName;
                                  $rowTerm     = $currentTermName;
                                  $wasResolved = true;
                              } else {
                                  $wasResolved = false;
                              }

                              $isCurrent  = ($rowSession === $currentSessionName);
                              $badgeClass = $isCurrent ? 'badge-success' : 'badge-warning';
                              $badgeLabel = $isCurrent ? 'Current' : 'Future';
                            ?>
                            <span class="badge <?= $badgeClass ?> mr-1"><?= $badgeLabel ?></span>
                            <?php if ($wasResolved): ?>
                              <span class="badge badge-secondary mr-1" title="Resolved from missing/past data">Auto</span>
                            <?php endif; ?>
                            <small><?= htmlspecialchars($rowSession) ?></small><br>
                            <small class="text-muted"><?= htmlspecialchars($rowTerm) ?></small>
                          </td>

                          <td><input type="checkbox" class="student_checkbox" name="student_ids[]"
                              value="<?php echo $row['id']; ?>"
                              data-session="<?php echo htmlspecialchars($rowSession); ?>"></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>

                            <a href="studentlist.php?id=<?php echo $row['id'] ?>&del=delete" title="click to delete"
                              onClick="return confirm('Are you sure you want to delete?')"
                              class=" btn btn-danger btn-xs "><i class=" fas fa-trash"></i></a>

                            <button class="btn btn-info btn-xs"
                              onclick='openDeadlineModal(<?php echo $row["id"]; ?>, <?php echo json_encode($rowSession); ?>)'>

                              <i class="fas fa-envelope-open-text"></i> Admit

                            </button>



                          </td>



                        </tr>

                        <?php $cnt = $cnt + 1;

                      } ?>

                    </tbody>

                  </table>

                  <center>

                    <button type="button" class="btn btn-block btn-primary" onclick="openBulkModal()">

                      <i class="fas fa-envelope-open-text"></i> Admit Selected Students

                    </button>

                  </center>

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

    });

    $(document).ready(function () {

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

    });

    $(document).ready(function () {

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

    });

  </script>

  <script type="text/javascript">

    $(document).ready(function () {

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

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

        $.ajax({

          url: "edit_student2.php",

          type: "post",

          data: {

            edit_id: edit_id

          },

          success: function (data) {

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

            $("#editData").data('ajax-src', 'edit_student2.php').modal('show');

          }

        });

      });

      // Intercept all form submissions inside the edit modal and handle via AJAX
      $(document).on('submit', '#editData form', function (e) {

        e.preventDefault();

        var formData = new FormData(this);
        formData.append('is_ajax', '1');

        $.ajax({

          url: "edit_student2.php",

          type: "post",

          data: formData,

          processData: false,

          contentType: false,

          success: function (response) {

            console.log('edit_student2 raw response:', response);

            try {
              var res = (typeof response === 'string') ? JSON.parse(response) : response;
              console.log('parsed res:', res);
              if (res.success) {
                $("#editData").modal('hide');
                Swal.fire({
                  icon: 'success',
                  title: 'Updated!',
                  text: 'Student record updated successfully.',
                  timer: 2500,
                  showConfirmButton: false,
                  customClass: { popup: 'swal-portal-popup' }
                });
              } else {
                Swal.fire({
                  icon: 'error',
                  title: 'Error',
                  text: 'Something went wrong, please try again.',
                  customClass: { popup: 'swal-portal-popup' }
                });
              }
            } catch (err) {
              console.log('JSON parse error:', err);
              $("#editData").modal('hide');
            }

          },

          error: function () {
            alert('Something went wrong, please try again.');
          }

        });

      });

    });



    const currentSessionName = <?= json_encode($currentSessionName) ?>;

    function openDeadlineModal(studentId, studentSession) {
      document.getElementById('modal_student_id').value = studentId;

      // Show acceptance fee field only if student is resuming in a future session
      const isFutureSession = studentSession !== currentSessionName;
      const group = document.getElementById('acceptance_deadline_group');
      const input = document.getElementById('acceptance_deadline_input');
      group.style.display = isFutureSession ? 'block' : 'none';
      input.required = isFutureSession;
      if (!isFutureSession) input.value = '';

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

  </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>

    // Select/deselect all checkboxes

    document.getElementById("select_all").addEventListener("change", function () {

      let checkboxes = document.querySelectorAll(".student_checkbox");

      checkboxes.forEach(cb => cb.checked = this.checked);

    });



    // Open bulk modal and gather selected IDs

    function openBulkModal() {

      let selected = [];
      let hasFutureSession = false;

      document.querySelectorAll(".student_checkbox:checked").forEach(cb => {
        selected.push(cb.value);
        // Check if any selected student is resuming in a future session
        if (cb.dataset.session && cb.dataset.session !== currentSessionName) {
          hasFutureSession = true;
        }
      });

      if (selected.length === 0) {
        alert("Please select at least one student.");
        return;
      }

      document.getElementById("bulk_student_ids").value = selected.join(",");

      // Show acceptance fee field only if at least one student is in a future session
      const group = document.getElementById('bulk_acceptance_deadline_group');
      const input = document.getElementById('bulk_acceptance_deadline_input');
      group.style.display = hasFutureSession ? 'block' : 'none';
      input.required = hasFutureSession;
      if (!hasFutureSession) input.value = '';

      $('#bulkAdmitModal').modal('show');

    }

  </script>





  <div class="modal fade" id="setDeadlineModal" tabindex="-1" role="dialog" aria-labelledby="setDeadlineModalLabel"
    aria-hidden="true">

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

      <form method="post" action="admit_student.php" data-no-ajax>

        <div class="modal-content">

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

            <h5 class="modal-title" id="setDeadlineModalLabel"><i class="fas fa-calendar-alt"></i> Set Payment Deadlines</h5>

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

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

            </button>

          </div>

          <div class="modal-body">

            <input type="hidden" name="student_id" id="modal_student_id">

            <div class="form-group" id="acceptance_deadline_group" style="display:none;">

              <label for="acceptance_deadline">Acceptance Fee Deadline</label>

              <input type="date" class="form-control" name="acceptance_deadline" id="acceptance_deadline_input">

              <small class="text-muted">Only shown for students resuming in a future session.</small>

            </div>

            <div class="form-group">

              <label for="schoolfee_deadline">School Fee Deadline</label>

              <input type="date" class="form-control" name="schoolfee_deadline" required>

            </div>

          </div>

          <div class="modal-footer">

            <button type="submit" name="submit_deadlines" class="btn btn-primary"><i
                class="fas fa-envelope-open-text"></i> Admit & Send Email</button>

            <button type="button" class="btn btn-danger" data-dismiss="modal"> <i class="fas fa-times"></i>
              Cancel</button>

          </div>

        </div>

      </form>

    </div>

  </div>



  <div class="modal fade" id="bulkAdmitModal" tabindex="-1" role="dialog" aria-labelledby="bulkAdmitModalLabel"
    aria-hidden="true">

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

      <form method="post" action="admit_student.php" data-no-ajax>

        <div class="modal-content">

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

            <h5 class="modal-title"><i class="fas fa-calendar-alt"></i> Bulk Admit Students</h5>

            <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>

          </div>

          <div class="modal-body">

            <input type="hidden" name="bulk_student_ids" id="bulk_student_ids">

            <div class="form-group" id="bulk_acceptance_deadline_group" style="display:none;">

              <label>Acceptance Fee Deadline</label>

              <input type="date" name="acceptance_deadline" id="bulk_acceptance_deadline_input" class="form-control">

              <small class="text-muted">Only shown when at least one selected student is resuming in a future session.</small>

            </div>

            <div class="form-group">

              <label>School Fee Deadline</label>

              <input type="date" name="schoolfee_deadline" class="form-control" required>

            </div>

          </div>

          <div class="modal-footer">

            <button type="submit" name="submit_bulk_deadlines" class="btn btn-primary">

              <i class="fas fa-envelope-open-text"></i> Admit Selected & Send Email

            </button>

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

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

            </button>

          </div>

        </div>

      </form>

    </div>

  </div>





</body>



</html>