<?php
// Include database connection code
include("includes/db.php");


// Main code
if (isset($_GET['class_id'])) {
    $classId = $_GET['class_id'];

    // Add pagination
    $page = isset($_GET['page']) ? $_GET['page'] : 1;
    $resultsPerPage = 10;
    $startFrom = ($page - 1) * $resultsPerPage;

    // Query distinct exam types for the selected class
    $examTypeQuery = "SELECT DISTINCT exam_type FROM marks WHERE class_id = $classId";
    $examTypeResult = $conn->query($examTypeQuery);

    // Query students, subjects, and marks for the specific class with pagination
    $query = "SELECT students.student_id AS student_id, students.name AS student_name,
            subjects.subject_code, subjects.subject_name, subjects.theory_full_marks, 
            subjects.internal_full_marks, subjects.theory_credit_hour, subjects.internal_credit_hour,
            marks.marks, int_marks.internal_marks AS internal_marks,
            classes.class_name, classes.section, marks.exam_type, int_marks.exam_type AS intexam_type
            FROM students
            INNER JOIN marks ON students.student_id = marks.student_id AND marks.class_id = $classId
            INNER JOIN int_marks ON students.student_id = int_marks.student_id AND marks.subject_id = int_marks.subject_id
            INNER JOIN classes ON marks.class_id = classes.Class_id
            INNER JOIN subjects ON marks.subject_id = subjects.id
            WHERE marks.class_id = $classId";

    // Check if exam_type is set, then filter by exam_type for both marks and int_marks
    if (isset($_GET['exam_type'])) {
        $examType = $conn->real_escape_string($_GET['exam_type']);
        $query .= " AND marks.exam_type = '$examType'";
    }

    $query .= " ORDER BY students.Student_id, subjects.id, marks.exam_type LIMIT $startFrom, $resultsPerPage";

    $result = $conn->query($query);

    // Prepare data for display
    $ledger = [];
    $currentStudentId = null;
    $totalMarks = 0;
    $TotalWGP = 0;
    $TotalCH = 0; // Initialize total credit hour

    while ($row = $result->fetch_assoc()) {
        $studentId = $row['student_id'];

        if ($studentId != $currentStudentId) {
            // Save total marks, Total WGP, and Total CH for the previous student and reset total marks
            if ($currentStudentId !== null) {
                $currentStudentData['total_marks'] = $totalMarks;
                $currentStudentData['totalwgp'] = $TotalWGP;
                $currentStudentData['totalch'] = $TotalCH; // Save total credit hours
                $ledger[] = $currentStudentData;
            }

            // Initialize data for the new student
            $currentStudentId = $studentId;
            $currentStudentData = [
                'sn' => count($ledger) + 1,
                'name' => $row['student_name'],
                'subjects' => [],
                'total_marks' => 0,
                'totalwgp' => 0,
                'totalch' => 0 // Initialize total credit hours for the new student
            ];

            // Reset total marks, Total WGP, and Total CH for the new student
            $totalMarks = 0;
            $TotalWGP = 0;
            $TotalCH = 0; // Reset total credit hours
        }

        // Add subject marks for the current student
        $currentStudentData['subjects'][] = [
            'subject' => $row['subject_name'],
            'subject_code' => $row['subject_code'],
            'theory_marks' => $row['marks'],
            'internal_marks' => $row['internal_marks'],
            'full_marks_theory' => $row['theory_full_marks'],
            'full_marks_internal' => $row['internal_full_marks'],
            'creditHour_theory' => $row['theory_credit_hour'],
            'creditHour_internal' => $row['internal_credit_hour']
        ];

        // Calculate total marks for the current student
        $totalMarks += $row['marks'];

        // Calculate Total WGP for the current student
        
        // Increment total credit hour for each subject
        $TotalCH += $row['theory_credit_hour'] + $row['internal_credit_hour'];
    }

    $TotalCH = ($TotalCH == 0) ? 1 : $TotalCH;

    // Add the last student's total marks, Total WGP, and Total CH to the ledger
    if ($currentStudentId !== null) {
        $currentStudentData['total_marks'] = $totalMarks;
        $currentStudentData['totalwgp'] = $TotalWGP;
        $currentStudentData['totalch'] = $TotalCH;
        $ledger[] = $currentStudentData;
    }

    // Pagination links
    $totalRecordsQuery = "SELECT COUNT(DISTINCT students.student_id) AS count FROM students
                            INNER JOIN marks ON students.student_id = marks.student_id
                            INNER JOIN int_marks ON students.student_id = int_marks.student_id AND marks.subject_id = int_marks.subject_id
                            INNER JOIN classes ON marks.class_id = classes.Class_id
                            INNER JOIN subjects ON marks.subject_id = subjects.id
                            WHERE marks.class_id = $classId";
    // Check if exam_type is set, then filter by exam_type
    if (isset($_GET['exam_type'])) {
        $examType = $conn->real_escape_string($_GET['exam_type']);
        $totalRecordsQuery .= " AND marks.exam_type = '$examType'";
    }
    $totalRecordsResult = $conn->query($totalRecordsQuery);
    $totalRecords = $totalRecordsResult->fetch_assoc()['count'];
    $totalPages = ceil($totalRecords / $resultsPerPage);

    $examtype1 = '';
    if (isset($_GET['exam_type'])) {
        $examType = $conn->real_escape_string($_GET['exam_type']);
        $examquery = "SELECT * FROM examination_type WHERE id = $examType";
        $examresult = $conn->query($examquery);
        $examDetails = $examresult->fetch_assoc();
        $examtype1 = $examDetails['exam_type'];
        $examyear = $examDetails['exm_year'];
    }

    echo '<div class="pagination">';
    for ($i = 1; $i <= $totalPages; $i++) {
        echo '<a href="?class_id=' . $classId . '&exam_type=' . $examType . '&page=' . $i . '">' . $i . '</a>';
    }
    echo '</div>';
}

?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Marks Obtained Ledger</title>
    <style>
        /* Add your CSS styles here */
        table {
            width: 100%;
            border-collapse: collapse;
        }

        table,
        th,
        td {
            border: 1px solid black;
            padding: 2px;
            text-align: left;
            margin-left: '';
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 10px;
        }

        .pagination a {
            padding: 5px 10px;
            margin: 0 5px;
            border: 1px solid #ddd;
            text-decoration: none;
            color: #333;
        }
    </style>
</head>

<body>

    <h2>Select Class</h2>
    <form action="ledgerthpr.php" method="get">
        <!-- Add a dropdown for exam_type -->
        <label for="exam_type">Select Exam Type:</label>
        <select name="exam_type" id="exam_type" class="form-control" style="width: 250px;">
            <option value="">Select Exam</option>
            <?php
            $queryexam = "SELECT id, exm_year, exam_type FROM examination_type";
            $resultexam = $conn->query($queryexam);

            while ($row = $resultexam->fetch_assoc()) {
                $selected = ($_GET['exam_type'] == $row['id']) ? 'selected' : '';
                echo "<option value='" . $row['id'] . "' $selected>" . $row['exm_year'] . " - " . $row['exam_type'] . "</option>";
            }
            ?>
        </select>
        <br>

        <label for="class_id">Select Class:</label>
        <select name="class_id" id="class_id" class="form-control" style="width: 250px;">
            <!-- Populate dropdown options dynamically from your database -->
            <?php
            // Query classes from the database
            $classQuery = "SELECT class_id, class_name, section FROM classes";
            $classResult = $conn->query($classQuery);

            while ($row = $classResult->fetch_assoc()) {
                $selected = ($_GET['class_id'] == $row['class_id']) ? 'selected' : '';
                echo "<option value='" . $row['class_id'] . "' $selected>" . $row['class_name'] . " - " . $row['section'] . "</option>";
            }

            // Close the database connection
            $conn->close();
            ?>
        </select>
        <br>
        <button type="submit" class="btn btn-primary">Show Ledger</button>
    </form>

    <div>
        <?php if (isset($ledger) && !empty($ledger)) : ?>
            <h2>Marks Obtained Ledger for Class <?php  ?></h2>
            <h3><?php echo $examtype1 ?></h3>
            <table>
                <thead>
                    <tr>
                        <th rowspan="2">S.N.</th>
                        <th width="200px" rowspan="2">Name</th>

                        <?php foreach ($ledger[0]['subjects'] as $subject) : ?>
                            <th colspan="3">
                                <center>
                                    <?= $subject['subject'] . '<br>[' . $subject['subject_code'] . ']' . '<br>[Full marks:' . $subject['full_marks_theory'] . '/' . $subject['full_marks_internal'] . ']' . '<br>[CH:' . $subject['creditHour_theory'] . '/' . $subject['creditHour_internal'] . ']' ?>
                                </center>
                            </th>
                        <?php endforeach; ?>
                        <th rowspan="2">Total</th>
  
                    </tr>
                    <tr>
                        <?php foreach ($ledger[0]['subjects'] as $subject) : ?>
                            <th> Obt. Marks [TH]</th>
                            <th> Obt. Marks [IN]</th>
                            <th>Total</th>
                        <?php endforeach; ?>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($ledger as $student) : ?>
                        <tr>
                            <td><?= $student['sn'] ?></td>
                            <td style="width: 200px;"><?= $student['name'] ?></td>
                            <?php foreach ($student['subjects'] as $subject) : ?>
                                <td><?= $subject['theory_marks'] ?></td>

                                <td><?= $subject['internal_marks'] ?></td>
                                <td> <?= $subject['theory_marks'] +  $subject['internal_marks']?>   </td>

                      
                        
                            <?php endforeach; ?>
                            <td><?= $student['total_marks'] ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</body>

</html>
