@extends('admin.layouts.app')

@section('title', 'Mark Entry: ' . $subject->name)

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('result-management.index') }}">Results</a></li>
    <li class="breadcrumb-item"><a href="{{ route('result-management.students', $exam) }}">{{ $exam->name }}</a></li>
    <li class="breadcrumb-item active" aria-current="page">{{ $subject->name }}</li>
@endsection

@section('content')
<div class="row justify-content-center">
    <div class="col-12">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-primary text-white py-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-1 fw-bold text-white">{{ $subject->name }} ({{ $subject->code }})</h6>
                        <small class="text-white-50">Batch: {{ $exam->batch->name }} | Year: {{ $exam->start_date->format('Y') }}</small>
                    </div>
                    <div class="text-end">
                        <div class="badge bg-white text-primary mb-1">{{ ucfirst($rule->paper_mode) }} Mode</div>
                        <div class="small text-white-50">Pass Marks: {{ $rule->pass_marks }}</div>
                    </div>
                </div>
            </div>

            <div class="card-body p-0">
                <form method="POST" action="{{ route('result-management.subject-save', ['exam' => $exam, 'subject' => $subject]) }}">
                    @csrf
                    
                    <div class="table-responsive">
                        <table class="table table-hover table-striped align-middle mb-0 table-bordered">
                            @php
                                $cfg = is_array($rule->config) ? $rule->config : (json_decode($rule->config ?? '[]', true) ?: []);
                                
                                if (($rule->paper_mode ?? 'merged') === 'separate') {
                                    // Separate paper mode
                                    $markDist = $cfg['mark_distribution'] ?? [];
                                    $firstPaper = $markDist['first_paper'] ?? [];
                                    $secondPaper = $markDist['second_paper'] ?? [];
                                    
                                    // Get first paper marks - hide if 0 or not set
                                    $fmcqMax = ($firstPaper['mcq'] ?? 0) > 0 ? $firstPaper['mcq'] : null;
                                    $fcqMax = ($firstPaper['cq'] ?? 0) > 0 ? $firstPaper['cq'] : null;
                                    $fpracMax = ($firstPaper['practical'] ?? 0) > 0 ? $firstPaper['practical'] : null;
                                    
                                    // Get second paper marks - hide if 0 or not set
                                    $smcqMax = ($secondPaper['mcq'] ?? 0) > 0 ? $secondPaper['mcq'] : null;
                                    $scqMax = ($secondPaper['cq'] ?? 0) > 0 ? $secondPaper['cq'] : null;
                                    $spracMax = ($secondPaper['practical'] ?? 0) > 0 ? $secondPaper['practical'] : null;
                                } else {
                                    // Merged mode - get marks from config root
                                    $mcqMax = ($cfg['mcq'] ??  0) > 0 ? $cfg['mcq'] : null;
                                    $cqMax = ($cfg['cq'] ?? 0) > 0 ? $cfg['cq'] : null;
                                    $pracMax = ($cfg['practical'] ?? 0) > 0 ? $cfg['practical'] : null;
                                }
                            @endphp
                            <thead class="bg-light sticky-top" style="z-index: 5;">
                                <tr>
                                    <th class="ps-3" style="width: 80px;">Roll</th>
                                    <th style="min-width: 150px;">Student Name</th>
                                    @if(($rule->paper_mode ?? 'merged') === 'separate')
                                        @if($fmcqMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">1st MCQ</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $fmcqMax }}</div></th> @endif
                                        @if($fcqMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">1st CQ</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $fcqMax }}</div></th> @endif
                                        @if($fpracMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">1st Prac</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $fpracMax }}</div></th> @endif
                                        
                                        @if($subject->has_second_paper)
                                            @if($smcqMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">2nd MCQ</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $smcqMax }}</div></th> @endif
                                            @if($scqMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">2nd CQ</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $scqMax }}</div></th> @endif
                                            @if($spracMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">2nd Prac</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $spracMax }}</div></th> @endif
                                        @endif
                                    @else
                                        @if($mcqMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">MCQ</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $mcqMax }}</div></th> @endif
                                        @if($cqMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">CQ</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $cqMax }}</div></th> @endif
                                        @if($pracMax !== null) <th class="text-center bg-white" style="width: 100px;"><div class="small fw-bold">Prac</div><div class="badge bg-light text-muted border text-dark fw-normal">Max: {{ $pracMax }}</div></th> @endif
                                    @endif
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($students as $st)
                                    @php $prev = $existing->get($st->id); @endphp
                                    <tr>
                                        <td class="ps-3 fw-bold text-muted">{{ $st->class_roll }}</td>
                                        <td class="fw-bold text-dark">{{ $st->name }}
                                            <input type="hidden" name="marks[{{$loop->index}}][student_id]" value="{{ $st->id }}">
                                        </td>

                                        @if(($rule->paper_mode ?? 'merged') === 'separate')
                                            {{-- First Paper --}}
                                            @if($fmcqMax !== null)
                                                <td class="p-1"><input type="number" step="0.01" min="0" max="{{ $fmcqMax }}" name="marks[{{$loop->index}}][first_paper_mcq]" value="{{ $prev->first_paper_mcq ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                            @endif
                                            @if($fcqMax !== null)
                                                 <td class="p-1"><input type="number" step="0.01" min="0" max="{{ $fcqMax }}" name="marks[{{$loop->index}}][first_paper_cq]" value="{{ $prev->first_paper_cq ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                            @endif
                                            @if($fpracMax !== null)
                                                 <td class="p-1"><input type="number" step="0.01" min="0" max="{{ $fpracMax }}" name="marks[{{$loop->index}}][first_paper_practical]" value="{{ $prev->first_paper_practical ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                            @endif
                                            
                                            {{-- Second Paper --}}
                                            @if($subject->has_second_paper)
                                                @if($smcqMax !== null)
                                                    <td class="p-1 bg-light"><input type="number" step="0.01" min="0" max="{{ $smcqMax }}" name="marks[{{$loop->index}}][second_paper_mcq]" value="{{ $prev->second_paper_mcq ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                                @endif
                                                @if($scqMax !== null)
                                                    <td class="p-1 bg-light"><input type="number" step="0.01" min="0" max="{{ $scqMax }}" name="marks[{{$loop->index}}][second_paper_cq]" value="{{ $prev->second_paper_cq ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                                @endif
                                                @if($spracMax !== null)
                                                    <td class="p-1 bg-light"><input type="number" step="0.01" min="0" max="{{ $spracMax }}" name="marks[{{$loop->index}}][second_paper_practical]" value="{{ $prev->second_paper_practical ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                                @endif
                                            @endif
                                        @else
                                            {{-- Merged Mode --}}
                                            @if($mcqMax !== null)
                                                <td class="p-1"><input type="number" step="0.01" min="0" max="{{ $mcqMax }}" name="marks[{{$loop->index}}][first_paper_mcq]" value="{{ $prev->first_paper_mcq ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                            @endif
                                            @if($cqMax !== null)
                                                <td class="p-1"><input type="number" step="0.01" min="0" max="{{ $cqMax }}" name="marks[{{$loop->index}}][first_paper_cq]" value="{{ $prev->first_paper_cq ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                            @endif
                                            @if($pracMax !== null)
                                                <td class="p-1"><input type="number" step="0.01" min="0" max="{{ $pracMax }}" name="marks[{{$loop->index}}][first_paper_practical]" value="{{ $prev->first_paper_practical ?? '' }}" class="form-control form-control-sm text-center fw-bold mark-input" placeholder="-"></td>
                                            @endif
                                        @endif
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>

                    <div class="card-footer bg-white py-3 sticky-bottom border-top shadow-sm" style="bottom: 0; z-index: 10;">
                        <div class="d-flex justify-content-between align-items-center">
                            <a href="{{ route('result-management.students', $exam) }}" class="btn btn-light border px-4">Cancel</a>
                            <button type="submit" class="btn btn-primary px-5 shadow-sm fw-bold"><i class="bi bi-save me-2"></i> Save All Marks</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
    /* Focus effect specifically for mark inputs to highlight the active cell clearly */
    .mark-input:focus {
        background-color: #fff;
        border-color: #86b7fe;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        z-index: 5;
        position: relative;
        transform: scale(1.05); /* Slight zoom on focus */
    }
    .sticky-bottom {
        position: sticky;
        bottom: 0;
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Validation logic
        const inputs = document.querySelectorAll('.mark-input');
        
        inputs.forEach(input => {
            input.addEventListener('input', function() {
                const max = parseFloat(this.getAttribute('max'));
                const val = parseFloat(this.value);
                
                if (val > max) {
                    this.classList.add('is-invalid');
                    // Optional: Reset to max? or just warn. Let's strict warn.
                    this.value = max;
                    // Flash red
                    this.style.backgroundColor = '#ffe6e6';
                    setTimeout(() => {
                        this.style.backgroundColor = '';
                        this.classList.remove('is-invalid');
                    }, 500);
                } else if (val < 0) {
                     this.value = 0;
                }
            });

            // Arrow key navigation (Basic up/down)
            input.addEventListener('keydown', function(e) {
                if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter') {
                    // This is a bit complex due to grid but we can try basic next/prev in DOM order
                    // Real grid nav requires finding the index in the row and moving to next row same index
                }
            });
        });
    });
</script>
@endsection
