<?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 successfully.');

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

                } else {

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

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

                }

            } else {

                flash_alert('Error preparing delete query.');

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

            }

        } else {

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

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

        }

        mysqli_stmt_close($stmt);

    } else {

        flash_alert('Error preparing backup query.');

        header('Location: graduated_students.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-graduated"></i>

                                    </div>

                                    <div>

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

                                            Student Information Management

                                            <span class="premium-subtitle text-secondary">Graduated Students</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">Manage Students</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 (Graduated Students Only)</h5>

                                    <div class="card-tools">

                                    </div>

                                </div>



                                <div class="card-body">

                                    <!-- Date filter form -->

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

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

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

                                                <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()) {

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

                                                    }

                                                    ?>

                                                </select>

                                            </div>



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

                                                <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-4 align-self-end">

                                                <button type="button" class="btn btn-success"
                                                    onclick="downloadFilteredPDF()"><i class="fas fa-download"></i>
                                                    Download</button>

                                            </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>Session Admitted</th>

                                                <th>Session Graduated</th>

                                                <th>Action</th>

                                            </tr>

                                        </thead>

                                        <tbody>

                                            <?php $query = mysqli_query($con, "select * from students where status = 3 ORDER BY graduated_session DESC");

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

                                                    <td><?php echo htmlentities($row['graduated_session']); ?></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="graduated_students.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>



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

                            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>