<?php
function template33($institutions, $branch, $students_array, $examination, $array, $result, $class_id, $section_id = null)
{
    $marksData = [];
    foreach ($array as $index => $value) {
        $marksData[$index] = $value;
    }
    global  $conn_rjllearning_specific;

    $analytics = $students_array[0]['analytics'] ?? null;

    // Ensure all required indexes exist
    for ($i = 1; $i <= 37; $i++) {
        if (!isset($marksData[$i])) {
            $marksData[$i] = '';
        }
    }

    $percentage = calculatePercentage($marksData);
?>

    <!DOCTYPE html>
    <html>
    <!--<head>-->
    <!--    <meta charset="utf-8">-->
    <!--    <meta name="viewport" content="width=device-width, initial-scale=1.0">-->
    <!--    <title>Template 27 - XI, XII</title>-->
    <!--    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>-->
    <!--    <link href="style_template27.css" type="text/css" rel="stylesheet">-->
    <!--</head>-->

    <body>
        <div class="container_marksheet_template">
            <div class="content_container">
                <div class="fullstretch header_template">
                    <div class="logo_div">
                        <img src="<?php echo $institutions['logo']; ?>" alt="School Logo">
                    </div>
                    <div class="header_institution">
                        <span class="heading_template"><?php echo $institutions['institution_name']; ?></span><br>
                        <span class="heading_code_info"><?php echo htmlspecialchars($branch['affiliation_code'] !== null ? $branch['affiliation_code'] : ''); ?></span><br>
                        <span class="heading_address">
                            <?php echo $branch['address'];
                            if ($branch['pincode'] != "" || $branch['city'] != "" || $branch['state_name'] != "" || $branch['country_name'] != "") {
                                echo ", " . $branch['city'] . ", " . $branch['state_name'] . ", " . $branch['country_name'] . " - " . $branch['pincode'];
                            }
                            ?>
                        </span><br>
                        <span class="contact_info">
                            <?php echo $branch['contact_number'];
                            if ($branch['email'] != "") {
                                echo ", " . strtolower($branch['email']);
                            }
                            ?>
                        </span>
                    </div>
                </div>

                <div class="fullstretch report_header">
                    <h2 class="heading_report">Progress Report</h2>
                    <div class="academic_session">Academic Session <?php echo $result; ?></div>
                </div>


                <div class="student_info_container">
                    <div class="student_info_item">
                        <label>Name:</label>
                        <span class="student_data"><?php echo $students_array[0]['name']; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Admission Number:</label>
                        <span class="student_data"><?php echo $students_array[0]['admission_number']; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Class:</label>
                        <span class="student_data"><?php echo $class_id; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Section:</label>
                        <span class="student_data"><?php echo $section_id; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Father's Name:</label>
                        <span class="student_data"><?php echo $students_array[0]['fathername']; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Mother's Name:</label>
                        <span class="student_data"><?php echo $students_array[0]['mothername']; ?></span>
                    </div>
                </div>

                <div class="form-container">
                    <div class="stream-selector">
                        <label for="stream-select">Stream: <?php echo htmlspecialchars(strtoupper($marksData[1])); ?></label>
                    </div>

                    <table id="subjects-table" class="subjects-table">
                        <thead>
                            <tr>
                                <th rowspan="2">Subject</th>
                                <th colspan="6"><?php echo ucwords($examination); ?></th>
                            </tr>
                            <tr>
                                <th>TH.</th>
                                <th>M.O.</th>
                                <!-- <th>PR.</th>
                                <th>M.O.</th> -->
                                <th>Total</th>
                                <th>Grade</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            // if subject_type!=A
                            $marksData = [];
                            $fail_counter = 0;
                            foreach ($array as $index => $value) {
                                $marksData[$index] = $value;
                            }

                            // Initialize totals
                            $totalTheoryMax = 0;
                            $totalTheoryMarks = 0;
                            $totalOverallMarks = 0;

                            for ($i = 2; $i <= 33; $i += 4) {

                                $subjectName = $marksData[$i] ?? '';

                                if (empty(trim($subjectName))) {
                                    break;
                                }

                                $subjectType = $marksData[$i + 1] ?? '';
                                $theoryMax = $marksData[$i + 2] ?? '';
                                $theoryMarks = $marksData[$i + 3] ?? '';

                                if (is_numeric($theoryMarks) && is_numeric($theoryMax) && (float)$theoryMax > 0) {
                                    $theoryMarksVal = (float)$theoryMarks;
                                    $theoryMaxVal = (float)$theoryMax;
                                    $subject_percentage_theory = ($theoryMarksVal / $theoryMaxVal) * 100;
                                } else {
                                    $theoryMarksVal = null;
                                    $theoryMaxVal = null;
                                    $subject_percentage_theory = null;
                                }

                                // Total calculation
                                $total_marks = 0;
                                $total_marks_obtained = 0;

                                if ($theoryMaxVal !== null) {
                                    $total_marks += $theoryMaxVal;
                                    $total_marks_obtained += $theoryMarksVal;
                                }

                                $grade = get_grade($total_marks_obtained, $total_marks);

                                // Add to totals only if subject is not Additional (A)
                                if ($subjectType != "A") {
                                    $totalTheoryMax += ($theoryMaxVal ?? 0);
                                    $totalTheoryMarks += ($theoryMarksVal ?? 0);
                                    $totalOverallMarks += ($total_marks_obtained ?? 0);
                                }

                                // Fail condition — only check if percentages exist
                                if (
                                    ($subject_percentage_theory !== null && $subject_percentage_theory < 33.00)
                                ) {
                                    $total_marks_obtained = '';
                                    $grade = '';

                                    if ($subjectType != "A") {
                                        $fail_counter++;
                                    }
                                }

                                // Cleanup for display: if values are null, make them empty strings (so they don't print as 0)
                                $theoryMarks = $theoryMarksVal === null ? '' : $theoryMarksVal;
                                $theoryMax   = $theoryMaxVal === null ? '' : $theoryMaxVal;

                                // Determine the display value for subjectType
                                $displaySubjectType = '';
                                if ($subjectType == 'M') {
                                    $displaySubjectType = 'Mandatory';
                                } elseif ($subjectType == 'O') {
                                    $displaySubjectType = 'Optional';
                                } elseif ($subjectType == 'A') {
                                    $displaySubjectType = 'Additional';
                                } else {
                                    $displaySubjectType = $subjectType;
                                }
                            ?>
                                <tr>
                                    <td>
                                        <?php echo htmlspecialchars($subjectName); ?>
                                        <?php if ($subjectType == 'A'): ?>
                                            <br><span style="font-size: 0.9em;">(Additional)</span>
                                        <?php endif; ?>
                                    </td>
                                    <!--<td><?php echo htmlspecialchars($displaySubjectType); ?></td>-->
                                    <td><?php echo htmlspecialchars($theoryMax); ?></td>
                                    <td><?php echo displayMark($theoryMarks); ?></td>
                                    <td><?php echo displayMark($total_marks_obtained); ?></td>
                                    <td><?php echo $grade; ?></td>
                                </tr>
                            <?php
                            }
                            ?>

                            <tr>
                                <td><strong>Total</strong></td>
                                <td><?php echo $totalTheoryMax; ?></td>
                                <td><?php echo $fail_counter == 0 ? $totalTheoryMarks : ''; ?></td>
                                <td><?php echo $fail_counter == 0 ? $totalOverallMarks : ''; ?></td>
                                <td></td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="summary-container">
                    <div class="summary-item">
                        <p>
                            <label for="percentage-input"><strong>Percentage: </strong></label>
                            <span><?php echo $fail_counter == 0 ? $percentage . '%' : '-'; ?></span>
                        </p>
                        <p>
                            <label for="attendance-input"><strong>Attendance: </strong></label>
                            <span><?php echo htmlspecialchars($array[34] ?? ''); ?></span>
                        </p>
                        <p>
                            <label for="remarks-select"><strong>Remarks: </strong></label>
                            <span><?php echo htmlspecialchars($array[35] ?? ''); ?></span>
                        </p>
                    </div>
                </div>
                <?php
                if ((!empty($marksData[36]) && strtolower($marksData[36]) !== 'na')) {
                ?>

                    <div class="congratulate_message">
                        <?php
                        if (!empty($marksData[36]) || $marksData[36] != 'na') {
                            // Fetch class_name from DB using the class ID
                            $className = '';
                            $stmt = $conn_rjllearning_specific->prepare(
                                "SELECT classname FROM class_info WHERE id = :id LIMIT 1"
                            );
                            $stmt->bindParam(':id', $marksData[36], PDO::PARAM_INT);
                            $stmt->execute();
                            $classRow = $stmt->fetch(PDO::FETCH_ASSOC);

                            if ($classRow && !empty($classRow['classname'])) {
                                $className = $classRow['classname'];
                            }

                            // Map gender to salutation
                            $gender = strtoupper(trim($students_array[0]['gender'] ?? ''));
                            $salutation = ($gender === 'M') ? 'Mr.' : (($gender === 'F') ? 'Miss.' : '');

                            // Display student promotion message with class name
                            if (!empty($className)) {
                                echo "Congratulations! "
                                    . $salutation . " "
                                    . ucwords(strtolower($students_array[0]['name']))
                                    . " has been promoted to Class "
                                    . htmlspecialchars($className);
                            }
                        }
                        ?>
                    </div>
                <?php
                }
                ?>

                <div class="new_session">
                    <?php
                    if (!empty($marksData[37]) || $marksData[37] != "" || $marksData[37] != null) {
                        // Format the date (d-m-Y)
                        $formattedDate = date("d-m-Y", strtotime($marksData[37]));
                        echo "New session begins from : " . htmlspecialchars($formattedDate);
                    }
                    ?>
                </div>

                <div class="signature_container">
                    <div class="signature_div">
                        <div class="signature-line"></div>
                        <span>Class Incharge</span>
                    </div>
                    <div class="signature_div">
                        <div class="signature-line"></div>
                        <span>Principal / Headmistress</span>
                    </div>
                    <div class="signature_div">
                        <div class="signature-line"></div>
                        <span>Parent</span>
                    </div>
                </div>

                <!-- Footer Note -->
                <div class="footer_note">
                    * Incase of any discrepancies in marksheet, please contact school administration.
                </div>
            </div>
        </div>

    </body>

    </html>

<?php
}
?>