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

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


// Function to calculate GP
function calculateGP($MP)
{
    if ($MP >= 0.9) {
        return '4.0';
    } elseif ($MP >= 0.8) {
        return '3.6';
    } elseif ($MP >= 0.7) {
        return '3.2';
    } elseif ($MP >= 0.6) {
        return '2.8';
    } elseif ($MP >= 0.5) {
        return '2.4';
    } elseif ($MP >= 0.4) {
        return '2.0';
    } elseif ($MP >= 0.35) {
        return '1.6';
    } elseif ($MP >= 0.0001) {
        return '<b><span style="color:#0011ff">NG</b>';
    } else {
        return '<b><span style="color:red">Abs</b>';
    }
}

// Function to get grade
function calculateGrade($MP)
{
    if ($MP >= 0.9) {
        return 'A+';
    } elseif ($MP >= 0.8) {
        return 'A';
    } elseif ($MP >= 0.7) {
        return 'B+';
    } elseif ($MP >= 0.6) {
        return 'B';
    } elseif ($MP >= 0.5) {
        return 'C+';
    } elseif ($MP >= 0.4) {
        return 'C';
    } elseif ($MP >= 0.35) {
        return 'D';
    } elseif ($MP >= 0.0001) {
        return '<b><span style="color:#0011ff">NG</b>';
    } else {
        return '<b><span style="color:red">Abs</b>';
    }
}

if (isset($_GET['class_id']) && is_array($_GET['class_id'])) {
    $classIds = $_GET['class_id'];

    // Construct a comma-separated string for SQL query
    $classIdString = implode(",", $classIds);

    // Query students, subjects, and marks for the selected classes
    $query = "SELECT students.student_id AS student_id, students.name AS student_name,
                studentsub.sub1, studentsub.sub2, studentsub.sub3,
                studentsub.sub4, studentsub.sub5, studentsub.sub6,
                subjects.subject_code, subjects.subject_name,
                subjects.theory_full_marks, subjects.theory_credit_hour,
                COALESCE(marks.marks, '') AS marks,
                classes.class_name,classes.class_id, classes.section

                FROM students

              INNER JOIN classes ON students.Class_id = classes.Class_id
              INNER JOIN studentsub ON students.student_id = studentsub.student_id AND students.Class_id = studentsub.class_id
              INNER JOIN subjects ON studentsub.sub1 = subjects.subject_code OR
                                      studentsub.sub2 = subjects.subject_code OR
                                      studentsub.sub3 = subjects.subject_code OR
                                      studentsub.sub4 = subjects.subject_code OR
                                      studentsub.sub5 = subjects.subject_code OR
                                      studentsub.sub6 = subjects.subject_code
              LEFT JOIN marks ON students.student_id = marks.student_id AND students.Class_id = marks.class_id AND subjects.id = marks.subject_id

              WHERE students.Class_id IN ($classIdString)
              ORDER BY students.Student_id, subjects.id";

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

    // Prepare data for display
    $ledger = [];
    $currentStudentId = null;
    $currentStudentData = null;
    $totalMarks = 0;
    $TotalWGP = 0;
    $TotalCH = 0;
    $totalwgp = 0;
    $totalch =0;
    $NGCount = 0;
    $classNames = [];

    while ($row = $result->fetch_assoc()) {
        $studentId = $row['student_id'];
        $subjectName = $row['subject_name'];
        $subjectcode = $row['subject_code'];
        $marks = $row['marks'];
        $creditHour = $row['theory_credit_hour'];
        $theoryFullMarks = $row['theory_full_marks'];
        $classname1 = $row['class_name'];
        $section1 = $row['section'];
        $Legclass = $classname1 . '-' . $section1;

        // Collect unique class and section names
        $classKey = $row['class_id'];
        if (!isset($classNames[$classKey])) {
            $classNames[$classKey] = $classname1 . ' - ' . $section1;
        }

        if ($studentId != $currentStudentId) {
            // Save total marks for the previous student and reset total marks
            if ($currentStudentId !== null) {
                $currentStudentData['total_marks'] = $totalMarks;
                $currentStudentData['totalwgp'] = $TotalWGP;
                $currentStudentData['totalch'] = $TotalCH;
                $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,

                'class_names' => array_values($classNames),
            ];

            
            // Reset total marks for the new student
            $totalMarks = 0;
            $TotalWGP = 0;
            $TotalCH = 0;

        }

        // Check if the subject is already added for the current student
        $existingSubject = array_filter(
            $currentStudentData['subjects'],
            function ($subj) use ($subjectcode) {
                return $subj['subject_code'] === $subjectcode;
            }
        );

        // Add subject only if it's not already added
        if (empty($existingSubject)) {
            // Add subject marks for the current student
            $currentStudentData['subjects'][] = [
                'subject_code' => $subjectcode,
                'subject_name' => $subjectName,
                'credit_hour' => $creditHour,
                'theory_full_marks' => $theoryFullMarks,
                'marks' => $marks,
            ];

            // Calculate GP and WGP for the current subject
            $Obtmarks = $marks;
            $fullmarks = $theoryFullMarks;
            $CH = $creditHour;

            // Explicitly cast to float to avoid non-numeric value warning
            $MP = is_numeric($fullmarks) && $fullmarks > 0 ? (float)$Obtmarks / (float)$fullmarks : 0;

            $grade = calculateGrade($MP);
            $GP = calculateGP($MP);

            if ($MP < 0.35 || $grade === 'NG'|| $GP === 'Abs') {
                // If NG, GP is blank, or MP < 0.35, set WGP to 0
                $WGP = 0;
                // $TotalWGP = 0;
                // $TotalCH = 0;

            } else {
                $WGP = $GP * $CH;
            }

            // Add GP and WGP to the running totals for the student
            $TotalWGP += $WGP;
            $TotalCH += $CH;
        }

        // Calculate total marks for the current student
        $totalMarks += is_numeric($marks) ? $marks : 0;
    }

    // Add the last student's total marks to the ledger
    if ($currentStudentId !== null) {
        $currentStudentData['total_marks'] = $totalMarks;
        $currentStudentData['totalwgp'] = $TotalWGP;
       
        $ledger[] = $currentStudentData;
    }
}
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="https://cdn.rawgit.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.4/xlsx.full.min.js"></script>

           
    <script src="js/multiselect-dropdown.js"></script>

  <link rel="stylesheet" href="css/tablestyle.css" type="text/css">
          <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" >
        <script src="js/modernizr/modernizr.min.js"></script>
    <title>Marks Obtained Ledger</title>
    
    
    <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, 'ledger_export.xlsx');
            });
        });
    </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>
    
</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">Full Ledger</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> Result </li>
                                        <li class="">Full Ledger</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>Full Ledger</h5>
                                                </div>
                                            </div>
                                            <div class="panel-body">
            <form action="fullledger.php" method="get">
                <div>
                    <label for="class_id">Select Class:</label>
                    <select name="class_id[]" id="class_id" class="form-control" style="width: 450px;" multiple>
                        <!-- Populate dropdown options dynamically from your database -->
                        <?php
                        // Include database connection code
                        include("includes/db.php");

                        // Query classes from the database
                        $classQuery = "SELECT class_id, class_name, section FROM classes";
                        $classResult = $conn->query($classQuery);

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

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

            <div class="container">
                <?php if (isset($ledger) && !empty($ledger)) : ?>
                    <h3>Ledger for Classes <?php echo implode(', ', $currentStudentData['class_names']); ?></h3>
                     <button id="exportExcelBtn" class="btn btn-success">Export to Excel</button>
            <button onclick="printTable()">Print Table</button>
            
                    <table id="customers" style="border-collapse: collapse; border: 1px solid #000000;">
    <thead>
        <tr><td colspan='30'><span style='border:none'><b>Mohanmaya Secondary School</b> <br> Birtamode-02, Jhapa<br> Third Terminal Examination Legder 2080 Poush<br>Ledger for Class <b> <?php echo implode(', ', $currentStudentData['class_names']); ?></b></td></tr>
        <tr>
            <th rowspan="2">S.N.</th>
            <th width="150px" rowspan="2">Name</th>
            <?php foreach ($ledger[0]['subjects'] as $subject) : ?>
                <th colspan="4">
                    <center><?= $subject['subject_code'] ?></center>
                </th>
            <?php endforeach; ?>
            <th>Total</th>
            <th rowspan="2">TOTAL [WGP / CH]</th>
            <th rowspan="2">Total GPA </th> <!--[Totalwgpa/Total CH]-->
            <!-- <th>NG Count</th> --> <!-- < Added NG count column -->
        </tr>
        <tr>
            <?php foreach ($ledger[0]['subjects'] as $subject) : ?>
                <th>Subject[CH, FM]</th>
                <th>Obt. Marks [TH]</th>
                <th>GP</th>
                <th>Grade</th>
            <?php endforeach; ?>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($ledger as $student) : ?>
            <?php
            // Initialize NG count for each student
            $NGCount = 0;
            ?>
            <tr>
                <td><?= $student['sn'] ?></td>
                <td style="width: 250px"><?= $student['name'] ?></td>
                <?php foreach ($student['subjects'] as $subject) : ?>
                    <td style="width: 200px">
                        <?= $subject['subject_name'] ?><br>
                        [CH: <?= $subject['credit_hour'] ?>, FM: <?= $subject['theory_full_marks'] ?>]
                    </td>
                    <td>
                        <?= is_numeric($subject['marks']) ? $subject['marks'] : '' ?>
                    </td>
                    <?php
                    // Calculate MP, grade, and GP
                    $Obtmarks = $subject['marks'];
                    $fullmarks = $subject['theory_full_marks'];
                    $CH = is_numeric($subject['credit_hour']) ? $subject['credit_hour'] : 0;
                    $totalch += $CH;

                    // Calculate MP, grade, and GP
                    $MP = $fullmarks > 0 ? (float)$Obtmarks / (float)$fullmarks : 0;
                    $grade = calculateGrade($MP);
                    $GP = calculateGP($MP);

                    // Increment NG count if the grade is 'NG'
                    if ($grade === '<b><span style="color:#0011ff">NG</b>' || $grade === '<b><span style="color:red">Abs</b>' ) {
                        $NGCount++;
                    }

                    // Display GP and grade
                    echo '<td>' . $GP . '</td>';
                    echo '<td>' . $grade . '</td>';
                    ?>
                <?php endforeach; ?>

                <td><?= $student['total_marks'] ?></td>
                <td style="font-size:14px"><?= $student['totalwgp'] . ' / ' . $student['totalch'] ?></td>

                <?php
                // Calculate GPA
                if ($NGCount > 0) {
                    $gpa = "-";
                } else {
                    $gpa = $student['totalch'] !== 0 ? round($student['totalwgp'] / $student['totalch'], 2) : 0;

                }
                ?>

                <td><?= $TotalCH > 0 ? $gpa : '' ?></td>
                <!-- <td><?= $NGCount ?></td>--> <!-- Display NG count for each student -->
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

                </div>
            <?php else : ?>
                <p>No data available for the selected class.</p>
            <?php endif; ?>
        </div>
   </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- /.col-md-12 -->
                                </div>
                    </div>
                </div>
                <!-- /.content-container -->
            </div>
            <!-- /.content-wrapper -->
        </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>

