<div>
    <!--[if BLOCK]><![endif]--><?php if(!$canUploadResults): ?>
        <div class="alert alert-warning mb-4">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <?php echo e($uploadDisabledMessage); ?>

        </div>
    <?php endif; ?><!--[if ENDBLOCK]><![endif]-->
    
    <!--[if BLOCK]><![endif]--><?php if($hasApprovedResults && !$canEditApprovedResults): ?>
        <div class="card border-info mb-4">
            <div class="card-header bg-info text-white">
                <h6 class="mb-0">
                    <i class="fas fa-check-circle me-2"></i>
                    Results Already Approved
                </h6>
            </div>
            <div class="card-body">
                <p class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>
                    The student's results for the selected session have already been approved and cannot be modified.
                </p>
            </div>
        </div>
    <?php endif; ?><!--[if ENDBLOCK]><![endif]-->
    
    <form wire:submit.prevent="saveResults" <?php echo e(!$canUploadResults ? 'style=pointer-events:none;opacity:0.6;' : ''); ?>>
        <!-- Search Row -->
        <div class="row mb-4">
            <div class="col-lg-6 col-md-8">
                <label for="searchTerm" class="form-label">Search Student</label>
                <input type="text"
                       wire:model.live="searchTerm"
                       class="form-control"
                       id="searchTerm"
                       placeholder="Search by name, email, or student ID...">

                <!--[if BLOCK]><![endif]--><?php if($showSearchResults && !empty($searchResults)): ?>
                    <div class="mt-1">
                        <!--[if BLOCK]><![endif]--><?php $__currentLoopData = $searchResults; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $student): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="p-2 border rounded mb-1 cursor-pointer hover-bg-light"
                                 wire:click="selectStudent(<?php echo e($student->id); ?>)"
                                 style="cursor: pointer; font-size: 0.875rem;">
                                <strong><?php echo e($student->name); ?></strong> - <?php echo e($student->student_id); ?>

                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><!--[if ENDBLOCK]><![endif]-->
                    </div>
                <?php endif; ?><!--[if ENDBLOCK]><![endif]-->

                <!--[if BLOCK]><![endif]--><?php $__errorArgs = ['selectedStudent'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                <div class="text-danger"><?php echo e($message); ?></div> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><!--[if ENDBLOCK]><![endif]-->
            </div>
        </div>
        
        <!-- Selection Row -->
        <div class="row mb-4">
            <div class="col-md-6 col-lg-2">
                <label for="selectedClass" class="form-label">Select Class</label>
                <select wire:model.live="selectedClass" class="form-select" id="selectedClass">
                    <option value="">Choose a class...</option>
                    <!--[if BLOCK]><![endif]--><?php $__currentLoopData = $classes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $class): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($class->id); ?>" <?php echo e($selectedClass == $class->id ? 'selected' : ''); ?>><?php echo e($class->display_name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><!--[if ENDBLOCK]><![endif]-->
                </select>
                <!--[if BLOCK]><![endif]--><?php $__errorArgs = ['selectedClass'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                <div class="text-danger"><?php echo e($message); ?></div> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><!--[if ENDBLOCK]><![endif]-->
            </div>
            <div class="col-md-6 col-lg-2">
                <label for="selectedBatch" class="form-label">Select Batch</label>
                <select wire:model.live="selectedBatch" class="form-select" id="selectedBatch">
                    <option value="">Choose a batch...</option>
                    <!--[if BLOCK]><![endif]--><?php $__currentLoopData = $batches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $batch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($batch->id); ?>" <?php echo e($selectedBatch == $batch->id ? 'selected' : ''); ?>><?php echo e($batch->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><!--[if ENDBLOCK]><![endif]-->
                </select>
                <!--[if BLOCK]><![endif]--><?php $__errorArgs = ['selectedBatch'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                <div class="text-danger"><?php echo e($message); ?></div> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><!--[if ENDBLOCK]><![endif]-->
            </div>
            <div class="col-md-6 col-lg-3">
                <label class="form-label">Select Student</label>
                <select wire:model.live="selectedStudent" class="form-select">
                    <option value="">Choose a student...</option>
                    <!--[if BLOCK]><![endif]--><?php $__currentLoopData = $students; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $student): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($student->id); ?>" <?php echo e($selectedStudent == $student->id ? 'selected' : ''); ?>><?php echo e($student->name); ?> (<?php echo e($student->student_id); ?>)</option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><!--[if ENDBLOCK]><![endif]-->
                </select>
            </div>
            <div class="col-md-6 col-lg-3">
                <label for="selectedSession" class="form-label">Select Session</label>
                <select wire:model.live="selectedSession" class="form-select" id="selectedSession">
                    <option value="">Choose a session...</option>
                    <!--[if BLOCK]><![endif]--><?php $__currentLoopData = $sessions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $session): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($session->id); ?>" <?php echo e($selectedSession == $session->id ? 'selected' : ''); ?>><?php echo e($session->name); ?> (<?php echo e($session->start_year); ?>/<?php echo e($session->end_year); ?>)</option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><!--[if ENDBLOCK]><![endif]-->
                </select>
                <!--[if BLOCK]><![endif]--><?php $__errorArgs = ['selectedSession'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                <div class="text-danger"><?php echo e($message); ?></div> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><!--[if ENDBLOCK]><![endif]-->
            </div>
            <div class="col-md-12 col-lg-2 d-flex align-items-center">
                <!--[if BLOCK]><![endif]--><?php if(($selectedStudent && $selectedSession) || (!empty($searchTerm) && $selectedSession)): ?>
                    <button type="button"
                            wire:click="loadResults"
                            class="btn btn-primary w-100 mt-3 mt-lg-0"
                            wire:loading.attr="disabled"
                            wire:target="loadResults">
                        <span wire:loading.remove wire:target="loadResults">
                            <i class="fas fa-sync me-2"></i>Load
                        </span>
                        <span wire:loading wire:target="loadResults">
                            <i class="fas fa-spinner fa-spin me-2"></i>Loading...
                        </span>
                    </button>
                <?php endif; ?><!--[if ENDBLOCK]><![endif]-->
            </div>
        </div>

        <!--[if BLOCK]><![endif]--><?php if(!empty($subjects)): ?>
            <div class="mb-3">
                <h5>
                    Student: <?php echo e($students->find($selectedStudent)->name ?? 'N/A'); ?>

                    -
                    Batch: <?php echo e($selectedBatch ? ($batches->where('id', $selectedBatch)->first()->name ?? 'N/A') : 'N/A'); ?></h5>
            </div>
            <div class="<?php echo e(($hasApprovedResults && !$canEditApprovedResults) ? 'position-relative' : ''); ?>">
                <!--[if BLOCK]><![endif]--><?php if($hasApprovedResults && !$canEditApprovedResults): ?>
                    <div class="position-absolute w-100 h-100" style="background: rgba(255,255,255,0.7); z-index: 10; pointer-events: none;"></div>
                <?php endif; ?><!--[if ENDBLOCK]><![endif]-->
                <div class="table-responsive" <?php echo e(($hasApprovedResults && !$canEditApprovedResults) ? 'style=pointer-events:none;opacity:0.6;' : ''); ?>>
                    <table class="table table-bordered">
                        <thead class="table-light">
                        <tr>
                            <th class="subject-column">Subject</th>
                            <th>CA Score</th>
                            <th>CA Abs</th>
                            <th>Exam Score</th>
                            <th>Exam Abs</th>
                            <th>Total</th>
                        </tr>
                        </thead>
                        <tbody>
                        <!--[if BLOCK]><![endif]--><?php $__currentLoopData = $subjects; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $subject): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <tr>
                                <td class="subject-column"><?php echo e($subject->display_name); ?></td>
                                <td style="min-width: 120px;">
                                    <input type="number"
                                           wire:model.defer="results.<?php echo e($subject->id); ?>.ca_score"
                                           class="form-control result-input"
                                           data-subject="<?php echo e($subject->id); ?>"
                                           data-field="ca_score"
                                           style="width: 110px;"
                                           min="0"
                                           max="<?php echo e($sessions->find($selectedSession)->ca_max_score ?? 100); ?>"
                                           step="1"
                                           tabindex="<?php echo e($loop->iteration * 2 - 1); ?>"
                                        <?php echo e(($results[$subject->id]['ca_absent'] ?? false) ? 'disabled' : ''); ?>>
                                    <!--[if BLOCK]><![endif]--><?php $__errorArgs = ["results.{$subject->id}.ca_score"];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="text-danger small"><?php echo e($message); ?></div> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><!--[if ENDBLOCK]><![endif]-->
                                </td>
                                <td>
                                    <div class="form-check">
                                        <input type="checkbox"
                                               wire:model.defer="results.<?php echo e($subject->id); ?>.ca_absent"
                                               class="form-check-input absent-checkbox"
                                               data-subject="<?php echo e($subject->id); ?>"
                                               data-field="ca_absent"
                                               data-target="ca_score"
                                               id="ca_absent_<?php echo e($subject->id); ?>">
                                        <label class="form-check-label" for="ca_absent_<?php echo e($subject->id); ?>">Abs</label>
                                    </div>
                                </td>
                                <td style="min-width: 120px;">
                                    <input type="number"
                                           wire:model.defer="results.<?php echo e($subject->id); ?>.exam_score"
                                           class="form-control result-input"
                                           data-subject="<?php echo e($subject->id); ?>"
                                           data-field="exam_score"
                                           style="width: 110px;"
                                           min="0"
                                           max="<?php echo e($sessions->find($selectedSession)->exam_max_score ?? 100); ?>"
                                           step="1"
                                           tabindex="<?php echo e($loop->iteration * 2); ?>"
                                        <?php echo e(($results[$subject->id]['exam_absent'] ?? false) ? 'disabled' : ''); ?>>
                                    <!--[if BLOCK]><![endif]--><?php $__errorArgs = ["results.{$subject->id}.exam_score"];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="text-danger small"><?php echo e($message); ?></div> <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><!--[if ENDBLOCK]><![endif]-->
                                </td>
                                <td>
                                    <div class="form-check">
                                        <input type="checkbox"
                                               wire:model.defer="results.<?php echo e($subject->id); ?>.exam_absent"
                                               class="form-check-input absent-checkbox"
                                               data-subject="<?php echo e($subject->id); ?>"
                                               data-field="exam_absent"
                                               data-target="exam_score"
                                               id="exam_absent_<?php echo e($subject->id); ?>">
                                        <label class="form-check-label" for="exam_absent_<?php echo e($subject->id); ?>">Abs</label>
                                    </div>
                                </td>
                                <td>
                                    <strong class="total-display" data-subject="<?php echo e($subject->id); ?>">
                                        <!--[if BLOCK]><![endif]--><?php if(isset($results[$subject->id])): ?>
                                            <?php echo e((floatval($results[$subject->id]['ca_score'] ?? 0)) + (floatval($results[$subject->id]['exam_score'] ?? 0))); ?>

                                        <?php else: ?>
                                            0
                                        <?php endif; ?><!--[if ENDBLOCK]><![endif]-->
                                    </strong>
                                </td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><!--[if ENDBLOCK]><![endif]-->
                        </tbody>
                    </table>
                </div>

                <div class="d-flex justify-content-end mt-3" <?php echo e(($hasApprovedResults && !$canEditApprovedResults) ? 'style=pointer-events:none;opacity:0.6;' : ''); ?>>
                    <button type="submit" class="btn btn-success btn-lg">
                        <i class="fas fa-save me-2"></i>Save Results
                    </button>
                </div>
            </div>
        <?php endif; ?><!--[if ENDBLOCK]><![endif]-->
    </form>
</div>

<script>
    let updateCounter = 0;
    let pendingUpdates = new Set();

    document.addEventListener('input', function (e) {
        if (e.target.type === 'number' && e.target.hasAttribute('max')) {
            const max = parseInt(e.target.getAttribute('max'));
            const value = parseInt(e.target.value);
            if (value > max) {
                e.target.setCustomValidity(`Value must not exceed ${max}`);
                e.target.reportValidity();
            } else {
                e.target.setCustomValidity('');
            }
        }
        
        // Track result input changes
        if (e.target.classList.contains('result-input')) {
            const subjectId = e.target.dataset.subject;
            
            // Update total instantly
            updateTotal(subjectId);
            
            if (!pendingUpdates.has(subjectId)) {
                pendingUpdates.add(subjectId);
                updateCounter++;
                
                if (updateCounter >= 10) {
                    saveUpdates();
                }
            }
        }
    });
    
    document.addEventListener('change', function (e) {
        // Handle absent checkbox changes
        if (e.target.classList.contains('absent-checkbox')) {
            const subjectId = e.target.dataset.subject;
            const targetField = e.target.dataset.target;
            
            // Disable/enable corresponding input
            const targetInput = document.querySelector(
                `input[data-subject="${subjectId}"][data-field="${targetField}"]`
            );
            
            if (targetInput) {
                if (e.target.checked) {
                    targetInput.value = 0;
                    targetInput.disabled = true;
                } else {
                    targetInput.disabled = false;
                }
            }
            
            // Update total instantly
            updateTotal(subjectId);
            
            if (!pendingUpdates.has(subjectId)) {
                pendingUpdates.add(subjectId);
                updateCounter++;
                
                if (updateCounter >= 10) {
                    saveUpdates();
                }
            }
        }
    });
    
    function updateTotal(subjectId) {
        const caInput = document.querySelector(`input[data-subject="${subjectId}"][data-field="ca_score"]`);
        const examInput = document.querySelector(`input[data-subject="${subjectId}"][data-field="exam_score"]`);
        const totalDisplay = document.querySelector(`.total-display[data-subject="${subjectId}"]`);
        
        if (caInput && examInput && totalDisplay) {
            const caScore = parseFloat(caInput.value) || 0;
            const examScore = parseFloat(examInput.value) || 0;
            const total = caScore + examScore;
            totalDisplay.textContent = total;
        }
    }
    
    function saveUpdates() {
        if (updateCounter > 0) {
            window.Livewire.find('<?php echo e($_instance->getId()); ?>').call('processPendingUpdates');
            updateCounter = 0;
            pendingUpdates.clear();
        }
    }
    
    // Save any remaining updates before form submission
    document.addEventListener('livewire:init', () => {
        Livewire.hook('commit', ({ component, commit, respond, succeed, fail }) => {
            if (component.name === 'results.by-student-form') {
                saveUpdates();
            }
        });
    });
</script>
<?php /**PATH C:\wamp64\www\edu-p\resources\views/livewire/results/by-student-form.blade.php ENDPATH**/ ?>