

<?php $__env->startSection('title', 'Edit Student: ' . $student->name); ?>

<?php $__env->startSection('content'); ?>

<form action="<?php echo e(route('students.update', $student->id)); ?>" method="POST" enctype="multipart/form-data">
    <?php echo csrf_field(); ?>
    <?php echo method_field('PUT'); ?>
    
    <div class="row g-4 mb-5 pb-5">
        <!-- Info Column -->
        <div class="col-12 col-lg-8">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-bold text-primary">Student Information</h6>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-12"><label class="form-label">Full Name *</label><input type="text" name="name" class="form-control" required value="<?php echo e(old('name', $student->name)); ?>"></div>
                        <div class="col-md-6"><label class="form-label">Father's Name *</label><input type="text" name="father_name" class="form-control" required value="<?php echo e(old('father_name', $student->father_name)); ?>"></div>
                        <div class="col-md-6"><label class="form-label">Mother's Name *</label><input type="text" name="mother_name" class="form-control" required value="<?php echo e(old('mother_name', $student->mother_name)); ?>"></div>
                        <div class="col-md-6">
                            <label class="form-label">Date of Birth *</label>
                            <div class="row g-2">
                                <div class="col-3">
                                    <select class="form-select" id="dob_day" required>
                                        <option value="">Day</option>
                                        <!-- JS populated -->
                                    </select>
                                </div>
                                <div class="col-5">
                                    <select class="form-select" id="dob_month" required>
                                        <option value="">Month</option>
                                        <option value="01">Jan</option>
                                        <option value="02">Feb</option>
                                        <option value="03">Mar</option>
                                        <option value="04">Apr</option>
                                        <option value="05">May</option>
                                        <option value="06">Jun</option>
                                        <option value="07">Jul</option>
                                        <option value="08">Aug</option>
                                        <option value="09">Sep</option>
                                        <option value="10">Oct</option>
                                        <option value="11">Nov</option>
                                        <option value="12">Dec</option>
                                    </select>
                                </div>
                                <div class="col-4">
                                    <select class="form-select" id="dob_year" required>
                                        <option value="">Year</option>
                                        <!-- JS populated -->
                                    </select>
                                </div>
                            </div>
                            <input type="hidden" name="date_of_birth" id="dob_hidden" value="<?php echo e(old('date_of_birth', $student->date_of_birth)); ?>">
                        </div>
                        <div class="col-md-6"><label class="form-label">Gender *</label>
                            <select name="gender" class="form-select" required>
                                <option value="">-- Select --</option>
                                <option value="Male" <?php echo e(old('gender', $student->gender) == 'Male' ? 'selected' : ''); ?>>Male</option>
                                <option value="Female" <?php echo e(old('gender', $student->gender) == 'Female' ? 'selected' : ''); ?>>Female</option>
                            </select>
                        </div>
                        <div class="col-md-6"><label class="form-label">SSC Reg No *</label><input type="text" name="ssc_reg_no" class="form-control" required value="<?php echo e(old('ssc_reg_no', $student->ssc_reg_no)); ?>"></div>
                        <div class="col-md-6"><label class="form-label">SSC Batch *</label><input type="number" name="ssc_batch" class="form-control" required value="<?php echo e(old('ssc_batch', $student->ssc_batch)); ?>"></div>
                        <div class="col-md-6"><label class="form-label">Phone</label><input type="text" name="phone" class="form-control" value="<?php echo e(old('phone', $student->phone)); ?>"></div>
                        <div class="col-md-6"><label class="form-label">Email</label><input type="email" name="email" class="form-control" value="<?php echo e(old('email', $student->email)); ?>"></div>
                        <div class="col-12"><label class="form-label">Address</label><textarea name="address" class="form-control" rows="2"><?php echo e(old('address', $student->address)); ?></textarea></div>
                    </div>
                </div>
            </div>

            <!-- Subject Selection -->
            <div class="card shadow-sm border-0 mb-4">
                 <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-bold text-primary">Academic & Subjects</h6>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-4">
                         <div class="col-md-4">
                             <label class="form-label">Class</label>
                             <select name="class" class="form-select" required>
                                 <option value="11" <?php echo e(old('class', $student->class) == 11 ? 'selected' : ''); ?>>Class XI</option>
                                 <option value="12" <?php echo e(old('class', $student->class) == 12 ? 'selected' : ''); ?>>Class XII</option>
                             </select>
                         </div>
                         <div class="col-md-4">
                             <label class="form-label">Academic Version</label>
                             <select name="academic_version_id" id="academic_version_id" class="form-select" required>
                                 <?php $__currentLoopData = $academicVersions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $v): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                     <option value="<?php echo e($v->id); ?>" <?php echo e(old('academic_version_id', $student->academic_version_id) == $v->id ? 'selected' : ''); ?>><?php echo e($v->name); ?></option>
                                 <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                             </select>
                         </div>
                         <div class="col-md-4">
                             <label class="form-label">Group</label>
                             <select name="group_code" id="group_code" class="form-select" required>
                                 <option value="">-- Select --</option>
                                 <?php $__currentLoopData = $groups; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $code => $name): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                     <option value="<?php echo e($code); ?>" <?php echo e(old('group_code', $student->group_code) == $code ? 'selected' : ''); ?>><?php echo e($name); ?></option>
                                 <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                             </select>
                         </div>
                         <!-- Batch -->
                        <div hidden>
                            <input name="batch_id" value=""> <!-- Optional internal batch -->
                        </div>
                    </div>

                    <div id="subject-loading" class="d-none text-center py-3">
                        <div class="spinner-border text-primary" role="status"></div>
                        <p class="small text-muted">Loading Subject Rules...</p>
                    </div>

                    <div id="subject-area" class="d-none">
                        <!-- Fixed Subjects -->
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="fw-bold fs-6 text-muted uppercase mb-0" style="font-size: 12px;">MANDATORY SUBJECTS</h6>
                            <span id="mandatory-counter" class="badge bg-primary">Selected: 0/6</span>
                        </div>
                        <div class="row g-2 mb-4" id="fixed-subjects-list">
                             <!-- Populated by JS -->
                        </div>

                        <!-- Buckets -->
                        <div id="buckets-area">
                             <!-- Populated by JS -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Sidebar -->
        <div class="col-12 col-lg-4">
             <div class="card shadow-sm border-0 mb-3">
                 <div class="card-body text-center">
                     <label class="form-label fw-bold">Photo</label>
                     
                     <!-- Preview Image -->
                     <div id="photo-preview-container" class="mb-3" style="<?php echo e($student->photo ? '' : 'display: none;'); ?>">
                         <img id="photo-preview" src="<?php echo e($student->photo ? asset('storage/'.$student->photo) : ''); ?>" alt="Photo Preview" class="img-fluid rounded" style="max-height: 200px; object-fit: cover;">
                     </div>
                     
                     <!-- Placeholder when no image -->
                     <div id="photo-placeholder" class="mb-3 p-4 border rounded bg-light" style="<?php echo e($student->photo ? 'display: none;' : ''); ?>">
                         <i class="bi bi-person-circle fs-1 text-muted"></i>
                         <p class="small text-muted mb-0">No photo selected</p>
                     </div>
                     
                     <input type="file" name="photo" id="photo-input" class="form-control form-control-sm" accept="image/*">
                     <small class="text-muted">JPG, PNG (Max 2MB)</small>
                 </div>
             </div>
             <div class="alert alert-info small">
                 Select Group to load subjects. Ensure mapping exists for HSC 2025.
             </div>
             
             <!-- Status (Edit Only) -->
            <div class="card shadow-sm border-0 mb-3">
                <div class="card-body">
                    <label class="form-label fw-bold">Status</label>
                    <select name="status" class="form-select">
                        <option value="active" <?php echo e($student->status == 'active' ? 'selected' : ''); ?>>Active</option>
                        <option value="inactive" <?php echo e($student->status == 'inactive' ? 'selected' : ''); ?>>Inactive</option>
                        <option value="alumni" <?php echo e($student->status == 'alumni' ? 'selected' : ''); ?>>Alumni</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Sticky Footer -->
    <div class="card fixed-bottom border-top shadow-lg">
        <div class="card-body py-3 d-flex justify-content-between">
             <a href="<?php echo e(route('students.index')); ?>" class="btn btn-light">Cancel</a>
             <button type="submit" class="btn btn-primary fw-bold"><i class="bi bi-save me-2"></i> Update Student</button>
        </div>
    </div>
</form>

<?php $__env->stopSection(); ?>

<?php $__env->startPush('styles'); ?>
<style>
.subject-card {
    display: block;
    position: relative;
    padding: 0;
    margin-bottom: 0.5rem;
    cursor: pointer;
    transition: all 0.2s ease;
}

.subject-card input[type="checkbox"] {
    position: absolute;
    opacity: 0;
    cursor: pointer;
}

.subject-card-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    background: #fff;
    transition: all 0.2s ease;
}

.subject-name {
    font-weight: 500;
    color: #495057;
    flex: 1;
    margin-right: 8px;
}

.subject-card-content .badge {
    font-size: 0.75rem;
    padding: 4px 8px;
}

.check-icon {
    color: #28a745;
    font-size: 20px;
    opacity: 0;
    transition: opacity 0.2s ease;
    margin-left: 8px;
}

.subject-card:hover .subject-card-content {
    border-color: #0d6efd;
    box-shadow: 0 2px 8px rgba(13, 110, 253, 0.15);
    transform: translateY(-1px);
}

.subject-card input[type="checkbox"]:checked ~ .subject-card-content {
    border-color: #0d6efd;
    background: linear-gradient(135deg, #e7f1ff 0%, #f8f9ff 100%);
}

.subject-card input[type="checkbox"]:checked ~ .subject-card-content .check-icon {
    opacity: 1;
}

.subject-card input[type="checkbox"]:checked ~ .subject-card-content .subject-name {
    color: #0d6efd;
    font-weight: 600;
}

.subject-card input[type="checkbox"]:disabled ~ .subject-card-content {
    opacity: 0.5;
    cursor: not-allowed;
}

.subject-card input[type="checkbox"]:disabled:not(:checked) ~ .subject-card-content {
    background: #f8f9fa;
    border-color: #dee2e6;
}

/* 4th Subject Radio Button Cards */
.fourth-subject-card {
    display: block;
    position: relative;
    padding: 0;
    margin-bottom: 0.5rem;
    cursor: pointer;
    transition: all 0.2s ease;
}

.fourth-subject-card input[type="radio"] {
    position: absolute;
    opacity: 0;
    cursor: pointer;
}

.fourth-subject-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    background: #fff;
    transition: all 0.2s ease;
}

.fourth-subject-name {
    font-weight: 500;
    color: #495057;
    flex: 1;
    margin-right: 8px;
}

.fourth-check-icon {
    color: #6610f2;
    font-size: 20px;
    opacity: 0;
    transition: opacity 0.2s ease;
    margin-left: 8px;
}

.fourth-subject-card:hover .fourth-subject-content {
    border-color: #6610f2;
    box-shadow: 0 2px 8px rgba(102, 16, 242, 0.15);
    transform: translateY(-1px);
}

.fourth-subject-card input[type="radio"]:checked ~ .fourth-subject-content {
    border-color: #6610f2;
    background: linear-gradient(135deg, #f3e8ff 0%, #faf5ff 100%);
}

.fourth-subject-card input[type="radio"]:checked ~ .fourth-subject-content .fourth-check-icon {
    opacity: 1;
}

.fourth-subject-card input[type="radio"]:checked ~ .fourth-subject-content .fourth-subject-name {
    color: #6610f2;
    font-weight: 600;
}

.fourth-subject-card input[type="radio"]:disabled ~ .fourth-subject-content {
    opacity: 0.5;
    cursor: not-allowed;
    background: #f8f9fa;
    border-color: #dee2e6;
}

.form-check-input:checked {
    background-color: #6610f2;
    border-color: #6610f2;
}
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const versionSelect = document.getElementById('academic_version_id');
    const groupSelect = document.getElementById('group_code');
    const subjectArea = document.getElementById('subject-area');
    const loadingArea = document.getElementById('subject-loading');
    const fixedList = document.getElementById('fixed-subjects-list');
    const bucketsArea = document.getElementById('buckets-area');
    const mandatoryCounter = document.getElementById('mandatory-counter');
    const form = document.querySelector('form');

    // Existing Data
    const existingMandatory = <?php echo json_encode($student->subjects->pluck('id'), 15, 512) ?>;
    const existingOptional = <?php echo e($student->optional_subject_id ?? 'null'); ?>;

    // Update mandatory subject counter and enforce limits
    function updateMandatoryCount() {
        const checked = document.querySelectorAll('.mandatory-checkbox:checked');
        const count = checked.length;
        const max = 6;
        
        // Update counter display
        mandatoryCounter.textContent = `Selected: ${count}/${max}`;
        
        // Change badge color based on count
        mandatoryCounter.classList.remove('bg-primary', 'bg-success', 'bg-danger', 'bg-warning');
        if (count === max) {
            mandatoryCounter.classList.add('bg-success');
        } else if (count > max) {
            mandatoryCounter.classList.add('bg-danger');
        } else if (count > 0) {
            mandatoryCounter.classList.add('bg-warning');
        } else {
            mandatoryCounter.classList.add('bg-primary');
        }
        
        // Disable unchecked checkboxes if limit reached
        document.querySelectorAll('.mandatory-checkbox').forEach(cb => {
            if (!cb.checked && count >= max) {
                cb.disabled = true;
                cb.parentElement.parentElement.classList.add('opacity-50');
            } else if (!cb.checked) {
                cb.disabled = false;
                cb.parentElement.parentElement.classList.remove('opacity-50');
            }
        });
    }

    // Cross-Bucket Duplicate Prevention for 4th Subject
    function updateExclusions() {
        const allChecked = [];
        
        // Collect all selected IDs
        document.querySelectorAll('.bucket-input:checked').forEach(el => {
            allChecked.push(el.value);
        });

        // Disable duplicates in other buckets
        document.querySelectorAll('.bucket-input').forEach(el => {
            if(el.checked) {
                el.disabled = false;
                el.parentElement.classList.remove('text-muted');
                return;
            }

            if(allChecked.includes(el.value)) {
                el.disabled = true;
                el.parentElement.classList.add('text-muted', 'text-decoration-line-through');
            } else {
                el.disabled = false;
                el.parentElement.classList.remove('text-muted', 'text-decoration-line-through');
            }
        });
    }

    // Update 4th subject counter
    function updateFourthSubjectCount() {
        const fourthCounter = document.getElementById('fourth-subject-counter');
        if (!fourthCounter) return;
        
        const checked = document.querySelectorAll('.bucket-input:checked');
        const count = checked.length;
        const max = 1;
        
        // Update counter display
        fourthCounter.textContent = `Selected: ${count}/${max}`;
        
        // Change badge color based on count
        fourthCounter.classList.remove('bg-secondary', 'bg-success', 'bg-danger');
        if (count === max) {
            fourthCounter.classList.add('bg-success');
        } else if (count > max) {
            fourthCounter.classList.add('bg-danger');
        } else {
            fourthCounter.classList.add('bg-secondary');
        }
    }

    // Attach event listeners
    subjectArea.addEventListener('change', function(e) {
        if(e.target.classList.contains('bucket-input')) {
            updateExclusions();
            updateFourthSubjectCount();
            handleFourthSubjectChange(); // Move unselected to mandatory
        }
        if(e.target.classList.contains('mandatory-checkbox')) {
            updateMandatoryCount();
        }
    });

    // Form validation before submission
    form.addEventListener('submit', function(e) {
        const mandatoryCount = document.querySelectorAll('.mandatory-checkbox:checked').length;
        const fourthSubjectCount = document.querySelectorAll('.bucket-input:checked').length;
        
        if (mandatoryCount !== 6) {
            e.preventDefault();
            alert(`Please select exactly 6 mandatory subjects. Currently selected: ${mandatoryCount}`);
            return false;
        }
        
        if (fourthSubjectCount > 1) {
            e.preventDefault();
            alert('Please select only 1 subject as 4th subject');
            return false;
        }
        
        return true;
    });

    async function loadRules() {
        const vId = versionSelect.value;
        const gCode = groupSelect.value;

        if(!vId || !gCode) {
            subjectArea.classList.add('d-none');
            return;
        }

        loadingArea.classList.remove('d-none');
        subjectArea.classList.add('d-none');

        try {
            const res = await fetch(`<?php echo e(route('api.student.rules')); ?>?version_id=${vId}&group_code=${gCode}`);
            const data = await res.json();
            
            // Store elective options globally for dynamic movement
            window.electiveOptions = data.buckets.length > 0 ? data.buckets[0].options : [];
            window.fixedSubjects = data.fixed || [];
            
            // 1. Render Fixed Subjects as CHECKBOXES with Card UI
            renderMandatorySubjects(window.fixedSubjects);

            // 2. Render Buckets (4th Subject) with Card UI
            bucketsArea.innerHTML = '';
            data.buckets.forEach(bucket => {
                let optionsHtml = '';
                const inputType = bucket.ui_type === 'radio' ? 'radio' : 'checkbox';
                const inputName = `bucket_selections[${bucket.id}]` + (inputType === 'checkbox' ? '[]' : '');

                bucket.options.forEach(opt => {
                    const isChecked = (existingOptional == opt.id) ? 'checked' : '';
                    optionsHtml += `
                        <div class="col-md-6">
                            <label class="fourth-subject-card" for="opt_${bucket.id}_${opt.id}">
                                <input class="bucket-input" 
                                       type="${inputType}" 
                                       name="${inputName}" 
                                       value="${opt.id}" 
                                       id="opt_${bucket.id}_${opt.id}"
                                       data-subject-name="${opt.name}"
                                       data-subject-code="${opt.code}"
                                       ${isChecked}>
                                <div class="fourth-subject-content">
                                    <span class="fourth-subject-name">${opt.name}</span>
                                    <span class="badge bg-dark">${opt.code}</span>
                                    <i class="bi bi-check-circle-fill fourth-check-icon"></i>
                                </div>
                            </label>
                        </div>
                    `;
                });

                const bucketHtml = `
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="fw-bold fs-6 text-primary mb-0">${bucket.name}</h6>
                            <span id="fourth-subject-counter" class="badge bg-secondary">Selected: 0/1</span>
                        </div>
                        <div class="row g-2">
                            ${optionsHtml}
                        </div>
                    </div>
                `;
                bucketsArea.insertAdjacentHTML('beforeend', bucketHtml);
            });

            // Initial Trigger to Move Subjects if checked
            handleFourthSubjectChange();

            subjectArea.classList.remove('d-none');
            updateMandatoryCount(); // Initial count update
            updateFourthSubjectCount(); // Initial 4th subject count
            updateExclusions(); // Initial exclusion check

        } catch(e) {
            console.error(e);
            alert('Error loading subjects. Please check if mapping exists.');
        } finally {
            loadingArea.classList.add('d-none');
        }
    }

    // Function to render mandatory subjects
    function renderMandatorySubjects(subjects) {
        fixedList.innerHTML = '';
        subjects.forEach(sub => {
            const isChecked = existingMandatory.includes(parseInt(sub.id)) ? 'checked' : '';
            const html = `
                <div class="col-md-6">
                    <label class="subject-card" for="mandatory_${sub.id}">
                        <input class="mandatory-checkbox" 
                               type="checkbox" 
                               name="mandatory_subjects[]" 
                               value="${sub.id}" 
                               id="mandatory_${sub.id}"
                               data-is-elective="false"
                               ${isChecked}>
                        <div class="subject-card-content">
                            <span class="subject-name">${sub.name}</span>
                            <span class="badge bg-dark">${sub.code}</span>
                            <i class="bi bi-check-circle-fill check-icon"></i>
                        </div>
                    </label>
                </div>`;
            fixedList.insertAdjacentHTML('beforeend', html);
        });
    }

    // Handle 4th subject selection and move unselected to mandatory
    function handleFourthSubjectChange() {
        const selectedFourth = document.querySelector('.bucket-input:checked');
        
        if (selectedFourth && window.electiveOptions) {
            // Get all elective IDs
            const allElectiveIds = window.electiveOptions.map(opt => opt.id);
            const selectedId = parseInt(selectedFourth.value);
            
            // Get unselected elective IDs
            const unselectedElectives = window.electiveOptions.filter(opt => opt.id !== selectedId);
            
            // Remove previously added electives from mandatory section
            document.querySelectorAll('.mandatory-checkbox[data-is-elective="true"]').forEach(el => {
                el.closest('.col-md-6').remove();
            });
            
            // Add unselected electives to mandatory section
            unselectedElectives.forEach(opt => {
                const html = `
                    <div class="col-md-6">
                        <label class="subject-card" for="mandatory_elective_${opt.id}">
                            <input class="mandatory-checkbox" 
                                   type="checkbox" 
                                   name="mandatory_subjects[]" 
                                   value="${opt.id}" 
                                   id="mandatory_elective_${opt.id}"
                                   data-is-elective="true"
                                   checked>
                            <div class="subject-card-content">
                                <span class="subject-name">${opt.name}</span>
                                <span class="badge bg-dark">${opt.code}</span>
                                <i class="bi bi-check-circle-fill check-icon"></i>
                            </div>
                        </label>
                    </div>`;
                fixedList.insertAdjacentHTML('beforeend', html);
            });
            
            updateMandatoryCount();
        } else {
            // No 4th subject selected, remove electives from mandatory
            document.querySelectorAll('.mandatory-checkbox[data-is-elective="true"]').forEach(el => {
                el.closest('.col-md-6').remove();
            });
            updateMandatoryCount();
        }
    }

    // DOB Handling
    const dobDay = document.getElementById('dob_day');
    const dobMonth = document.getElementById('dob_month');
    const dobYear = document.getElementById('dob_year');
    const dobHidden = document.getElementById('dob_hidden');

    if (dobDay && dobMonth && dobYear) {
        // Populate Years (Current Year - 10 down to 1980)
        const currentYear = new Date().getFullYear();
        const startYear = currentYear - 10;
        const endYear = 1990;
        
        for (let y = startYear; y >= endYear; y--) {
            const opt = document.createElement('option');
            opt.value = y;
            opt.textContent = y;
            dobYear.appendChild(opt);
        }

        // Populate Days (Initial 31)
        for (let d = 1; d <= 31; d++) {
            const opt = document.createElement('option');
            const val = d < 10 ? '0' + d : d;
            opt.value = val;
            opt.textContent = d;
            dobDay.appendChild(opt);
        }

        function updateDob() {
            const d = dobDay.value;
            const m = dobMonth.value;
            const y = dobYear.value;

            // Update days in month based on selection
            if (m && y) {
                const daysInMonth = new Date(y, m, 0).getDate();
                
                // Show/Hide invalid days
                Array.from(dobDay.options).forEach(opt => {
                    if (opt.value === '') return;
                    if (parseInt(opt.value) > daysInMonth) {
                        opt.style.display = 'none';
                        if (opt.value == d) dobDay.value = ''; // Reset if current day is invalid
                    } else {
                        opt.style.display = 'block';
                    }
                });
            }

            if (d && m && y) {
                dobHidden.value = `${y}-${m}-${d}`;
            } else {
                dobHidden.value = '';
            }
        }

        // Pre-fill existing data
        if (dobHidden.value) {
            const [y, m, d] = dobHidden.value.split('-');
            dobYear.value = y;
            dobMonth.value = m;
            dobDay.value = d;
            updateDob();
        }

        dobDay.addEventListener('change', updateDob);
        dobMonth.addEventListener('change', updateDob);
        dobYear.addEventListener('change', updateDob);
    }

    if(versionSelect && groupSelect) {
        versionSelect.addEventListener('change', loadRules);
        groupSelect.addEventListener('change', loadRules);
        if(versionSelect.value && groupSelect.value) loadRules();
    }

    // Photo Preview Handler
    const photoInput = document.getElementById('photo-input');
    const photoPreview = document.getElementById('photo-preview');
    const photoPreviewContainer = document.getElementById('photo-preview-container');
    const photoPlaceholder = document.getElementById('photo-placeholder');

    if (photoInput) {
        photoInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            
            if (file) {
                // Check file size (2MB max)
                if (file.size > 2 * 1024 * 1024) {
                    alert('File size must be less than 2MB');
                    photoInput.value = '';
                    return;
                }
                
                // Check file type
                if (!file.type.startsWith('image/')) {
                    alert('Please select a valid image file');
                    photoInput.value = '';
                    return;
                }
                
                // Show preview
                const reader = new FileReader();
                reader.onload = function(event) {
                    photoPreview.src = event.target.result;
                    photoPreviewContainer.style.display = 'block';
                    photoPlaceholder.style.display = 'none';
                };
                reader.readAsDataURL(file);
            } else {
                // No file selected, show placeholder
                photoPreviewContainer.style.display = 'none';
                photoPlaceholder.style.display = 'block';
                photoPreview.src = '';
            }
        });
    }
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH T:\Motiur\college\admin\resources\views/students/edit.blade.php ENDPATH**/ ?>