<?php
include('session_validator.php');
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SRMS Admin Generate Admit Card</title>
    <!-- Include necessary stylesheets -->
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
    <link rel="stylesheet" href="css/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <link rel="stylesheet" href="css/admitcard.css" media="screen">

    <!-- Include DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css">

    <!-- Include jQuery -->
    <script src="js/jquery/jquery-2.2.4.min.js"></script>

    <!-- Include DataTables JS -->
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script>


    <style>
        /* Additional styling for the "Print All Admit Cards" button */
        .print-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
        }

        /* Style for the buttons */
        .action-btn {
            margin-right: 10px;
        }
    </style>
</head>

<body class="top-navbar-fixed">

    <div class="main-wrapper">
        <!-- ========== TOP NAVBAR ========== -->
        <?php include('includes/topbar.php'); ?>
        <!-- ========== WRAPPER FOR BOTH SIDEBARS & MAIN CONTENT ========== -->
        <div class="content-wrapper">
            <div class="content-container">
                <?php include('includes/leftbar.php'); ?>
                <div class="main-page">
                    <div class="container-fluid">
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title">Generate Symbol Numbers</h2>
                            </div>
                        </div>
                        <div class="row breadcrumb-div">
                            <div class="col-md-6">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li> Exam</li>
                                    <li class="">Symbol Numbers</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <section class="section">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="panel">
                                        <div class="panel-heading">
                                            <div class="panel-title">
                                                <h5>Generate Symbol Numbers</h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">

                                            <!-- Step 1: Create HTML form to select exam type and class -->
                                            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                                                <div class="form-row">
                                                    <div class="form-group col-md-4">
                                                        <label for="exam_type">Select Exam Type:</label>
                                                        <select id="exam_type" name="exam_type" class="form-control" required>
                                                            <option>Select Exam Type</option>
                                                            <!-- Populate exam types from the database -->
                                                            <?php
                                                            // Include your database connection code here
                                                            include('includes/db.php');
                                                            // Fetch exam types from the database
                                                            $fetchExamTypesQuery = "SELECT id, exam_type FROM examination_type";
                                                            $examTypesResult = $conn->query($fetchExamTypesQuery);

                                                            if ($examTypesResult->num_rows > 0) {
                                                                while ($row = $examTypesResult->fetch_assoc()) {
                                                                    echo '<option value="' . $row['id'] . '">' . $row['exam_type'] . '</option>';
                                                                }
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>

                                                    <div class="form-group col-md-3">
                                                        <label for="class_id">Select Class:</label>
                                                        <select id="class_id" name="class_id[]" class="form-control" required>
                                                            <option>Select Class</option>
                                                            <!-- Populate classes from the database -->
                                                            <?php
                                                            // Fetch classes from the database
                                                            $fetchClassesQuery = "SELECT class_id, class_name, section FROM classes";
                                                            $classesResult = $conn->query($fetchClassesQuery);

                                                            if ($classesResult->num_rows > 0) {
                                                                while ($row = $classesResult->fetch_assoc()) {
                                                                    echo '<option value="' . $row['class_id'] . '">' . $row['class_name'] . '-' . $row['section'] . '</option>';
                                                                }
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                <button type="submit" name="submit" class="btn btn-primary action-btn">Submit</button>
                                            </form>

                                            <!-- Step 2: Display students table with S.N., Regd no, Name, and empty input field for symbol number -->
                                            <table id="studentsTable" class="table">
                                                <!-- Step 5: Display buttons -->

                                                <button type="button" id="displayModalBtn" class="btn btn-primary action-btn">Create Symbol Number</button>
                                                <button type="button" id="assignSymbolBtn" class="btn btn-primary action-btn">Assign Symbol Numbers</button>
                                                <thead>
                                                    <tr>
                                                        <th>S.N.</th>
                                                        <th>IEMIS No</th>
                                                        <th>Registration No</th>
                                                        <th>Name</th>
                                                        <th>Symbol Number</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    // Fetch and display students based on selected exam type and classes
                                                    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
                                                        $examTypeId = $_POST['exam_type'];
                                                        $selectedClasses = $_POST['class_id'];

                                                        // Fetch students for each selected class
                                                        foreach ($selectedClasses as $classId) {
                                                            $fetchStudentsQuery = "SELECT student_id, regd_id,registration_no, name FROM students WHERE class_id = $classId";
                                                            $studentsResult = $conn->query($fetchStudentsQuery);

                                                            if ($studentsResult->num_rows > 0) {
                                                                $serialNumber = 1;

                                                                while ($row = $studentsResult->fetch_assoc()) {
                                                                    echo '<tr>';
                                                                    echo '<td>' . $serialNumber . '</td>';
                                                                    echo '<td>' . $row['regd_id'] . '</td>';
                                                                    echo '<td>' . $row['registration_no'] . '</td>';
                                                                    echo '<td>' . $row['name'] . '</td>';
                                                                    echo '<td><input style="color:Red; font-weight:bold" class="form-control" type="text" name="symbol_number[' . $row['student_id'] . ']" /></td>';
                                                                    echo '</tr>';

                                                                    $serialNumber++;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>

                                            <!-- Step 4: After submitting auto-create symbol numbers -->
                                            <div class="modal fade" id="symbolNumberModal" tabindex="-1" role="dialog" aria-labelledby="symbolNumberModalLabel">
                                                <div class="modal-dialog" role="document">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title" id="symbolNumberModalLabel">Create Symbol Numbers</h5>
                                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                <span aria-hidden="true">&times;</span>
                                                            </button>
                                                        </div>
                                                        <div class="modal-body">
                                                            <!-- Step 3: Allow the user to define symbol number and the difference between each symbol number -->
                                                            <div class="form-group">
                                                                <label for="symbol_start">Start Symbol Number:</label>
                                                                <input type="text" id="symbol_start" class="form-control" required>
                                                            </div>

                                                            <div class="form-group">
                                                                <label for="symbol_difference">Symbol Number Difference:</label>
                                                                <input type="text" id="symbol_difference" class="form-control" required>
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                            <!-- Add a button to assign symbol numbers -->
                                                            <button type="button" id="assignSymbolNumbersBtn" class="btn btn-primary">Assign</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Include necessary scripts -->
<script src="js/jquery/jquery-2.2.4.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>

<script>
    $(document).ready(function () {
        // Add an event listener for displaying the modal form
        $("#displayModalBtn").click(function () {
            // Show the modal
            $("#symbolNumberModal").modal("show");
        });

        // Add an event listener for the "Assign" button in the modal
        $("#assignSymbolNumbersBtn").click(function () {
            // Collect symbol start number and difference
            var symbolStart = $("#symbol_start").val();
            var symbolDifference = $("#symbol_difference").val();

            // Validate input
            if (symbolStart === "" || symbolDifference === "") {
                alert("Please enter both start symbol number and symbol number difference.");
                return;
            }

            // Parse symbolStart and symbolDifference to integers
            symbolStart = parseInt(symbolStart);
            symbolDifference = parseInt(symbolDifference);

            // Counter for auto-generating symbol numbers
            var symbolCounter = symbolStart;

            // Iterate through each input field containing symbol numbers
            $("input[name^='symbol_number']").each(function () {
                // Update the input field with the current symbol number
                $(this).val(symbolCounter);

                // Increment symbolCounter by the symbol difference
                symbolCounter += symbolDifference;
            });

            // Show confirmation dialog before final assignment
            var confirmAssign = confirm("Are you sure you want to assign these symbol numbers?");
            if (confirmAssign) {
                // Close the modal
                $("#symbolNumberModal").modal("hide");

                // Display success message
                alert("Symbol numbers assigned successfully");
            } else {
                // User canceled the assignment
                alert("Symbol numbers assignment canceled");
            }
        });

        // Add an event listener for assigning symbol numbers
        $("#assignSymbolBtn").click(function () {
            // Show confirmation dialog before initiating the assignment
            var confirmInitiate = confirm("This will initiate the symbol numbers assignment process. Are you sure?");
            if (confirmInitiate) {
                // Get the selected exam type, classes, and symbol numbers
                var examType = $("#exam_type").val();
                var selectedClasses = $("#class_id").val();

                var symbolNumbers = {};
                $("input[name^='symbol_number']").each(function () {
                    var studentId = $(this).attr("name").match(/\[(\d+)\]/)[1];
                    var symbolNumber = $(this).val();
                    symbolNumbers[studentId] = symbolNumber;
                });

                // Send the data to the server using AJAX
                $.ajax({
                    type: "POST",
                    url: "assign_symbol_numbers.php", // Replace with the actual server-side script
                    data: {
                        examType: examType,
                        selectedClasses: selectedClasses,
                        symbolNumbers: symbolNumbers
                    },
                    success: function (response) {
                        // Handle the response from the server
                        console.log(response);

                        // Display success message
                        alert("Symbol numbers assigned successfully");
                    },
                    error: function (error) {
                        // Handle errors
                        console.error(error);

                        // Display error message
                        alert("Error assigning symbol numbers. Please try again.");
                    }
                });
            } else {
                // User canceled the initiation
                alert("Symbol numbers assignment initiation canceled");
            }
        });

        // Initialize DataTable without pagination
        $('#studentsTable').DataTable({
            paging: false,
            ordering: true, // Enable sorting
            searching: false
        });
    });
</script>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    </div>

    <!-- Include necessary scripts -->
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/iscroll/iscroll.js"></script>
    <script src="js/prism/prism.js"></script>
    <script src="js/waypoint/waypoints.min.js"></script>
    <script src="js/counterUp/jquery.counterup.min.js"></script>
    <script src="js/toastr/toastr.min.js"></script>
    <script src="js/icheck/icheck.min.js"></script>
    <script src="js/main.js"></script>
    <script src="js/production-chart.js"></script>
    <script src="js/traffic-chart.js"></script>
    <script src="js/task-list.js"></script>
</body>

</html>
