<?php
include('session_validator.php');
// view_attendance.php

// Include the database connection file
include("includes/db.php");

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate and sanitize input
    $examType = mysqli_real_escape_string($conn, $_POST['exam_type']);
    $classId = mysqli_real_escape_string($conn, $_POST['class_id']);

    // Fetch attendance details based on exam type and class
    $fetchAttendanceQuery = "SELECT students.student_id, students.name, students.symbol_no, attendance.atten_day
                            FROM students
                            LEFT JOIN attendance ON students.student_id = attendance.std_id
                            WHERE attendance.exam_type = ? AND students.class = ?
                            ORDER BY students.symbol_no";
    $stmt = $conn->prepare($fetchAttendanceQuery);
    $stmt->bind_param('si', $examType, $classId);
    $stmt->execute();
    $result = $stmt->get_result();

    // Store attendance data in an associative array
    $attendanceData = array();
    while ($row = $result->fetch_assoc()) {
        $attendanceData[$row['student_id']] = $row['atten_day'];
    }

    // Close the prepared statement
    $stmt->close();
}

// Close the database connection
mysqli_close($conn);
?>

<!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>View Attendance</title>
    <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/tablestyle.css" type="text/css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="js/modernizr/modernizr.min.js"></script>
    <script>
        function printTable() {
            var printWindow = window.open('', '_blank');
            printWindow.document.write('<html><head><title>MMSS, Class Wise Attendance</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 = '90%';

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

<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <?php include('includes/leftbar.php'); ?>
            <div class="main-page">
                <div class="container-fluid">
                    <!-- Your existing HTML content -->

                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5>View/Edit Attendance</h5>
                                        </div>
                                    </div>
                                    <div class="panel-body">

                                        <form method="POST" action="">
                                            <div class="form-group col-md-4">
                                                <label for="exam_type">Exam Type</label>
                                                <select id="exam_type" name="exam_type" class="form-control" required>
                                                    <option value="">Select Exam Type</option>
                                                    <!-- Options filled dynamically from the database -->
                                                    <?php
                                                    include("includes/db.php");
                                                    $fetchExamTypesQuery = "SELECT id, exam_type FROM examination_type";
                                                    $examTypesResult = $conn->query($fetchExamTypesQuery);
                                                    if ($examTypesResult->num_rows > 0) {
                                                        while ($row = $examTypesResult->fetch_assoc()) {
                                                            $selected = ($row['id'] == $examType) ? 'selected' : '';
                                                            echo '<option value="' . $row['id'] . '" ' . $selected . '>' . $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("includes/db.php");
                                                    $query = "SELECT class_id, class_name, section FROM classes";
                                                    $result = $conn->query($query);
                                                    while ($row = $result->fetch_assoc()) {
                                                        $selected = ($row['class_id'] == $classId) ? 'selected' : '';
                                                        echo "<option value='" . $row['class_id'] . "' " . $selected . ">" . $row['class_name'] . " - " . $row['section'] . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div>
                                                <button type="submit" class="btn btn-primary">Fetch Attendance</button>
                                            </div>
                                        </form>

            <?php if (isset($attendanceData)) : ?>
                <form method="POST" action="update_attendance.php">
                    <input type="hidden" name="exam_type" value="<?= $examType ?>">
                    <input type="hidden" name="class_id" value="<?= $classId ?>">
                    <div id="customers">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Student ID</th>
                                    <th>Symbol No</th>
                                    <th>Student Name</th>
                                    <th>Attendance Day</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($attendanceData as $studentId => $attenDay) : ?>
                                    <tr>
                                        <td><?= $studentId ?></td>
                                        <td><?= getStudentsym($studentId) ?></td>
                                        <td><?= getStudentName($studentId) ?></td>
                                        <td>
                                            <input type="text" name="attendance[<?= $studentId ?>][atten_day]" class="form-control" value="<?= $attenDay ?>">
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <button type="submit" name="submit" class="btn btn-primary">Update Attendance</button>
                </form>
                <button onclick="printTable()">Print Table</button>
            <?php endif; ?>

       </div>
                         </div>
                     </div>
                 </div>
             </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>
</body>

</html>


<?php
// Function to get student name based on student ID
function getStudentName($studentId)
{
    include("includes/db.php");
    $query = "SELECT name FROM students WHERE student_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $studentId);
    $stmt->execute();
    $stmt->bind_result($studentName);
    $stmt->fetch();
    $stmt->close();
    return $studentName;
}
// Function to get student name based on student ID
function getStudentsym($studentId)
{
    include("includes/db.php");
    $query = "SELECT symbol_no FROM students WHERE student_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $studentId);
    $stmt->execute();
    $stmt->bind_result($symbolno);
    $stmt->fetch();
    $stmt->close();
    return $symbolno;
}
?>
