<?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'];

// Pending token count
$pendingStmt = $con->prepare("SELECT COUNT(*) AS cnt FROM registration_tokens WHERE token_status = 'pending'");
$pendingStmt->execute();
$pendingCount = $pendingStmt->get_result()->fetch_assoc()['cnt'];
$pendingStmt->close();

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: student_list.php');
          exit;

        } else {

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

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

        }

      } else {

        flash_alert('Error preparing delete query.');

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

      }

    } else {

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

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

    }

    mysqli_stmt_close($stmt);

  } else {

    flash_alert('Error preparing backup query.');

    header('Location: student_list.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">Registration Token</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">Token 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">

              <!-- Pending Token Summary -->
              <div class="token-summary-panel mb-4 mt-3">
                <style>
                  .token-summary-panel {
                    background: linear-gradient(135deg, #fff8e1 0%, #ffffff 100%);
                    border: 1px solid #ffe082;
                    border-radius: 16px;
                    padding: 24px 28px;
                    box-shadow: 0 4px 24px rgba(255,193,7,0.10), 0 1.5px 6px rgba(0,0,0,0.04);
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    flex-wrap: wrap;
                    gap: 18px;
                  }
                  .token-summary-left {
                    display: flex;
                    align-items: center;
                    gap: 18px;
                  }
                  .token-summary-icon {
                    width: 60px;
                    height: 60px;
                    border-radius: 14px;
                    background: linear-gradient(135deg, #ffc107, #ff8f00);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    box-shadow: 0 4px 12px rgba(255,193,7,0.35);
                    flex-shrink: 0;
                  }
                  .token-summary-icon i {
                    font-size: 26px;
                    color: #fff;
                  }
                  .token-summary-meta {
                    display: flex;
                    flex-direction: column;
                  }
                  .token-summary-label {
                    font-size: 12px;
                    font-weight: 600;
                    text-transform: uppercase;
                    letter-spacing: 0.08em;
                    color: #9e7c00;
                    margin-bottom: 2px;
                  }
                  .token-summary-count {
                    font-size: 36px;
                    font-weight: 800;
                    color: #212121;
                    line-height: 1;
                  }
                  .token-summary-sub {
                    font-size: 12px;
                    color: #888;
                    margin-top: 3px;
                  }
                  .token-summary-actions {
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    flex-wrap: wrap;
                  }
                  .btn-bulk-reminder {
                    display: inline-flex;
                    align-items: center;
                    gap: 8px;
                    background: linear-gradient(135deg, #ffc107, #ff8f00);
                    color: #fff;
                    border: none;
                    border-radius: 10px;
                    padding: 10px 22px;
                    font-size: 14px;
                    font-weight: 600;
                    cursor: pointer;
                    box-shadow: 0 3px 10px rgba(255,193,7,0.35);
                    transition: transform 0.15s, box-shadow 0.15s;
                    text-decoration: none;
                  }
                  .btn-bulk-reminder:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 6px 18px rgba(255,193,7,0.45);
                    color: #fff;
                  }
                  .btn-bulk-reminder .badge-count {
                    background: rgba(255,255,255,0.25);
                    border-radius: 20px;
                    padding: 1px 8px;
                    font-size: 12px;
                    font-weight: 700;
                  }
                  .btn-email-log {
                    display: inline-flex;
                    align-items: center;
                    gap: 8px;
                    background: #fff;
                    color: #555;
                    border: 1.5px solid #e0e0e0;
                    border-radius: 10px;
                    padding: 10px 20px;
                    font-size: 14px;
                    font-weight: 500;
                    cursor: pointer;
                    transition: border-color 0.15s, color 0.15s, box-shadow 0.15s;
                    text-decoration: none;
                  }
                  .btn-email-log:hover {
                    border-color: #bdbdbd;
                    color: #222;
                    box-shadow: 0 2px 8px rgba(0,0,0,0.07);
                    text-decoration: none;
                  }
                </style>

                <div class="token-summary-left">
                  <div class="token-summary-icon">
                    <i class="fas fa-hourglass-half"></i>
                  </div>
                  <div class="token-summary-meta">
                    <span class="token-summary-label">Awaiting Registration</span>
                    <span class="token-summary-count"><?= intval($pendingCount) ?></span>
                    <span class="token-summary-sub">
                      <?= intval($pendingCount) === 1 ? 'student has not used their token yet' : 'students have not used their tokens yet' ?>
                    </span>
                  </div>
                </div>

                <div class="token-summary-actions">
                  <?php if ($pendingCount > 0): ?>
                    <form method="POST" action="send_token_reminder.php" style="margin:0;"
                      onsubmit="return confirm('Send reminder emails to all <?= intval($pendingCount) ?> pending students?');">
                      <input type="hidden" name="action" value="bulk">
                      <button type="submit" class="btn-bulk-reminder">
                        <i class="fas fa-paper-plane"></i>
                        Send Bulk Reminder
                        <span class="badge-count"><?= intval($pendingCount) ?></span>
                      </button>
                    </form>
                  <?php endif; ?>
                  <a href="email_log.php" class="btn-email-log">
                    <i class="fas fa-history"></i>
                    Email Log
                  </a>
                </div>
              </div>
              <!-- End Pending Token Summary -->

              <div class="card card-primary">

                <div class="card-header">

                  <h5 class="card-title font-weight-bold"> <i class="fas fa-id-card"></i> Registration Tokens</h5>

                  <div class="card-tools">

                  </div>

                </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>Admission No.</th>

                        <th>Fullname</th>

                        <th>Class</th>

                        <th>Token</th>

                        <th>Token For</th>

                        <th>School Type</th>

                        <th>Status</th>

                        <th>Email</th>

                        <th>Action</th>

                      </tr>

                    </thead>

                    <tbody>

                      <?php



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



                      $sql = "SELECT * FROM registration_tokens";

                      $conditions = [];

                      if (!empty($classFilter)) {

                        $conditions[] = "class = '" . mysqli_real_escape_string($con, $classFilter) . "'";

                      }

                      if (!empty($conditions)) {

                        $sql .= " WHERE " . implode(" AND ", $conditions);

                      }

                      $sql .= " ORDER BY id DESC";

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





                      $cnt = 1;

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

                        ?>

                        <tr>

                          <td><?= htmlentities($cnt); ?></td>

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

                          <td><?= htmlentities($row['student_name']); ?></td>

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

                          <td><?= htmlentities($row['token']); ?></td>

                          <td><?= htmlentities($row['token_for']); ?></td>

                          <td><?= htmlentities($row['school_type']); ?></td>

                          <td><?= htmlentities($row['token_status']); ?></td>

                          <td><?= htmlentities($row['email']); ?></td>

                          <td>
                            <?php if ($row['token_status'] === 'pending'): ?>
                              <form method="POST" action="send_token_reminder.php" style="display:inline;">
                                <input type="hidden" name="action" value="single">
                                <input type="hidden" name="token_id" value="<?= intval($row['id']); ?>">
                                <button type="submit" class="btn btn-sm btn-info">
                                  <i class="fas fa-envelope"></i> Send Reminder
                                </button>
                              </form>
                            <?php endif; ?>
                          </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_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>

</body>



</html>