<?php
include("includes/db.php");


// Initialize variables
$marksResult = null;

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit"])) {
    // Collect data from the form
    // $examTypeId = $conn->real_escape_string($_POST["exam_type_id"]);
    $classId = $conn->real_escape_string($_POST["class_id"]);
    $subjectId = $conn->real_escape_string($_POST["subject_id"]);

    // Fetch marks data from the database based on the selected criteria
    $marksQuery = "SELECT students.name, students.symbol_no, students.regd_id, int_marks.internal_marks
                   FROM int_marks
                   INNER JOIN students ON int_marks.student_id = students.student_id
                Where int_marks.class_id = '$classId'
                   AND int_marks.subject_id = '$subjectId' ORDER by students.symbol_no ";
    $marksResult = $conn->query($marksQuery);
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <!-- Meta tags, title, and stylesheets can be added here -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  -->
    <link rel="stylesheet" href="styles.css"> <!-- Include your custom styles here -->
    <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="nepali.datepicker.v4.0.1\css\main.css" media="screen">
    <link rel="stylesheet" href="css\sweet-alert\sweetalert.css" media="screen">
     <link rel="stylesheet" href="css/tablestyle.css" type="text/css">
    <!-- Include jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
           
<script>
function printTable() {
    var printWindow = window.open('', '_blank');
    printWindow.document.write('<html><head><title>Mohanmaya Sec. School, First Term Examination 2080</title>');
    printWindow.document.write('<link rel="stylesheet" href="css/tablestyle.css" type="text/css">');
    printWindow.document.write('</head><body>');
    printWindow.document.write(document.getElementById('customers').outerHTML);
    printWindow.document.write('</body></html>');
    printWindow.document.close();

    printWindow.document.documentElement.style.zoom = '75%';

    // Use setTimeout to ensure styles are applied before printing
    setTimeout(function () {
        printWindow.print();
        printWindow.onafterprint = function () {
            printWindow.close();
        };
    }, 500);
}

    
    </script>

<script>
        $(document).ready(function () {
            // DataTable initialization
            var table = $('#customers').DataTable();

            // // Add print button
            // $('#printBtn').on('click', function () {
            //     window.print();
            // });

            // Add export to Excel button
            $('#exportExcelBtn').on('click', function () {
                var exportData = [];
                table.rows().every(function () {
                    var data = this.data();
                    exportData.push(data);
                });

                // // Sort data alphabetically by student name
                // exportData.sort(function (a, b) {
                //     return a[1].localeCompare(b[1]);
                // });

                // Create worksheet and add data
                var ws = XLSX.utils.json_to_sheet(exportData);

                // Create workbook and add worksheet
                var wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, 'Ledger');

                // Save the workbook
                XLSX.writeFile(wb, 'Mark_export.xlsx');
            });
        });
    </script>
</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">

                    <!-- ========== LEFT SIDEBAR ========== -->
                   <?php include('includes/leftbar.php');?>  
                    <!-- /.left-sidebar -->

                    <div class="main-page">

                     <div class="container-fluid">
                            <div class="row page-title-div">
                                <div class="col-md-6">
                                    <h2 class="title">Subject Marks</h2>
                                
                                </div>
                                
                                <!-- /.col-md-6 text-right -->
                            </div>
                            <!-- /.row -->
                            <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> Ledger </li>
                                        <li class="">Subject Marks</li>
                                    </ul>
                                </div>
                             
                            </div>
                            <!-- /.row -->
                        </div>
                        <div class="container-fluid">
                           
                        <div class="row">
                                    <div class="col-md-12">
                                        <div class="panel">
                                            <div class="panel-heading">
                                                <div class="panel-title">
                                                    <h5>Subject Marks</h5>
                                                </div>
                                            </div>
                                            <div class="panel-body">
        
        <form method="POST" action="">


            <div class="form-row">
                <div class="form-group col-md-3">
                    <label for="exam_type_id">Select Exam Type:</label>
                    <select id="exam_type_id" name="exam_type_id" class="form-control" required>
                        <!-- Populate exam types dynamically from the database -->
                        <?php
                        $examTypeQuery = "SELECT id, exam_type FROM examination_type";
                        $examTypeResult = $conn->query($examTypeQuery);

                        while ($row = $examTypeResult->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 value="">Select Class</option>
                    <?php
                    // Include the database configuration file
                    include("includes/db.php");

                    // Fetch class names from the 'classes' table
                    $query = "SELECT class_id, class_name, section FROM classes";
                    $result = $conn->query($query);

                    // Populate the dropdown with class names and sections
                    while ($row = $result->fetch_assoc()) {
                        echo "<option value='" . $row['class_id'] . "'>" . $row['class_name'] . " - " . $row['section'] . "</option>";
                    }

                    ?>


</select>
                </div>


    <div class="form-group col-md-4">
            <label for="subject_id">Select Subject:</label>
        <select id="subject_id" name="subject_id" class="form-control" required>
            <option value="">Select Subject</option>
        </select>
</div>

                <div class="form-group col-md-2">
                    <button type="submit" name="submit" class="btn btn-primary mt-4">Get Marks</button>
                </div>
            </div>
        </form>
    </div>

        

        <?php  $sn = 1;

        if ($marksResult && $marksResult->num_rows > 0) : ?>
            <!-- Display marks data in a table -->
            
<div class="table-responsive">
                <!-- Options to export to Excel -->
            <div class="mt-4">
    <button id="print-marks-btn" class="btn btn-primary" onclick="printTable()">Print Table</button>
 
                <a href="export_to_excel.php?exam_type_id=<?php echo $examTypeId; ?>&class_id=<?php echo $classId; ?>&subject_id=<?php echo $subjectId; ?>" class="btn btn-success">Export to Excel</a>
            </div>




                <table id="customers" style="border-collapse: collapse; border: 1px solid #000000;">
                   <thead>
        <tr><td colspan='3'><span style='border:none'><b>Mohanmaya Secondary School</b> <br> Birtamode-02, Jhapa<br></span> <br> Subject Marks <b> </b>
        </td>
    </tr>
                            <tr>
                            <th> S.N.</th>
                            <th>Iemis No</th>
                            <th>Symbol No</th>
                            <th>Student Name</th>
                            <th>Marks</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $marksResult->fetch_assoc()) : ?>
                            <tr>
                                <td> <?php echo $sn++ ?></td>
                                <td><?php echo $row['regd_id']; ?></td>
                                <td style="color:Red; font-weight: bold"><?php echo $row['symbol_no']; ?></td>
                                <td><?php echo $row['name']; ?></td>
                                <td><?php echo $row['internal_marks']; ?></td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>


<?php elseif ($marksResult && $marksResult->num_rows === 0) : ?>
            <div class="alert alert-info mt-4">No marks data available for the selected criteria.</div>
        <?php endif; ?>
            
    </div></div></div>
</div>

</div>
   <!-- /.main-wrapper -->
        <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <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/select2/select2.min.js"></script>
        <script src="js/main.js"></script>
<script>
            $(document).ready(function () {
                

                // Event handler for class selection
                $('#class_id').change(function () {
                    var classId = $(this).val();
                    var subjectId = $('#subject_id').val();

                    // Fetch and populate students based on class and subject
                    fetchStudents(classId, subjectId);
                });

                // Event handler for subject selection
                $('#subject_id').change(function () {
                    var subjectId = $(this).val();
                    var classId = $('#class_id').val();

                    // Fetch and populate students based on class and subject
                    fetchStudents(classId, subjectId);
                });
            });
        </script>
        <script>
            document.getElementById("class_id").addEventListener("change", function () {
                var classId = this.value;
                var subjectDropdown = document.getElementById("subject_id");

                subjectDropdown.innerHTML = "<option value=''>Select Subject</option>";

                fetch(`getSubjects.php?class_id=${classId}`)
                    .then(response => response.json())
                    .then(data => {
                        data.forEach(subject => {
                            var option = document.createElement("option");
                            option.value = subject.id;
                            option.textContent = subject.subject_name;
                            subjectDropdown.appendChild(option);
                        });
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            });
        </script>
</body>

</html>