@extends('layouts.master')
@section('content')
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400..700&family=Open+Sans:ital,wght@0,300..800;1,300..800&family=PT+Sans:ital,wght@0,400;0,700;1,400;1,700&family=Poppins:ital,wght@0,200;0,300;1,200;1,300;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');

        body {
            font-family: "Roboto", sans-serif;
            font-style: normal;
        }

        a {
            text-decoration: none;
        }

        .print-container {
            width: 210mm;
            height: 297mm;
            margin-bottom: 10px;
            background-image: url("{{ asset('default/certificate-back.png') }}");
            background-size: cover;
            /* Ensures the image covers the print-container */
            background-position: center center;
            background-repeat: no-repeat;
            overflow: hidden;
            position: relative;
        }

        .first-row {
            position: relative;
            padding: 0px 10px 0px;
            margin-top: 50px;
            background-color: transparent;
            /* border: 3px double #ccc; */
        }

        table,
        th,
        td {
            border: 1px solid rgb(216, 215, 215);
            border-collapse: collapse;
        }

        .first-table-wrapper {
            display: flex;
            gap: 20px;
            justify-content: center;
        }

        .left-side {
            text-align: center;
        }

        .left-side h2 {
            font-size: 22px;
        }

        .third-table-wrapper {
            display: flex;
        }

        .sig {
            font-family: "Dancing Script", cursive;
            font-weight: 600;
            text-align: center;
        }

        table tr th,
        table tr td {
            padding-left: 5px;
        }

        .col-height {
            height: 34px;
        }

        .bg-gray {
            background-color: #e9e9e9;
        }
    </style>


    @if (isset($students) && !empty($students))
        <div class="card mt-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between border-bottom">
                <h6 class="m-0 table__top__txt">All Mark Sheet (Total Result: {{ count($students) }})</h6>
                <div class="m-0 float-right">
                    <a class="btn btn-secondary btn__export mr-1" href="#" data-toggle="tooltip" onclick="printMarkDiv()"
                        title="Print">
                        <i class="fas fa-print"></i>
                    </a>
                </div>
            </div>
            <div class="card-body table_content">
                @php
                    $grades_str = '';
                    foreach ($grades as $grade) {
                        $grades_str .= "<tr>
                                            <td align='center'>$grade->mark_from-$grade->mark_to</td>
                                            <td align='center'>$grade->name</td>
                                            <td align='center'>$grade->remark</td>
                                        </tr>";
                    }

                    $head_marks_array = json_decode($assignedMarksHead->first(), true);

                    $head_id_array = array_keys($head_marks_array);
                    $subject_head_marks = $assignedMarksHead;
                    $highest_grand_total_obtain = 0;
                    // dd($assignedMarksHead);
                @endphp

                @foreach ($students as $key => $student)
                    @php
                        $examRecords = $student->examRecords;
                        $singleRecord = $examRecords->first();
                        $total_gp_sum = 0;
                        $total_subjects_count = 0;
                        // dd($singleRecord);
                    @endphp

                    @if ($examRecords->isNotEmpty())
                        @php
                            $grand_total = 0;
                            $grand_total_obtain = 0;
                            $fail_count = 0;
                            $head_wise_grand_total = [];
                            $section = $sections[$singleRecord->section_id] ?? '';
                            $class = $studentClasses[$singleRecord->class_id] ?? '';
                            $academicYear = $academicYears[request()->academic_year] ?? '';
                            $logo_path = get_setting_value(Settings::EXPORT_LOGO)
                                ? get_setting_value(Settings::EXPORT_LOGO)
                                : 'uploads/images/logo.png';
                            $institute_name = get_setting_value(Settings::SCHOOL_NAME)
                                ? get_setting_value(Settings::SCHOOL_NAME)
                                : '';
                            $principal_signature = get_setting_value(Settings::PRINCIPAL_SIGNATURE)
                                ? get_setting_value(Settings::PRINCIPAL_SIGNATURE)
                                : '';
                        @endphp
                        <section class="page-section">
                            <div class="container print-container">
                                <div class="first-row">
                                    {{-- <div class="ms__icon"></div> --}}
                                    <div class="first-table-wrapper" style="display: flex; padding-bottom:20px; width: 100%;">
                                        <!-- Left Side -->
                                        <div class="left-side" style="width: 30%; text-align: center;">
                                            <p>{{ $institute_name }}</p>
                                            <img src="{{ asset($logo_path) }}" height="135"
                                                width="200" alt="">
                                        </div>

                                        <!-- Middle Side (Student Info) -->
                                        <div class="middle-side" style="width: 30%;">
                                            <div class="student-information">
                                                <table width="100%"
                                                    style="height: 250px; border: 1px solid black; border-collapse: collapse;">
                                                    <tr>
                                                        <th colspan="2" align="center">Student Information</th>
                                                    </tr>
                                                    <tr>
                                                        <th align="center">ID</th>
                                                        <td align="center">{{ $student->student_id_no }}</td>
                                                    </tr>
                                                    <tr>
                                                        <th align="center">Name</th>
                                                        <td align="center">{{ $student->first_name }}
                                                            {{ $student->last_name }}</td>
                                                    </tr>
                                                    <tr>
                                                        <th align="center">Session</th>
                                                        <td align="center">{{ $exam->academic_year->year ?? '' }}</td>
                                                    </tr>
                                                    <tr>
                                                        <th align="center">Class</th>
                                                        <td align="center">{{ $class }}</td>
                                                    </tr>
                                                    <tr>
                                                        <th align="center">Section</th>
                                                        <td align="center">{{ $section }}</td>
                                                    </tr>
                                                    <tr>
                                                        <th align="center">Roll</th>
                                                        <td align="center">{{ $student->class_roll }}</td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>

                                        <!-- Right Side (Grade Reference) -->
                                        <div class="right-side" style="width: 40%;">
                                            <div class="Grade-reference">
                                                <table width="100%"
                                                    style="height: 250px; border: 1px solid black; border-collapse: collapse;">
                                                    <tr>
                                                        <th colspan="3" align="center">Grade Reference</th>
                                                    </tr>
                                                    <tr>
                                                        <th align="center">Marks(%)</th>
                                                        <th align="center">Grade</th>
                                                        <th align="center">Comments</th>
                                                    </tr>
                                                    {!! $grades_str !!}
                                                </table>
                                            </div>
                                        </div>
                                    </div>


                                    <div class="second-and-third-wrapper" >
                                        <div class="second-table-wrapper" style="padding-bottom:20px;">
                                            <table class="result-table" width="100%">

                                                <tr>
                                                    <th rowspan="2">Subject</th>
                                                    <th rowspan="2" class="bg-gray">Full <br> Marks </th>
                                                    <th colspan="{{ count($head_id_array) + 3 }}"
                                                        class="text-center col-height"> {{ $exam->exam_name ?? '' }}
                                                        {{ $exam->academic_year->year ?? '' }}</th>
                                                </tr>

                                                <tr align="center">
                                                    @if (isset($head_id_array))
                                                        @foreach ($markHeads as $head)
                                                            @if (in_array($head->id, $head_id_array))
                                                                <th>{{ $head->short_name }}</th>
                                                            @endif
                                                        @endforeach
                                                    @endif
                                                    <th>Total Obt.</th>
                                                    <th>Grade</th>
                                                    <th>Heighest Marks</th>
                                                </tr>

                                                @foreach ($subjects_assigns as $subjects_assign)
                                                    @php
                                                        $subject_id = $subjects_assign->subject_id;
                                                        $recoards = $examRecords->firstWhere('subject_id', $subject_id);

                                                        $full_marks = 0;
                                                        $head_wise_fail_count = 0;
                                                        $head_wise_total_obtain = [];
                                                        $total_marks_obtain = 0;
                                                        $head_records_str = '';



                                                        $head_wise_marks_record = $recoards
                                                            ? json_decode($recoards->head_wise_marks)
                                                            : null;
                                                        $head_marks_data = $subject_head_marks[$subject_id] ?? '{}';
                                                        $head_marks_array = json_decode($head_marks_data);

                                                        $head_marks_array2 = json_decode($head_marks_data, true);       // array
                                                        $head_wise_marks_record2 = $recoards ? json_decode($recoards->head_wise_marks, true) : []; // array

                                                        // ==============================
                                                        // HEAD-WISE PASS FAIL CHECK
                                                        // ==============================
                                                        $head_wise_pass_fail = [];

                                                        foreach ($head_marks_array2 as $head_id => $total_marks) {
                                                            $pass_marks = $total_marks * 0.33;  // 33%
                                                            $marks_obtained = $head_wise_marks_record2[$head_id] ?? 0;

                                                            $head_wise_pass_fail[$head_id] = ($marks_obtained >= $pass_marks)
                                                                ? 'Pass'
                                                                : 'Fail';
                                                        }

                                                        // subject fail if ANY head failed
                                                        if (in_array('Fail', $head_wise_pass_fail)) {
                                                            $head_wise_fail_count++;
                                                        }

                                                        // Skip subject if all head-wise marks (e.g., written + viva) are null
                                                        $all_marks_null = true;
                                                        if ($head_wise_marks_record) {
                                                            foreach ($head_id_array as $head_id) {
                                                                if (isset($head_wise_marks_record->{$head_id}) && $head_wise_marks_record->{$head_id} !== null) {
                                                                    $all_marks_null = false;
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                        if ($all_marks_null) {
                                                            continue;
                                                        }
                                                    @endphp

                                                    <tr align="center">
                                                        <td align="left">{{ $subjects_assign->subject->subject_name }}</td>

                                                        @if ($head_wise_marks_record)
                                                            @foreach ($markHeads as $head)
                                                                @if (in_array($head->id, $head_id_array))
                                                                    @php
                                                                        $full_marks += $head_marks_array->{$head?->id} ?? 0;
                                                                        $head_records_str .= '<td>' . ($head_wise_marks_record->{$head?->id} ?? '0') . '</td>';
                                                                        $total_marks_obtain += $head_wise_marks_record->{$head?->id} ?? 0;
                                                                        $head_wise_grand_total[$head?->id] =
                                                                            ($head_wise_grand_total[$head?->id] ?? 0) +
                                                                            ($head_wise_marks_record->{$head?->id} ?? 0);
                                                                    @endphp
                                                                @endif
                                                            @endforeach

                                                            <td class="bg-gray">{{ $full_marks }}</td>
                                                            {!! $head_records_str !!}

                                                            @php
                                                                $grand_total_obtain += $total_marks_obtain;
                                                                $grand_total += $full_marks;
                                                            @endphp
                                                        @else
                                                            @php
                                                                $full_marks = 0;
                                                                // First: calculate full marks
                                                                foreach ($markHeads as $head) {
                                                                    if (in_array($head->id, $head_id_array)) {
                                                                        $full_marks += $head_marks_array->{$head->id} ?? 0;
                                                                    }
                                                                }
                                                                $grand_total += $full_marks;
                                                            @endphp

                                                            <td class="bg-gray">{{ $full_marks }}</td>
                                                            @foreach ($markHeads as $head)
                                                                @if (in_array($head->id, $head_id_array))
                                                                    <td>0</td>
                                                                @endif
                                                            @endforeach
                                                        @endif

                                                        <td>{{ $total_marks_obtain }}</td>

                                                        @php
                                                            $subject_grade_name = 'F';
                                                            $subject_gp = 0; // store GP for this single subject
                                                           
                                                            $total_percentage =
                                                                $total_marks_obtain > 0 && $full_marks > 0
                                                                    ? round(($total_marks_obtain * 100) / $full_marks)
                                                                    : 0;
                                                            
                                                            if ($head_wise_fail_count == 0) {
                                                                foreach ($grades as $grade) {
                                                                    if ($grade->mark_from <= $total_percentage && $grade->mark_to >= $total_percentage) {
                                                                        $subject_grade_name = $grade->name;
                                                                        $subject_gp = (float) $grade->gpa;   // save GP for this subject
                                                                        // dd($grade->gpa);
                                                                        if ($subject_grade_name == 'F') {
                                                                            $fail_count++;
                                                                        }
                                                                    }
                                                                }
                                                            } else {
                                                                $fail_count++; // fail due to head-wise fail
                                                                $subject_grade_name == 'F';
                                                                $subject_gp = 0.00;
                                                            }

                                                             // add to final GP list
                                                            $total_gp_sum = ($total_gp_sum ?? 0) + $subject_gp;
                                                            $total_subjects_count = ($total_subjects_count ?? 0) + 1;
                                                            
                                                        @endphp

                                                        <td>{{ $subject_grade_name }}</td>
                                                        <td>
                                                            @if (array_key_exists($subject_id, $highest_marks_array))
                                                                {{ round($highest_marks_array[$subject_id]) }}
                                                            @endif
                                                        </td>
                                                    </tr>
                                                @endforeach

                                                @php
                                                    if ($grand_total_obtain > $highest_grand_total_obtain) {
                                                        $highest_grand_total_obtain = $grand_total_obtain;
                                                    }
                                                @endphp

                                                <tr align="center">
                                                    <td align="left"> <b>Grand Total</b></td>
                                                    <td class="bg-gray"><b>{{ $grand_total }}</b></td>
                                                    @foreach ($markHeads as $head)
                                                        @if (in_array($head->id, $head_id_array))
                                                            <th>{{ $head_wise_grand_total[$head->id] }}</th>
                                                        @endif
                                                    @endforeach
                                                    <td> <b>{{ $grand_total_obtain }}</b></td>
                                                    <td></td>
                                                    <td>{{ array_sum($highest_marks_array) }}</td>
                                                </tr>

                                                @php
                                                    $grade_name = 'F';
                                                    $grade_name_remarks = '';
                                                    $grand_total_percentage =
                                                        $grand_total_obtain > 0 && $grand_total > 0
                                                            ? round(($grand_total_obtain * 100) / $grand_total)
                                                            : 0;
                                                @endphp

                                                <tr align="center">
                                                    <td class="col-height" align="left"> <b>Percentage</b> </td>
                                                    <td colspan="{{ count($head_id_array) + 4 }}">
                                                        <b>{{ round($grand_total_percentage, 2) }}%</b>
                                                    </td>
                                                </tr>
                                                <tr align="center">
                                                    <td class="col-height" align="left"><b>Grade</b></td>
                                                    <td colspan="{{ count($head_id_array) + 1 }}">
                                                        @if ($fail_count > 0)
                                                            <b>F</b>
                                                        @else
                                                            @php
                                                                $grade_name = gradeCalculation(number_format($total_gp_sum / $total_subjects_count, 2))
                                                            @endphp
                                                            <b>{{ $grade_name }}</b>
                                                        @endif
                                                    </td>
                                                    <td class="col-height" align="left"><b>GPA</b></td>
                                                    <td colspan="{{ count($head_id_array) + 1 }}">
                                                        @if ($fail_count > 0)
                                                            <b>0.00</b>
                                                        @else
                                                            <b>{{ number_format($total_gp_sum / $total_subjects_count, 2) }}</b>
                                                        @endif
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>

                                        <div class="third-table-wrapper" style="display: flex; padding-bottom:50px; width: 100%;">
                                            <div class="work-information" style="width: 50%;">
                                                <table width="100%">

                                                    <tr>
                                                        <td style="width: 50%">Working Days</td>
                                                        <td style="width: 50%"></td>
                                                    </tr>
                                                    <tr>
                                                        <td>Present</td>
                                                        <td>{{ '' }}</td>
                                                    </tr>
                                                    <tr>
                                                        <td>Absent</td>
                                                        <td>{{ '' }}</td>
                                                    </tr>
                                                    <tr>
                                                        <td>Remarks</td>
                                                        <td></td>
                                                    </tr>
                                                    <tr>
                                                        <td>Result Published</td>
                                                        <td>{{ $publish_date }}</td>
                                                    </tr>
                                                </table>
                                            </div>
                                            <div class="conduct-info" style="width: 50%;">
                                                <table width="100%">
                                                    <tr>
                                                        <td style="width: 50%">Conduct</td>
                                                        <td style="width: 50%"></td>
                                                    </tr>
                                                    <tr>
                                                        <td>Moral Development</td>
                                                        <td></td>
                                                    </tr>
                                                    <tr>
                                                        <td>Discipline</td>
                                                        <td></td>
                                                    </tr>
                                                    <tr>
                                                        <td>Hand Writing</td>
                                                        <td></td>
                                                    </tr>
                                                    <tr>
                                                        <td>General Remark</td>
                                                        <td>{{ gradeNameRemarks($grade_name) }}</td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="last-table-wrapper">
                                        <table border="1" width="100%">
                                            <tr>
                                                <th>Class Teacher's Signature</th>
                                                <th>Principle's Signature</th>
                                                <th>Guardian's Signature</th>
                                            </tr>
                                            <tr>
                                                <td class="sig" style="height: 30px"></td>
                                                <td class="sig">
                                                    @if (!empty($principal_signature))
                                                        <img width="150px" src="{{ asset($principal_signature) }}" />
                                                    @else
                                                        <img width="150px" src="{{ asset('signature/principal.jpg') }}" />
                                                    @endif
                                                </td>
                                                <td class="sig"></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="page-break"></div>
                        </section>
                    @endif
                @endforeach
            </div>

        </div>
    @endif
@endsection


@section('scripts')
    <script src="{{ asset('js/report-actions.js') }}"></script>
    <script>


function printMarkDiv() {
    const divsToPrint = document.getElementsByClassName("print-container");
    const certificateBgUrl = window.certificateBgUrl || "/default/certificate-back.png";
    const newWin = window.open("", "_blank");

    let htmlToPrint = `
    <html>
    <head>
        <title>Print Mark Sheets</title>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@600&display=swap">
        <style>
            @page {
                size: A4;
                margin: 0;
            }
            .hide-btn{
                visibility: hidden;
            }
            @import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400..700&family=Open+Sans:ital,wght@0,300..800;1,300..800&family=PT+Sans:ital,wght@0,400;0,700;1,400;1,700&family=Poppins:ital,wght@0,200;0,300;1,200;1,300;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');

            body {
                font-family: "Roboto", sans-serif;
                font-style: normal;
            }

            .print-page {
            width: 210mm;
            height: 297mm;
            margin-bottom: 10px;
           page-break-after: always;
                background-image: url("${certificateBgUrl}");
            background-size: cover;
            /* Ensures the image covers the print-container */
            background-position: center center;
            background-repeat: no-repeat;
            overflow: hidden;
            position: relative;
        }

            table {
                border-collapse: collapse;
                width: 100%;
            }
            table, th, td {
                border: 1px solid rgb(216, 215, 215);
            }
            th, td {
                padding: 3px 3px ;
            }
            .first-row {
                padding: 10px;
                margin-top: 50px;
            }
            .first-table-wrapper {
                display: flex;
                justify-content: space-between;
                gap: 20px;
                margin-top: 15px;
            }
            .left-side, .middle-side, .right-side {
                box-sizing: border-box;
            }
            .left-side { width: 30%; text-align: center; }
            .middle-side { width: 30%; }
            .right-side { width: 40%; }

            @media print {
                body {
                    -webkit-print-color-adjust: exact;
                    print-color-adjust: exact;
                }
                .first-row {
                    position: relative;
                    padding-left: 40px;
                    padding-right: 40px;
                    margin-top: 20px;
                    background-color: transparent;
          
                }
            }
        </style>
    </head>
    <body>
    `;

    for (let i = 0; i < divsToPrint.length; i++) {
        htmlToPrint += `
        <div class="print-page">
            ${divsToPrint[i].innerHTML}
        </div>
        `;
    }

    htmlToPrint += `
    </body>
    </html>
    `;

    newWin.document.open();
    newWin.document.write(htmlToPrint);
    newWin.document.close();

    newWin.onload = function () {
        newWin.focus();
        newWin.print();
        newWin.close();
    };
}
    </script>
@endsection
