@extends('layouts.app')
@section('title', 'Result Card')
@section('page_title', 'Result Card')
@section('breadcrumbs')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Home</a></li><li class="breadcrumb-item active">Result Card</li>
@endsection

@section('content')
    <div class="card mb-3 no-print"><div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-5"><label class="form-label small">Exam</label>
                <select name="exam_id" class="form-select form-select-sm">
                    <option value="">— Select exam —</option>
                    @foreach($exams as $e)<option value="{{ $e->id }}" @selected($exam && $exam->id==$e->id)>{{ $e->name }}</option>@endforeach
                </select></div>
            <div class="col-md-5"><label class="form-label small">Student</label>
                <select name="student_id" class="form-select form-select-sm js-select2">
                    <option value="">— Select student —</option>
                    @foreach($students as $s)<option value="{{ $s->id }}" @selected($student && $student->id==$s->id)>{{ $s->name }} ({{ $s->admission_number }})</option>@endforeach
                </select></div>
            <div class="col-md-2"><button class="btn btn-sm btn-primary w-100"><i class="bi bi-search me-1"></i>View</button></div>
        </form>
    </div></div>

    @if($exam && $student && $result)
        @php
            $branch    = $student->branch;
            $logo      = $branch?->logo ? asset('storage/'.ltrim($branch->logo, '/')) : '';
            $photo     = $student->photo ? asset('storage/'.ltrim($student->photo, '/')) : '';
            $session   = $exam->academicSession?->name ?? \App\Models\AcademicSession::current()?->name;
            $overall   = $grades->firstWhere('grade', $result['grade']);
            $remark    = $overall?->remark ?? ($result['status'] === 'Pass' ? 'Passed' : 'Needs Improvement');
            $addr      = trim(($branch?->address ?? '').(($branch?->address && $branch?->city) ? ', ' : '').($branch?->city ?? ''));
            $failCount = collect($result['rows'])->where('pass', false)->count();
        @endphp

        @if(!$exam->is_published)<div class="alert alert-warning small no-print"><i class="bi bi-exclamation-triangle me-1"></i>This exam's results are not published yet (visible to staff only).</div>@endif

        <div class="rc-toolbar no-print">
            <button onclick="window.print()" class="btn btn-sm btn-primary"><i class="bi bi-printer me-1"></i>Print Result Card</button>
        </div>

        <div class="rc-sheet">
          <div class="rc-frame">
            {{-- Watermark --}}
            @if($logo)<div class="rc-wm" style="background-image:url('{{ $logo }}')"></div>@endif

            {{-- Header --}}
            <div class="rc-head">
                @if($logo)<img class="rc-logo" src="{{ $logo }}" onerror="this.style.display='none'">@else<div class="rc-logo rc-logo-ph">{{ strtoupper(mb_substr($branch?->name ?? 'S',0,1)) }}</div>@endif
                <div class="rc-head-mid">
                    <div class="rc-school">{{ $branch?->name ?? config('app.name') }}</div>
                    @if($addr)<div class="rc-addr">{{ $addr }}</div>@endif
                    @if($branch?->phone)<div class="rc-addr">Phone: {{ $branch->phone }}@if($branch?->email) &nbsp;•&nbsp; {{ $branch->email }}@endif</div>@endif
                    <div class="rc-title">Progress Report / Result Card</div>
                </div>
                @if($photo)<img class="rc-photo" src="{{ $photo }}" onerror="this.style.display='none'">@else<div class="rc-photo rc-photo-ph"><i class="bi bi-person"></i></div>@endif
            </div>

            <div class="rc-exam-band">
                <span>{{ $exam->name }}</span>
                @if($session)<span class="rc-session">Session {{ $session }}</span>@endif
            </div>

            {{-- Student info --}}
            <table class="rc-info">
                <tr>
                    <th>Student Name</th><td>{{ $student->name }}</td>
                    <th>Roll No.</th><td>{{ $student->roll_number ?: '—' }}</td>
                </tr>
                <tr>
                    <th>Father Name</th><td>{{ $student->family?->father_name ?: '—' }}</td>
                    <th>Admission No.</th><td>{{ $student->admission_number }}</td>
                </tr>
                <tr>
                    <th>Class / Section</th><td>{{ $student->schoolClass?->name }}{{ $student->section ? ' — '.$student->section->name : '' }}</td>
                    <th>Position</th><td>{{ $position ? $position.($classSize ? ' of '.$classSize : '') : '—' }}</td>
                </tr>
            </table>

            {{-- Marks --}}
            <table class="rc-marks">
                <thead>
                    <tr>
                        <th class="l">#</th>
                        <th class="l">Subject</th>
                        <th>Total</th>
                        <th>Passing</th>
                        <th>Obtained</th>
                        <th>%</th>
                        <th>Grade</th>
                        <th>Remarks</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($result['rows'] as $i => $row)
                        @php $rBand = $grades->firstWhere('grade', $row['grade']); @endphp
                        <tr class="{{ $row['pass'] ? '' : 'rc-fail' }}">
                            <td class="l">{{ $i + 1 }}</td>
                            <td class="l">{{ $row['subject'] }}</td>
                            <td>{{ number_format($row['total']) }}</td>
                            <td>{{ number_format($row['passing']) }}</td>
                            <td class="b">{{ $row['absent'] ? 'ABS' : number_format($row['obtained']) }}</td>
                            <td>{{ $row['percentage'] }}%</td>
                            <td class="b">{{ $row['grade'] }}</td>
                            <td class="rc-rem">{{ $row['absent'] ? 'Absent' : ($rBand?->remark ?? ($row['pass'] ? 'Pass' : 'Fail')) }}</td>
                        </tr>
                    @endforeach
                </tbody>
                <tfoot>
                    <tr>
                        <td class="l" colspan="2">GRAND TOTAL</td>
                        <td>{{ number_format($result['total_max']) }}</td>
                        <td>—</td>
                        <td class="b">{{ number_format($result['total_obtained']) }}</td>
                        <td class="b">{{ $result['percentage'] }}%</td>
                        <td class="b">{{ $result['grade'] }}</td>
                        <td class="rc-rem">{{ $remark }}</td>
                    </tr>
                </tfoot>
            </table>

            {{-- Summary strip --}}
            <div class="rc-summary">
                <div class="rc-sum"><span>Obtained</span><b>{{ number_format($result['total_obtained']) }} / {{ number_format($result['total_max']) }}</b></div>
                <div class="rc-sum"><span>Percentage</span><b>{{ $result['percentage'] }}%</b></div>
                <div class="rc-sum"><span>Grade</span><b>{{ $result['grade'] }}</b></div>
                <div class="rc-sum"><span>GPA</span><b>{{ number_format($result['gpa'], 2) }}</b></div>
                <div class="rc-sum rc-sum-res {{ $result['status'] === 'Pass' ? 'ok' : 'no' }}"><span>Result</span><b>{{ strtoupper($result['status']) }}</b></div>
            </div>

            {{-- Grading scale legend --}}
            @if($grades->isNotEmpty())
                <div class="rc-legend">
                    <span class="rc-legend-t">Grading Scale:</span>
                    @foreach($grades as $g)
                        <span class="rc-legend-i"><b>{{ $g->grade }}</b> {{ rtrim(rtrim(number_format($g->min_percentage,0),'0'),'.') }}–{{ rtrim(rtrim(number_format($g->max_percentage,0),'0'),'.') }}%@if($g->remark) ({{ $g->remark }})@endif</span>
                    @endforeach
                </div>
            @endif

            {{-- Footer: remarks + signatures --}}
            <div class="rc-foot">
                <div class="rc-remark-box">
                    <div class="rc-remark-title">Class Teacher's Remarks</div>
                    <div class="rc-remark-line">
                        @if($result['status'] !== 'Pass')
                            {{ $student->name }} needs to improve in {{ $failCount }} subject(s). Keep working hard.
                        @elseif($result['percentage'] >= 80)
                            Outstanding performance. Keep it up!
                        @elseif($result['percentage'] >= 60)
                            Good effort. There is still room to improve.
                        @else
                            Satisfactory. More consistent effort is encouraged.
                        @endif
                    </div>
                </div>
                <div class="rc-signs">
                    <div class="rc-sign"><span>Class Teacher</span></div>
                    <div class="rc-sign"><span>Examination In-charge</span></div>
                    <div class="rc-sign"><span>Principal</span></div>
                </div>
            </div>

            <div class="rc-issued">
                Issued on {{ now()->format('d M Y') }} · This is a computer-generated result card.
            </div>
          </div>
        </div>
    @elseif($exam || $student)
        <div class="card"><div class="card-body text-center text-muted py-4">Select both an exam and a student.</div></div>
    @endif
@endsection

@push('styles')
<style>
    .rc-toolbar{max-width:820px;margin:0 auto 12px;text-align:right}
    .rc-sheet{max-width:820px;margin:0 auto;background:#fff;padding:22px;border-radius:8px;box-shadow:0 2px 14px rgba(15,30,60,.10)}
    .rc-frame{position:relative;border:2px solid #16324f;padding:16px 18px;color:#14202e;font-family:'Segoe UI',Arial,sans-serif}
    .rc-frame::before{content:"";position:absolute;inset:4px;border:1px solid #b7c4d4;pointer-events:none}
    .rc-wm{position:absolute;inset:0;background-repeat:no-repeat;background-position:center;background-size:58%;opacity:.05;pointer-events:none}

    .rc-head{display:flex;align-items:center;gap:14px;position:relative}
    .rc-logo{width:66px;height:66px;object-fit:contain;flex:0 0 auto}
    .rc-logo-ph{display:flex;align-items:center;justify-content:center;background:#16324f;color:#fff;border-radius:8px;font-size:30px;font-weight:700}
    .rc-head-mid{flex:1;text-align:center}
    .rc-school{font-size:23px;font-weight:800;letter-spacing:.5px;color:#16324f;text-transform:uppercase;line-height:1.1}
    .rc-addr{font-size:11px;color:#4a5b6d}
    .rc-title{margin-top:5px;font-size:13px;font-weight:700;color:#b3541e;text-transform:uppercase;letter-spacing:1.5px}
    .rc-photo{width:74px;height:88px;object-fit:cover;border:1px solid #16324f;flex:0 0 auto}
    .rc-photo-ph{display:flex;align-items:center;justify-content:center;background:#eef2f6;color:#9fb0c0;font-size:34px}

    .rc-exam-band{margin:12px 0 10px;background:#16324f;color:#fff;padding:6px 12px;display:flex;justify-content:space-between;align-items:center;font-weight:700;font-size:13px;letter-spacing:.5px}
    .rc-session{font-weight:500;font-size:12px;opacity:.9}

    .rc-info{width:100%;border-collapse:collapse;font-size:12.5px;margin-bottom:12px}
    .rc-info th,.rc-info td{border:1px solid #c7d2de;padding:5px 9px;text-align:left}
    .rc-info th{background:#eef3f8;color:#16324f;font-weight:700;width:15%;white-space:nowrap}
    .rc-info td{width:35%}

    .rc-marks{width:100%;border-collapse:collapse;font-size:12.5px}
    .rc-marks th,.rc-marks td{border:1px solid #b9c6d4;padding:6px 8px;text-align:center}
    .rc-marks thead th{background:#16324f;color:#fff;font-weight:700;font-size:11.5px;text-transform:uppercase;letter-spacing:.3px}
    .rc-marks td.l,.rc-marks th.l{text-align:left}
    .rc-marks tbody tr:nth-child(even){background:#f6f9fc}
    .rc-marks .b{font-weight:700}
    .rc-marks .rc-rem{font-size:11px;color:#51606f}
    .rc-marks tr.rc-fail td{color:#b02a1e}
    .rc-marks tr.rc-fail .b{color:#b02a1e}
    .rc-marks tfoot td{background:#eef3f8;font-weight:700;color:#16324f;border-top:2px solid #16324f}

    .rc-summary{display:flex;gap:8px;margin:12px 0}
    .rc-sum{flex:1;border:1px solid #c7d2de;border-radius:6px;text-align:center;padding:7px 4px;background:#f9fbfd}
    .rc-sum span{display:block;font-size:10px;text-transform:uppercase;letter-spacing:.5px;color:#6a7a8b}
    .rc-sum b{font-size:16px;color:#16324f}
    .rc-sum-res.ok{background:#e9f7ee;border-color:#8fd3a6}
    .rc-sum-res.ok b{color:#1c7a3e}
    .rc-sum-res.no{background:#fdecea;border-color:#f0a89f}
    .rc-sum-res.no b{color:#b02a1e}

    .rc-legend{font-size:10.5px;color:#4a5b6d;border:1px dashed #c7d2de;border-radius:6px;padding:6px 9px;margin-bottom:14px;line-height:1.7}
    .rc-legend-t{font-weight:700;color:#16324f;margin-right:6px}
    .rc-legend-i{display:inline-block;margin-right:12px;white-space:nowrap}
    .rc-legend-i b{color:#16324f}

    .rc-foot{display:flex;gap:16px;align-items:flex-end;margin-top:6px}
    .rc-remark-box{flex:1}
    .rc-remark-title{font-size:11px;font-weight:700;color:#16324f;text-transform:uppercase;letter-spacing:.5px;margin-bottom:3px}
    .rc-remark-line{border:1px solid #c7d2de;border-radius:6px;padding:8px 10px;font-size:12px;min-height:42px;background:#f9fbfd}
    .rc-signs{display:flex;gap:22px}
    .rc-sign{text-align:center;padding-top:26px}
    .rc-sign span{border-top:1px solid #16324f;padding-top:3px;font-size:11px;font-weight:600;color:#16324f;display:block;min-width:110px}

    .rc-issued{text-align:center;font-size:10px;color:#8091a2;margin-top:12px;font-style:italic}

    @media print{
        @page{ size:A4 portrait; margin:10mm; }
        .sms-sidebar,.sms-topbar,.sms-topmenu,.sms-backdrop,.page-head,footer,.no-print{display:none !important;}
        .sms-content,.content-wrap,main{margin:0 !important;padding:0 !important;}
        .rc-sheet{max-width:100%;box-shadow:none;padding:0;border-radius:0;}
        .rc-frame{border-color:#000;}
        body{background:#fff !important;}
        -webkit-print-color-adjust:exact; print-color-adjust:exact;
    }
</style>
@endpush
