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

$schoolname = '';
$schooladdress = '';
$estd = '';
$examtype = '';
$class_names = '';
$examType= '';


// 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:red ">NG</span></b>';
    } else {
        return '<b><span style="color:#0011ff">Abs</span></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 'NG';
    } else {
        return 'Abs';
    }
}


if (isset($_GET['class_id']) && is_array($_GET['class_id']) && isset($_GET['exam_type'])) {
    $classIds = $_GET['class_id'];
    $examType = $_GET['exam_type']; // New parameter for exam type

    
    // 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, students.symbol_no,
                studentsub.sub1, studentsub.sub2, studentsub.sub3,
                studentsub.sub4, studentsub.sub5, studentsub.sub6,studentsub.sub7,
                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, attendance.atten_day, classes.section , subjects.*

            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 OR
                                      studentsub.sub7 = 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
              AND marks.exam_type = '$examType'
              LEFT JOIN attendance ON students.student_id = attendance.std_id AND marks.exam_type = attendance.exam_type
        

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

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

    // Prepare data for display
    $ledger = [];
    $currentStudentId = null;
    $currentStudentData = null;
    $totalMarks = 0;
    $TotalWGP = 0;
    $TotalCH = 0;
    $totalch = 0;
    $totalwgp = 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;
        $attenDay = $row['atten_day'];

        // 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'],
                'symbol' => $row['symbol_no'],
                'subjects' => [],
                'total_marks' => 0,
                'totalwgp' => 0,
                'totalch' =>0,
                'class_names' => array_values($classNames),
                'atten_day'=>$row['atten_day'],
                'stdsection' =>$row['section'],
            ];

            
            // 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_name' => $subjectName,
                'subject_code' => $subjectcode,
                'credit_hour' => $creditHour,
                'theory_full_marks' => $theoryFullMarks,
                'marks' => $marks,
                'atten_day'=> $attenDay,
                'stdsection' => $section1,
            ];

// 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 ($grade === 'NG' || $GP === '' || $MP < 0.35) {
                // If NG, GP is blank, or MP < 0.35, set WGP to 0
                $WGP = 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;
    }
}
// Fetch school details
$query = "SELECT * FROM schools LIMIT 1";
$result = $conn->query($query);

if ($result->num_rows > 0) {
    $schoolDetails = $result->fetch_assoc();
    $logoPath = $schoolDetails['logo'];
    // Assign values to the variables
    $schoolname = $schoolDetails['school_name'];
    $schooladdress = $schoolDetails['address'];
    $estd = $schoolDetails['establishment_year'];
}

// Fetch exam details
if (!empty($examType) && is_numeric($examType)) {
    $examquery = "SELECT * FROM examination_type WHERE id = $examType";
    $examresult = $conn->query($examquery);

    if ($examresult === false) {
        echo "Error executing query: " . $conn->error;
        // Handle the error accordingly, such as displaying an error message or logging it
    } else {
        // Fetch exam details from the result
        if ($examresult->num_rows > 0) {
            $examDetails = $examresult->fetch_assoc();
            // Assign values to the variables
            $examtype = $examDetails['exam_type'];
            $examyear = $examDetails['exm_year'];
        } else {
            // Handle the case where no exam details are found
        }
    }
} else {
    // Handle the case where $examType is empty or not valid
}

?>

<!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="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
    <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/prism/prism.css" media="screen" >
    <link rel="stylesheet" href="nepali.datepicker.v4.0.1/css/main.css" media="screen" >
    <script src="js/multiselect-dropdown.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" >

   

    <title>Marks Obtained Ledger</title>
   
</head>
<p>
Go back to home: <a href="dashboard.php">
<img border="0" alt="SRMS" src="favicon.ico" width="40" height="40" Value="Dashboard">
</a>
</p>
<body>
<script>
    $(document).ready(function () {
        // Check if the DataTable is already initialized
        if (!$.fn.DataTable.isDataTable('#customers')) {
            // Initialize DataTables with a default page length of 50 and a custom length menu
            $('#customers').DataTable({
                "pageLength": 100,
                "lengthMenu": [10, 25, 50, 100, 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, 'ledger_export.xlsx');
            });
        });
    </script>


<script>
        function printTable() {
          
            var printWindow = window.open('', '_blank');
            printWindow.document.write('<html><head><title>Mohanmaya Sec. School, Grade Ledger </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
        // Use setTimeout to ensure styles are applied before printing
            setTimeout(function () {
                printWindow.print();
                printWindow.onafterprint = function () {
                    printWindow.close();
                };
            }, 500);

        }
    </script>



    <div class="container"  >
        <h2>Select Class</h2>
        <div class="container" style="margin-left:-200px">
            <!-- Update the form in marks_ledger.php -->
            <form action="ledger_sort.php" method="get">
                <div class="row">
                    <div class="form-group col-md-4">
                    <label for="exam_type">Select Exam Type:</label>
            <select name="exam_type" id="exam_type" class="form-control" required>
                          <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>
    </div>
     <div class="form-group col-md-4">
                    <label for="class_id">Select Class:</label>
                    <select name="class_id[]" id="class_id" class="form-control" 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>
            <!-- Add print and export buttons -->
           <button onclick="printTable()">Print Table</button>
            <button id="exportExcelBtn" class="btn btn-success">Export to Excel</button>
    
               <?php






// Count the total number of subjects and additional columns
$totalSubjects = count($ledger[0]['subjects']); // Assuming the first student has all subjects

// Assuming you have additional columns like 'S.N.', 'Name', 'Emis no', 'Final GPA', 'Total', etc.
$additionalColumns = 5; // Adjust this count based on your actual additional columns

// Calculate the total number of columns
$totalColumns = $totalSubjects * 4 + $additionalColumns;?>
               <br><br>
                  <table id="customers" style="border-collapse: collapse; border: 1px solid #000000;">
    <thead>
        <tr>                             

<?php  $totalColumns; ?>
<td colspan='<?php echo $totalColumns; ?>'><span style='border:none'>

                                        <b><?= $schoolname ?></b> <br><?= $schooladdress ?><br> Estd: <?= $estd ?><br> <?= $examtype .' - '. $examyear ?><br>Ledger for Class <b>
                                            <?php echo implode(', ', $currentStudentData['class_names']); ?>
                                        </b>
                                </td>

                            </tr>
        <tr>
            <th rowspan="2">S.N.</th>
            <th rowspan="2">Symbol</th>
            <th width="" rowspan="2">Name</th>
            <th width="" rowspan="2">Sec</th>

            <?php foreach ($ledger[0]['subjects'] as $subject) : ?>
                <th colspan="3">
                    <center><?= $subject['subject_name']?></center>
                </th>
            <?php endforeach; ?>
            <!-- <th rowspan="2"> NGCOUNT </th> -->
            <!-- <th>Total</th> -->
            <!--<th rowspan="2">TOTAL [WGP / CH]</th>-->
            <th rowspan="2">Total GPA </th> <!--[Totalwgpa/Total CH]-->
            <th rowspan="2">Atten</th>
           <!-- <th rowspan="2">NG Count</th>  < Added NG count column --> 
        </tr>
        <tr>
            <?php foreach ($ledger[0]['subjects'] as $subject) : ?>
                <th>Subject<br>[CH,FM]</th>
                <!-- <th>Marks [TH]</th> -->
                <th>GP</th>
                <th>Grd</th>
                <!-- <th>pass mark</th> -->
            <?php endforeach; ?>
          
        </tr>
    </thead>
    <tbody>
    <?php foreach ($ledger as $student) : ?>
        <?php
        // Initialize NG count for each student and total credit hours
        $NGCount1 = 0;
        $totalch1 = 0; // Total credit hours for this student
        ?>
        <tr>
            <td><?= $student['sn'] ?></td>
            <td style="color: red; font-size: 13px; text-align: left; font-weight: bold"><?= $student['symbol'] ?></td>
            <td style="width:'150px';text-align: left; font-size: 16px;"><?= $student['name'] ?></td>
            <td style=" align:'left' "><?= $student['stdsection'] ?></td>
           <?php foreach ($student['subjects'] as $subject) : ?>
                <td style=" font-size: 90%;">
                    <?= $subject['subject_code'] ?><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'];
                $CH1 = is_numeric($subject['credit_hour']) ? $subject['credit_hour'] : 0;

                // 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' or 'Abs'
                // if ($grade === '<b><span style="color:red">NG</span></b>' || $grade === '<b><span style="color:#0011ff">Abs</span></b>') {
                //     $NGCount++;
                // }
                
                 $Passmark = $fullmarks * .35;
                
                // Display GP and grade
                echo '<td style="font-weight: bold; font-size: 16px;">' . $GP . '</td>';
                echo '<td style="font-weight: bold; font-size: 16px;">' . $grade . '</td>';
              '<td>' . $Passmark . '</td>';
           
                 if ($Obtmarks < $Passmark) {
                   $NGCount1++;
                 }

           
            
                // Calculate total credit hours for this student
                $totalch1 += $CH1;
                ?>
                
            <?php endforeach; ?>
<!-- <td><?= $NGCount1 ?> </td> -->
            <!--<td><?= $student['total_marks'] ?></td>-->
            <!--<td style="font-size:14px"><?= $student['totalwgp'] . ' / ' . $totalch1 ?></td>-->

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

            <td style="font-size:16px; font-weight:bold"><?= $totalch1 > 0 ? $gpa : '' ?></td>
            <td style="padding: -5%; font-size:16px"><?= $subject['atten_day'] ?></td>
        </tr>
    <?php endforeach; ?>
</tbody>

<tr>
       <td style="border:none;"></td>
   </tr>
   <tr></tr>
                    <tfoot style="border:none">
                        <tr>
         <td colspan="3" ><strong>Subject Code</strong></td>
        <?php foreach ($ledger[0]['subjects'] as $subject) : ?>
            <td colspan="3" style="text-align:center"><strong><?= $subject['subject_code'] ?></strong></td>
        <?php endforeach; ?> 
    </tr>
 
    <tr>
        <td colspan="3"><strong>Subject Name</strong></td>
        <?php foreach ($ledger[0]['subjects'] as $subject) : ?>
            <td colspan="3" style="text-align:center; font-size: 12px;"><strong><?= $subject['subject_name'] ?><br>
                

            </strong></td>
        <?php endforeach; ?>
    </tr>
           </table>





        <?php else : ?>
            <p>No data available for the selected class.</p>
        <?php endif; ?>
    </div>
</div>


        <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>