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

        } else {

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

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

        }

      } else {

        flash_alert('Error preparing delete query.');

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

      }

    } else {

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

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

    }

    mysqli_stmt_close($stmt);

  } else {

    flash_alert('Error preparing backup query.');

    header('Location: studentlist11.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/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-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="dashboard2.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="add_student1.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="studentlist1.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>Registration No.</th>

                        <th>Fullname</th>

                        <th>Class </th>

                        <th>Arm </th>

                        <th>School Type </th>

                        <th> Payment Status </th>

                        <th> Amount Paid</th>

                        <th>Action</th>

                      </tr>

                    </thead>

                    <tbody>

                      <?php

                      function smartRoundToThousand($value)
                      {

                        $remainder = $value % 1000;

                        return ($remainder > 100) ? ceil($value / 1000) * 1000 : floor($value / 1000) * 1000;

                      }



                      // Fetch all students with sum of payments
                      
                      $sql = "

      SELECT s.*, COALESCE(SUM(p.amount), 0) AS total_paid

      FROM students s

      LEFT JOIN payment p 

        ON p.student_id = s.id 

       AND p.pay_for = 'School Fees (New Student)'

       AND p.status = 'Approved'

      WHERE s.status IN (2, 4)

    ";



                      // Optional filters (if you want to keep them)
                      
                      if (!empty($classFilter)) {

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

                      }

                      if (!empty($armFilter)) {

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

                      }

                      if (!empty($streamFilter)) {

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

                      }

                      if (!empty($scholarshipFilter)) {

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

                      }



                      $sql .= " GROUP BY s.id ORDER BY s.class ASC";



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

                      if (!$query) {

                        echo "<tr><td colspan='8' class='text-center text-danger'>DB error: " . mysqli_error($con) . "</td></tr>";

                        exit();

                      }



                      $cnt = 1;

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

                        $studentClass = mysqli_real_escape_string($con, $row['class']);

                        $studentStream = mysqli_real_escape_string($con, $row['stream']);

                        $total_paid = $row['total_paid'];



                        // Query fee amount for this student's class and stream
                      
                        $feeQuery = mysqli_query($con, "

        SELECT amount FROM fees

        WHERE class = '$studentClass' 

          AND stream = '$studentStream' 

          AND student_type = 'New' 

          AND name = 'School Fees (New Student)' 

        LIMIT 1

      ");



                        if ($feeQuery && mysqli_num_rows($feeQuery) > 0) {

                          $feeRow = mysqli_fetch_assoc($feeQuery);

                          $totalFee = $feeRow['amount'];

                        } else {

                          $totalFee = 0; // No fee found, assume 0 or handle differently
                      
                        }



                        // Calculate acceptance fee threshold (adjust formula as needed)
                      
                        $acceptanceRatio = 30000 / 190000; // Your ratio
                      
                        $rawAcceptance = $acceptanceRatio * $totalFee;

                        $acceptanceFee = smartRoundToThousand($rawAcceptance);



                        // Determine payment status
                      
                        if ($totalFee == 0) {

                          $payment_status = '<span class="badge bg-secondary">Fee Not Set</span>';

                        } elseif ($total_paid >= $totalFee) {

                          $payment_status = '<span class="badge bg-success">Fully Paid</span>';

                        } elseif ($total_paid >= $acceptanceFee && $total_paid < $totalFee) {

                          $payment_status = '<span class="badge bg-warning">Acceptance Fees Paid</span>';

                        } else {

                          $payment_status = '<span class="badge bg-danger">Not Paid</span>';

                        }

                        ?>

                        <tr>

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

                          <td><?php echo htmlentities($row['studentRegNo']); ?></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><?php echo $payment_status; ?></td>

                          <td>₦<?php echo number_format($row['total_paid'], 2); ?></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>

                          </td>

                        </tr>

                        <?php

                        $cnt++;

                      }

                      ?>

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

    });

    $(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_student1.php",

          type: "post",

          data: {

            edit_id: edit_id

          },

          success: function (data) {

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

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

          type: "post",

          data: {

            edit_id2: edit_id2

          },

          success: function (data) {

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

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