<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Annual Master List - {{ $data['class']->display_name }} {{ $data['year'] }}/{{ $data['year'] + 1 }}</title>
    <link href="{{ asset('vendor/bootstrap-5.3.7.min.css') }}" rel="stylesheet">
    <link href="{{ asset('vendor/fontawesome-6.7.2/css/all.min.css') }}" rel="stylesheet">
    <link href="{{ asset('css/school-portal.css') }}" rel="stylesheet">
    <style>
        @page {
            size: A4 landscape;
            margin: 0.3in;
        }

        .page-break {
            page-break-before: always;
        }

        .report-title {
            font-size: 12px;
            font-style: italic;
            font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
            height: 25px;
            padding-top: 5px;
            margin-top: 0px;
            background-color: #757575 !important;
        }

        .add-border {
            border: 1px solid #CCC;
        }

        .header-flex {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
        }

        .school-logo {
            width: auto;
            height: 60px;
            border-radius: 5px;
            flex-shrink: 0;
        }

        .school-info {
            text-align: center;
        }

        .result-header {
            font-size: 8px;
            background-color: transparent !important;
            padding: 2px !important;
        }

        .fontwhite {
            color: #000 !important;
            font-weight: bold !important;
        }

        .result-body {
            font-size: 7px;
            font-weight: bolder;
            padding: 2px !important;
        }

        .result-body2 {
            font-size: 6px;
            font-weight: normal;
        }

        .report-body2 {
            font-size: 8px;
            font-weight: bold;
        }

        .fontnormal {
            font-weight: normal;
        }

        .school-name {
            font-size: 14px;
            font-family: Georgia, "Times New Roman", Times, serif;
            font-weight: bolder;
            margin-bottom: 3px;
        }

        .contacts {
            font-size: 8px;
            font-weight: bold;
            margin-bottom: 2px;
        }

        .bgimage {
            background-image: url(images/signin_feild_bg.gif) !important;
            background-repeat: repeat;
            -webkit-print-color-adjust: exact;
        }

        @media print {
            .no-print {
                display: none;
            }

            body {
                margin: 0;
            }
        }

        /* Force annual summary table to fit A4 landscape width */
        .annual-summary-table {
            width: 1107px !important;
            table-layout: fixed !important;
        }

        .annual-summary-table th,
        .annual-summary-table td {
            font-size: 5px !important;
            padding: 1px !important;
            word-wrap: break-word !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
        }


    </style>
</head>
<body class="a4-landscape-min">

@php
    $studentCount = count($data['masterListData']);
    $estimatedTableHeight = ($studentCount * 15) + 80; // Rough estimate: 15px per row + 80px for headers
    $pageHeight = 700; // Approximate A4 height in pixels for print
    $halfPageHeight = $pageHeight * 0.5;
    $headerHeight = 200; // Approximate header height
    $availableHeight = $pageHeight - $headerHeight;
@endphp

@foreach($data['sessions'] as $sessionIndex => $session)
    @php
        $isFirstSession = $sessionIndex === 0;
        $needsNewPage = false;
        
        if (!$isFirstSession) {
            // Check if we need a new page based on estimated height
            $needsNewPage = $estimatedTableHeight > $halfPageHeight;
        }
    @endphp
    
    @if($needsNewPage)
        </div> <!-- Close previous container -->
        <div class="page-break"></div>
    @endif
    
    @if($isFirstSession || $needsNewPage)
    <div style="width:1123px;margin:auto;margin-top:0px;padding:8px;margin-bottom:15px" class="bgimage add-border main-container">
        <!-- Header -->
        <div class="header-flex">
            <img src="{{ asset('images/rosa-mys-logo.png') }}" alt="school logo" class="school-logo">
            <div class="school-info">
                <div class="school-name">{{ $data['school_info']['name'] }}</div>
                @if($data['school_info']['address'])
                <div class="contacts">{{ $data['school_info']['address'] }}</div>
                @endif
                <div class="contacts">
                    @if($data['school_info']['website'])
                        <i class="fa fa-desktop"></i> {{ $data['school_info']['website'] }}
                    @endif
                    @if($data['school_info']['website'] && $data['school_info']['email']) | @endif
                    @if($data['school_info']['email'])
                        <i class="fa fa-envelope"></i> {{ $data['school_info']['email'] }}
                    @endif
                </div>
                @if($data['school_info']['phone_1'] || $data['school_info']['phone_2'])
                <div class="contacts">
                    <i class="fa fa-phone"></i> Phone: 
                    {{ $data['school_info']['phone_1'] }}
                    @if($data['school_info']['phone_1'] && $data['school_info']['phone_2']) , @endif
                    {{ $data['school_info']['phone_2'] }}
                </div>
                @endif
            </div>
            @if($qrCode && $sessionIndex === 0)
                <div class="qr-code" style="flex-shrink: 0; transform: scale(0.49);">
                    {!! $qrCode !!}
                </div>
            @endif
        </div>

        <!-- Title -->
        <div class="text-center report-title" style="margin-top: 8px; color: #FFF;">
            Annual Master List - {{ $data['class']->display_name }}
        </div>

        <!-- Description -->
        <div style="margin-top: 10px;">
            <table class="table-condensed report-body2">
                <tbody>
                <tr>
                    <td><strong>Class:</strong> <span class="fontnormal">{{ $data['class']->display_name }}@if($data['batch']) - {{ $data['batch']->name }}@endif</span></td>
                    <td><strong>Academic Year:</strong> <span class="fontnormal">{{ $data['year'] }}/{{ $data['year'] + 1 }}</span></td>
                </tr>
                </tbody>
            </table>
        </div>
    @endif

    <!-- Session Table -->
    <div style="margin-top: {{ $isFirstSession || $needsNewPage ? '10px' : '20px' }};">
        <h6 class="text-center" style="margin-bottom: 5px; font-weight: bold;">{{ $session->name }}</h6>
        <table width="100%" class="table-condensed table-striped table-responsive table-bordered" border="1" style="font-size: 7px;">
            <thead>
            <tr class="result-header">
                <td rowspan="2" align="center" class="fontwhite">Pos</td>
                <td rowspan="2" align="center" class="fontwhite">Student ID</td>
                <td rowspan="2" align="center" class="fontwhite">Student Name</td>
                @foreach($data['subjects'] as $subject)
                    <td colspan="3" align="center" class="fontwhite">{{ $subject->display_name }}</td>
                @endforeach
                <td rowspan="2" align="center" class="fontwhite">Total</td>
                <td rowspan="2" align="center" class="fontwhite">Avg</td>
            </tr>
            <tr class="result-header">
                @foreach($data['subjects'] as $subject)
                    <td align="center" class="fontwhite">CA</td>
                    <td align="center" class="fontwhite">Ex</td>
                    <td align="center" class="fontwhite">Tot</td>
                @endforeach
            </tr>
            </thead>
            <tbody class="result-body" style="text-align: center; vertical-align: middle;">
            @foreach($data['masterListData'] as $studentData)
                <tr>
                    <td><strong>{{ $studentData['position_suffix'] }}</strong></td>
                    <td>{{ $studentData['student']->student_id ?? 'N/A' }}</td>
                    <td nowrap="nowrap" style="text-align: left;"><strong>{{ strtoupper($studentData['student']->name) }}</strong></td>
                    @foreach($data['subjects'] as $subject)
                        @php
                            $result = $studentData['sessions'][$session->id]['subjects'][$subject->id] ?? null;
                            $isLastSubject = $loop->last;
                        @endphp
                        <td>{{ $result['ca_score'] === '-' ? '-' : ($result['ca_score'] ?? 0) }}</td>
                        <td>{{ $result['exam_score'] === '-' ? '-' : ($result['exam_score'] ?? 0) }}</td>
                        <td style="{{ $isLastSubject ? 'border-right: 2px solid #000;' : '' }}">{{ $result['total'] === '-' ? '-' : ($result['total'] ?? 0) }}</td>
                    @endforeach
                    <td><strong>{{ $studentData['sessions'][$session->id]['grand_total'] ?? 0 }}</strong></td>
                    <td><strong>{{ $studentData['sessions'][$session->id]['average'] ?? 0 }}</strong></td>
                </tr>
            @endforeach
            </tbody>
        </table>
    </div>
@endforeach

@if(count($data['sessions']) > 0)
    </div> <!-- Close final container -->
@endif

<!-- Final Page with Annual Grades -->
<div class="page-break"></div>
<div style="width:1123px;margin:auto;margin-top:0px;padding:8px;margin-bottom:15px" class="bgimage add-border main-container">
    <!-- Header -->
    <div class="header-flex">
        <img src="{{ asset('images/rosa-mys-logo.png') }}" alt="school logo" class="school-logo">
        <div class="school-info">
            <div class="school-name">{{ $data['school_info']['name'] }}</div>
            @if($data['school_info']['address'])
            <div class="contacts">{{ $data['school_info']['address'] }}</div>
            @endif
            <div class="contacts">
                @if($data['school_info']['website'])
                    <i class="fa fa-desktop"></i> {{ $data['school_info']['website'] }}
                @endif
                @if($data['school_info']['website'] && $data['school_info']['email']) | @endif
                @if($data['school_info']['email'])
                    <i class="fa fa-envelope"></i> {{ $data['school_info']['email'] }}
                @endif
            </div>
            @if($data['school_info']['phone_1'] || $data['school_info']['phone_2'])
            <div class="contacts">
                <i class="fa fa-phone"></i> Phone: 
                {{ $data['school_info']['phone_1'] }}
                @if($data['school_info']['phone_1'] && $data['school_info']['phone_2']) , @endif
                {{ $data['school_info']['phone_2'] }}
            </div>
            @endif
        </div>
    </div>

    <!-- Title -->
    <div class="text-center report-title" style="margin-top: 8px; color: #FFF;">
        Annual Summary - {{ $data['year'] }}/{{ $data['year'] + 1 }}
    </div>

    <!-- Description -->
    <div style="margin-top: 10px;">
        <table class="table-condensed report-body2">
            <tbody>
            <tr>
                <td><strong>Class:</strong> <span class="fontnormal">{{ $data['class']->display_name }}@if($data['batch']) - {{ $data['batch']->name }}@endif</span></td>
                <td><strong>Academic Year:</strong> <span class="fontnormal">{{ $data['year'] }}/{{ $data['year'] + 1 }}</span></td>
                <td><strong>Total Students:</strong> <span class="fontnormal">{{ count($data['masterListData']) }}</span></td>
            </tr>
            </tbody>
        </table>
    </div>

    <!-- Annual Grades Table -->
    <div class="row">
        <div class="col-xs-12">
            <table width="100%" class="table-condensed table-striped table-responsive table-bordered annual-summary-table" border="1">
                <thead>
                <tr class="result-header">
                    <td rowspan="2" align="center" class="fontwhite">Pos</td>
                    @foreach($data['subjects'] as $subject)
                        <td colspan="{{ count($data['sessions']) + 2 }}" align="center" class="fontwhite">{{ $subject->display_name }}</td>
                    @endforeach
                    @php
                        $sampleStudent = $data['masterListData'][0] ?? null;
                        $sampleHelpers = $sampleStudent ? app('App\Services\AnnualResultService')->getCalculationHelpers($data['sessions'], $data['subjects'], $sampleStudent) : null;
                        $sampleAnnualMaxTotal = $sampleHelpers ? $sampleHelpers['annual_max_total'] : ($data['subjects']->count() * 100 * count($data['sessions']));
                    @endphp
                    <td rowspan="2" align="center" class="fontwhite">Annual Total ({{ $sampleAnnualMaxTotal }})</td>
                    <td rowspan="2" align="center" class="fontwhite">Total Average ({{ $data['max_total_average'] }})</td>
                    <td rowspan="2" align="center" class="fontwhite">Annual Score % (100%)</td>
                    <td colspan="6" align="center" class="fontwhite">Annual Grades</td>
                    <td rowspan="2" align="center" class="fontwhite">Status</td>
                </tr>
                <tr class="result-header">
                    @foreach($data['subjects'] as $subject)
                        @foreach($data['sessions'] as $session)
                            <td align="center" class="fontwhite">{{ $session->name }}</td>
                        @endforeach
                        <td align="center" class="fontwhite">Total</td>
                        <td align="center" class="fontwhite">Avg</td>
                    @endforeach
                    <td align="center" class="fontwhite">A</td>
                    <td align="center" class="fontwhite">B</td>
                    <td align="center" class="fontwhite">C</td>
                    <td align="center" class="fontwhite">D</td>
                    <td align="center" class="fontwhite">E</td>
                    <td align="center" class="fontwhite">F</td>
                </tr>
                </thead>
                <tbody class="result-body" style="text-align: center; vertical-align: middle;">
                @foreach($data['masterListData'] as $studentData)
                    <tr>
                        <td align="center"><strong>{{ $studentData['position_suffix'] }}</strong></td>
                        @foreach($data['subjects'] as $subject)
                            @php
                                $subjectTotal = 0;
                                $validSessions = 0;
                                $allDashes = true;
                            @endphp
                            @foreach($data['sessions'] as $session)
                                @php
                                    $result = $studentData['sessions'][$session->id]['subjects'][$subject->id] ?? null;
                                    $total = $result['total'] ?? 0;
                                    if($total !== '-') {
                                        $subjectTotal += $total;
                                        $validSessions++;
                                        $allDashes = false;
                                    }
                                @endphp
                                <td>{{ $total === '-' ? '-' : $total }}</td>
                            @endforeach
                            <td><strong>{{ $allDashes ? '-' : $subjectTotal }}</strong></td>
                            <td style="{{ $loop->last ? '' : 'border-right: 2px solid #000;' }}"><strong>{{ $allDashes ? '-' : ($validSessions > 0 ? round($subjectTotal / $validSessions, 2) : 0) }}</strong></td>
                        @endforeach
                        @php
                            $helpers = app('App\Services\AnnualResultService')->getCalculationHelpers($data['sessions'], $data['subjects'], $studentData);
                            $annualMaxTotal = $helpers['annual_max_total'];
                            $correctedAnnualAverage = $helpers['corrected_annual_average'];
                            $promotionStatus = $helpers['promotion_status'];
                        @endphp
                        <td><strong>{{ $studentData['annual_grand_total'] }}</strong></td>
                        <td><strong>{{ $studentData['total_average'] }}</strong></td>
                        <td><strong>{{ $correctedAnnualAverage }}%</strong></td>
                        <td>{{ $studentData['annual_grades']['A'] }}</td>
                        <td>{{ $studentData['annual_grades']['B'] }}</td>
                        <td>{{ $studentData['annual_grades']['C'] }}</td>
                        <td>{{ $studentData['annual_grades']['D'] }}</td>
                        <td>{{ $studentData['annual_grades']['E'] }}</td>
                        <td>{{ $studentData['annual_grades']['F'] }}</td>
                        <td style="color: {{ $promotionStatus['is_promoted'] ? 'green' : 'red' }}"><strong>{{ $promotionStatus['comment'] }}</strong></td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        </div>
    </div>

    <!-- Teachers and Timestamp Section -->
    @if(settings('show_class_teachers_on_print', true) || settings('show_timestamp', true))
    <div style="margin-top: 20px; border-top: 1px solid #ccc; padding-top: 10px;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
            @if(settings('show_class_teachers_on_print', true))
            <div>
                <strong class="result-body">Class Teachers:</strong>
                <span class="result-body2">
                    @if($data['teachers'] && $data['teachers']->count() > 0)
                        {{ $data['teachers']->pluck('name')->join(', ') }}
                    @else
                        No teachers assigned
                    @endif
                </span>
            </div>
            @endif
            @php
                $signatureType = settings('signature_type', 'head_teacher');
                $showProprietor = settings('show_proprietor_signature', false);
                $showHeadTeacher = settings('show_head_teacher_signature', true);
                $proprietorName = settings('proprietor_name', 'School Proprietor');
                $headTeacherName = settings('head_teacher_name', 'Head Teacher');
            @endphp
            @if($signatureType === 'both')
                <div style="text-align: center; display: flex; gap: 20px; justify-content: center;">
                    @if($showProprietor)
                    <div>
                        <img src="{{ asset('images/proprietor-sign.jpg') }}" style="width:70px;height:35px;border-radius:3px" alt="proprietor signature" class="img-responsive">
                        <div class="result-body2" style="margin-top: 3px;">{{ $proprietorName }}</div>
                        <div class="result-body2">Proprietor</div>
                        <div class="result-body2">{{ $data['school_info']['name'] }}</div>
                    </div>
                    @endif
                    @if($showHeadTeacher)
                    <div>
                        <img src="{{ asset('images/head-teacher-sign.jpg') }}" style="width:70px;height:35px;border-radius:3px" alt="head teacher signature" class="img-responsive">
                        <div class="result-body2" style="margin-top: 3px;">{{ $headTeacherName }}</div>
                        <div class="result-body2">Head Teacher</div>
                        <div class="result-body2">{{ $data['school_info']['name'] }}</div>
                    </div>
                    @endif
                </div>
            @elseif($signatureType === 'proprietor' && $showProprietor)
                <div style="text-align: center;">
                    <img src="{{ asset('images/proprietor-sign.jpg') }}" style="width:80px;height:40px;border-radius:3px" alt="proprietor signature" class="img-responsive">
                    <div class="result-body2" style="margin-top: 3px;">{{ $proprietorName }}</div>
                    <div class="result-body2">Proprietor</div>
                    <div class="result-body2">{{ $data['school_info']['name'] }}</div>
                </div>
            @elseif($signatureType === 'head_teacher' && $showHeadTeacher)
                <div style="text-align: center;">
                    <img src="{{ asset('images/head-teacher-sign.jpg') }}" style="width:80px;height:40px;border-radius:3px" alt="head teacher signature" class="img-responsive">
                    <div class="result-body2" style="margin-top: 3px;">{{ $headTeacherName }}</div>
                    <div class="result-body2">Head Teacher</div>
                    <div class="result-body2">{{ $data['school_info']['name'] }}</div>
                </div>
            @endif
            @if(settings('show_timestamp', true))
            <div>
                <span class="result-body2">Generated on: {{ $data['generated_at']->format('M d, Y \a\t h:i A') }}</span>
            </div>
            @endif
        </div>
    </div>
    @endif
</div>

<div class="no-print" style="margin-top: 30px; text-align: center;">
    <button class="btn btn-primary" onclick="window.print()">
        <i class="fa fa-print"></i> Print Annual Master List
    </button>
    <button class="btn btn-secondary" onclick="window.close()">
        <i class="fa fa-times"></i> Close
    </button>
</div>

</body>
</html>