@extends('admin.layouts.app')

@section('content')
    <section class="section">
        <div class="section-header">
            <h1>إعدادات صفحة الخريجين</h1>
            <div class="section-header-breadcrumb">
                <div class="breadcrumb-item active"><a href="/admin/">{{ trans('admin/main.dashboard') }}</a></div>
                <div class="breadcrumb-item">إعدادات صفحة الخريجين</div>
            </div>
        </div>

        <div class="section-body">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <form action="/admin/additional_page/graduates_page" method="post" id="graduatesSettingsForm">
                                {{ csrf_field() }}
                                <input type="hidden" name="selected_graduates_json" id="selected_graduates_json" value="">

                                <div class="row">
                                    <div class="col-12 col-md-6">
                                        <h4 class="section-title">إعدادات البانر</h4>

                                        <div class="form-group">
                                            <label class="input-label">صورة البانر</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <button type="button" class="input-group-text admin-file-manager" data-input="banner_image_record" data-preview="holder">
                                                        <i class="fa fa-chevron-up"></i>
                                                    </button>
                                                </div>
                                                <input type="text" name="value[banner_image]" id="banner_image_record" value="{{ (!empty($value) and !empty($value['banner_image'])) ? $value['banner_image'] : '' }}" class="form-control"/>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label class="input-label">عنوان البانر</label>
                                            <input type="text" name="value[banner_title]" value="{{ (!empty($value) and !empty($value['banner_title'])) ? $value['banner_title'] : 'الخريجين' }}" class="form-control" placeholder="الخريجين"/>
                                        </div>

                                        <div class="form-group">
                                            <label class="input-label">وصف البانر</label>
                                            <textarea name="value[banner_description]" rows="3" class="form-control" placeholder="تعريف مختصر عن الخريجين">{{ (!empty($value) and !empty($value['banner_description'])) ? $value['banner_description'] : '' }}</textarea>
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-6">
                                        <h4 class="section-title">إعدادات العرض</h4>

                                        <div class="form-group">
                                            <label class="input-label">عدد الخريجين المعروض</label>
                                            <input type="number" name="value[graduates_limit]" value="{{ (!empty($value) and !empty($value['graduates_limit'])) ? $value['graduates_limit'] : '12' }}" class="form-control" min="1" max="100"/>
                                            <div class="text-muted text-small mt-1">عدد الخريجين الذين يظهرون في الصفحة (افتراضي: 12)</div>
                                        </div>

                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" name="value[show_graduates]" value="1" class="custom-control-input" id="show_graduates" {{ (!empty($value) and !empty($value['show_graduates']) and $value['show_graduates'] == '1') ? 'checked' : 'checked' }}>
                                                <label class="custom-control-label" for="show_graduates">إظهار قسم الخريجين</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mt-4">
                                    <div class="col-12">
                                        <h4 class="section-title">اختيار الخريجين المعروضين</h4>
                                        <p class="text-muted">اختر الخريجين الذين تريد عرضهم في صفحة الخريجين. إذا لم تختر أي خريج، سيتم عرض جميع الخريجين وفق التصفية والحد الأقصى.</p>
                                    </div>

                                    <div class="col-12">
                                        <div class="form-group">
                                            <label class="input-label">البحث عن خريج</label>
                                            <input type="text" id="searchGraduate" class="form-control" placeholder="ابحث بالاسم أو البريد الإلكتروني..."/>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="form-group">
                                            <div class="d-flex justify-content-between mb-2 align-items-center">
                                                <label class="input-label mb-0">الخريجين المتاحين</label>
                                                <div class="d-flex align-items-center gap-2">
                                                    <span id="selectedCount" class="badge badge-info mr-2">محدد: 0</span>
                                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllGraduates()">تحديد الكل</button>
                                                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="deselectAllGraduates()">إلغاء التحديد</button>
                                                </div>
                                            </div>
                                            <div style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; border-radius: 4px;">
                                                @php
                                                    $displayedCount = 0;
                                                    $totalCount = $certificates->count();
                                                @endphp
                                                @forelse($certificates as $certificate)
                                                    @php
                                                        $student = $certificate->student;
                                                        $isSelected = in_array($certificate->id, $selectedCertificateIds ?? []);
                                                    @endphp
                                                    @if($student)
                                                        @php $displayedCount++; @endphp
                                                @php
                                                    // Get saved country name for this graduate (stored as text)
                                                    $savedCountryName = $value['graduate_countries'][$certificate->id] ?? null;
                                                    $savedCountryFlag = null;
                                                    $savedFlagImage = $value['graduate_flags'][$certificate->id] ?? null;
                                                    
                                                    if ($savedCountryName) {
                                                        $savedCountryName = trim($savedCountryName);
                                                        // Get country flag emoji (only if no custom flag image)
                                                        if (!$savedFlagImage && class_exists('\App\Helpers\CountryHelper')) {
                                                            $savedCountryFlag = \App\Helpers\CountryHelper::getCountryFlag($savedCountryName);
                                                        }
                                                    }
                                                    
                                                    // Fallback to student's country if no saved country
                                                    if (!$savedCountryName && !empty($student->country_id)) {
                                                        try {
                                                            $country = \App\Models\Region::where('id', $student->country_id)->first();
                                                            if ($country && !empty($country->title)) {
                                                                $savedCountryName = trim($country->title);
                                                                if (!$savedFlagImage && class_exists('\App\Helpers\CountryHelper')) {
                                                                    $savedCountryFlag = \App\Helpers\CountryHelper::getCountryFlag($savedCountryName);
                                                                }
                                                            }
                                                        } catch (\Exception $e) {
                                                            // Silently handle errors
                                                        }
                                                    }
                                                @endphp
                                                <div class="mb-3 graduate-item" data-name="{{ strtolower($student->full_name) }}" data-email="{{ strtolower($student->email ?? '') }}" data-country="{{ strtolower($savedCountryName ?? '') }}">
                                                    <div class="d-flex flex-column flex-md-row align-items-start align-items-md-center">
                                                        <div class="mr-md-3 mb-2 mb-md-0 flex-grow-1">
                                                            <div class="custom-control custom-checkbox">
                                                                <input type="checkbox" name="value[selected_graduates][]" value="{{ $certificate->id }}" class="custom-control-input graduate-checkbox" id="graduate_{{ $certificate->id }}" {{ $isSelected ? 'checked' : '' }}>
                                                                <label class="custom-control-label d-block" for="graduate_{{ $certificate->id }}">
                                                                    <div class="d-flex align-items-center flex-wrap">
                                                                        <strong class="mr-2">{{ $student->full_name }}</strong>
                                                                        @if($student->email)
                                                                            <span class="text-muted mr-2">({{ $student->email }})</span>
                                                                        @endif
                                                                        @if($savedCountryName)
                                                                            <span class="badge badge-light text-dark ml-2 d-inline-flex align-items-center mt-1" id="country_badge_{{ $certificate->id }}">
                                                                                @if($savedFlagImage)
                                                                                    <img src="{{ $savedFlagImage }}" alt="{{ $savedCountryName }}" class="mr-1 country-flag-image" style="max-width: 16px; max-height: 12px; object-fit: contain; vertical-align: middle;">
                                                                                @elseif($savedCountryFlag)
                                                                                    <span class="mr-1 country-flag" style="font-size: 16px; line-height: 1;">{{ $savedCountryFlag }}</span>
                                                                                @endif
                                                                                <span class="country-name">{{ $savedCountryName }}</span>
                                                                            </span>
                                                                        @endif
                                                                    </div>
                                                                </label>
                                                            </div>
                                                        </div>
                                                        <div class="flex-grow-1">
                                                            <div class="form-group mb-2">
                                                                <label class="input-label d-block font-12 mb-1">البلد</label>
                                                                <input type="text" name="value[graduate_countries][{{ $certificate->id }}]" value="{{ $savedCountryName ?? '' }}" class="form-control form-control-sm graduate-country-input" data-certificate-id="{{ $certificate->id }}" placeholder="اكتب اسم البلد..." onkeyup="updateCountryBadgeFromInput({{ $certificate->id }}, this.value)" onchange="updateCountryBadgeFromInput({{ $certificate->id }}, this.value)">
                                                            </div>
                                                            <div class="form-group mb-2">
                                                                <label class="input-label d-block font-12 mb-1">صورة علم البلد (اختياري)</label>
                                                                <div class="input-group input-group-sm">
                                                                    <div class="input-group-prepend">
                                                                        <button type="button" class="input-group-text admin-file-manager" data-input="graduate_flag_{{ $certificate->id }}" data-preview="flag_preview_{{ $certificate->id }}">
                                                                            <i class="fa fa-chevron-up"></i>
                                                                        </button>
                                                                    </div>
                                                                    <input type="text" name="value[graduate_flags][{{ $certificate->id }}]" id="graduate_flag_{{ $certificate->id }}" value="{{ $value['graduate_flags'][$certificate->id] ?? '' }}" class="form-control" placeholder="مسار صورة العلم...">
                                                                </div>
                                                                @if(!empty($value['graduate_flags'][$certificate->id]))
                                                                    <div class="mt-1" id="flag_preview_{{ $certificate->id }}">
                                                                        <img src="{{ $value['graduate_flags'][$certificate->id] }}" alt="علم البلد" style="max-width: 30px; max-height: 20px; object-fit: contain;">
                                                                    </div>
                                                                @endif
                                                            </div>
                                                            <label class="input-label d-block font-12 mb-1">صورة بطاقة الخريج (اختياري)</label>
                                                            <div class="input-group input-group-sm">
                                                                <div class="input-group-prepend">
                                                                    <button type="button" class="input-group-text admin-file-manager" data-input="graduate_image_{{ $certificate->id }}" data-preview="holder">
                                                                        <i class="fa fa-chevron-up"></i>
                                                                    </button>
                                                                </div>
                                                                <input type="text" name="value[graduate_images][{{ $certificate->id }}]" id="graduate_image_{{ $certificate->id }}" value="{{ $value['graduate_images'][$certificate->id] ?? '' }}" class="form-control">
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                    @endif
                                                @empty
                                                    <p class="text-muted">لا يوجد خريجين متاحين</p>
                                                @endforelse
                                                
                                                @php
                                                    \Log::info('Graduates Settings View - Total Certificates: ' . $totalCount);
                                                    \Log::info('Graduates Settings View - Displayed Certificates: ' . $displayedCount);
                                                @endphp
                                                
                                                <!-- Debug Info -->
                                                <div class="mt-3 p-2 bg-light rounded">
                                                    <small class="text-muted">
                                                        <strong>معلومات التصحيح:</strong><br>
                                                        إجمالي الشهادات: {{ $totalCount }}<br>
                                                        الشهادات المعروضة: {{ $displayedCount }}<br>
                                                        الشهادات المخفية: {{ $totalCount - $displayedCount }}
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mt-4">
                                    <div class="col-12">
                                        <h4 class="section-title">إعدادات SEO</h4>
                                    </div>

                                    <div class="col-12 col-md-6">
                                        <div class="form-group">
                                            <label class="input-label">عنوان الصفحة (Page Title)</label>
                                            <input type="text" name="value[seo_title]" value="{{ (!empty($value) and !empty($value['seo_title'])) ? $value['seo_title'] : 'الخريجين' }}" class="form-control" placeholder="الخريجين"/>
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-6">
                                        <div class="form-group">
                                            <label class="input-label">وصف الصفحة (Meta Description)</label>
                                            <textarea name="value[seo_description]" rows="3" class="form-control" placeholder="وصف الصفحة لمحركات البحث">{{ (!empty($value) and !empty($value['seo_description'])) ? $value['seo_description'] : '' }}</textarea>
                                        </div>
                                    </div>
                                </div>

                                <div class="mt-4">
                                    <button type="submit" class="btn btn-primary" id="saveGraduatesBtn">{{ trans('admin/main.save_change') }}</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
@endsection

@push('scripts_bottom')
    <script>
        // Country flags mapping (common countries)
        const countryFlags = {
            'السعودية': '🇸🇦',
            'المملكة العربية السعودية': '🇸🇦',
            'مصر': '🇪🇬',
            'الإمارات العربية المتحدة': '🇦🇪',
            'الإمارات': '🇦🇪',
            'الكويت': '🇰🇼',
            'قطر': '🇶🇦',
            'البحرين': '🇧🇭',
            'عمان': '🇴🇲',
            'اليمن': '🇾🇪',
            'الأردن': '🇯🇴',
            'لبنان': '🇱🇧',
            'سوريا': '🇸🇾',
            'العراق': '🇮🇶',
            'فلسطين': '🇵🇸',
            'السودان': '🇸🇩',
            'ليبيا': '🇱🇾',
            'تونس': '🇹🇳',
            'الجزائر': '🇩🇿',
            'المغرب': '🇲🇦',
        };

        function getCountryFlag(countryName) {
            if (!countryName) return '';
            return countryFlags[countryName] || '';
        }

        function updateCountryBadgeFromInput(certificateId, countryName) {
            const input = document.querySelector(`input[data-certificate-id="${certificateId}"]`);
            const badge = document.getElementById(`country_badge_${certificateId}`);
            const flagInput = document.getElementById(`graduate_flag_${certificateId}`);
            const flagImage = flagInput ? flagInput.value.trim() : '';
            
            if (!input) return;
            
            countryName = countryName.trim();
            
            if (countryName) {
                const flag = flagImage ? null : getCountryFlag(countryName);
                
                if (!badge) {
                    // Create badge if it doesn't exist
                    const label = input.closest('.graduate-item').querySelector('.custom-control-label');
                    if (label) {
                        const flexDiv = label.querySelector('.d-flex');
                        if (flexDiv) {
                            const newBadge = document.createElement('span');
                            newBadge.id = `country_badge_${certificateId}`;
                            newBadge.className = 'badge badge-light text-dark ml-2 d-inline-flex align-items-center mt-1';
                            
                            let flagHtml = '';
                            if (flagImage) {
                                flagHtml = `<img src="${flagImage}" alt="${countryName}" class="mr-1 country-flag-image" style="max-width: 16px; max-height: 12px; object-fit: contain; vertical-align: middle;">`;
                            } else if (flag) {
                                flagHtml = `<span class="mr-1 country-flag" style="font-size: 16px; line-height: 1;">${flag}</span>`;
                            }
                            
                            newBadge.innerHTML = `
                                ${flagHtml}
                                <span class="country-name">${countryName}</span>
                            `;
                            flexDiv.appendChild(newBadge);
                        }
                    }
                } else {
                    // Update existing badge
                    const flagSpan = badge.querySelector('.country-flag');
                    const flagImg = badge.querySelector('.country-flag-image');
                    const nameSpan = badge.querySelector('.country-name');
                    
                    // Remove existing flag elements
                    if (flagSpan) flagSpan.remove();
                    if (flagImg) flagImg.remove();
                    
                    // Add new flag
                    if (flagImage) {
                        badge.insertAdjacentHTML('afterbegin', `<img src="${flagImage}" alt="${countryName}" class="mr-1 country-flag-image" style="max-width: 16px; max-height: 12px; object-fit: contain; vertical-align: middle;">`);
                    } else if (flag) {
                        badge.insertAdjacentHTML('afterbegin', `<span class="mr-1 country-flag" style="font-size: 16px; line-height: 1;">${flag}</span>`);
                    }
                    
                    if (nameSpan) {
                        nameSpan.textContent = countryName;
                    }
                }
            } else if (badge) {
                // Remove badge if no country entered
                badge.remove();
            }
        }

        // Search functionality
        const searchInput = document.getElementById('searchGraduate');
        if (searchInput) {
            searchInput.addEventListener('input', function(e) {
                const searchTerm = e.target.value.toLowerCase();
                const items = document.querySelectorAll('.graduate-item');

                items.forEach(item => {
                    const name = item.getAttribute('data-name') || '';
                    const email = item.getAttribute('data-email') || '';
                    const country = item.getAttribute('data-country') || '';
                    
                    // Also check the country input field value
                    const countryInput = item.querySelector('.graduate-country-input');
                    const countryValue = countryInput ? countryInput.value.toLowerCase() : '';

                    if (name.includes(searchTerm) || email.includes(searchTerm) || country.includes(searchTerm) || countryValue.includes(searchTerm)) {
                        item.style.display = 'block';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
        }
        
        // Initialize badges on page load
        document.addEventListener('DOMContentLoaded', function() {
            const countryInputs = document.querySelectorAll('.graduate-country-input');
            countryInputs.forEach(input => {
                const certificateId = input.getAttribute('data-certificate-id');
                const countryName = input.value;
                if (countryName) {
                    updateCountryBadgeFromInput(certificateId, countryName);
                }
            });
            
            // Initialize flag image previews
            const flagInputs = document.querySelectorAll('input[id^="graduate_flag_"]');
            flagInputs.forEach(input => {
                input.addEventListener('change', function() {
                    const certificateId = this.id.replace('graduate_flag_', '');
                    updateFlagPreview(certificateId, this.value);
                });
                
                // Show preview if value exists
                if (input.value) {
                    const certificateId = input.id.replace('graduate_flag_', '');
                    updateFlagPreview(certificateId, input.value);
                }
            });
        });
        
        function updateFlagPreview(certificateId, flagImagePath) {
            const previewDiv = document.getElementById(`flag_preview_${certificateId}`);
            const countryInput = document.querySelector(`input[data-certificate-id="${certificateId}"]`);
            
            if (flagImagePath && flagImagePath.trim()) {
                if (!previewDiv) {
                    // Create preview div if it doesn't exist
                    const input = document.getElementById(`graduate_flag_${certificateId}`);
                    if (input) {
                        const formGroup = input.closest('.form-group');
                        if (formGroup) {
                            const newPreview = document.createElement('div');
                            newPreview.id = `flag_preview_${certificateId}`;
                            newPreview.className = 'mt-1';
                            newPreview.innerHTML = `<img src="${flagImagePath}" alt="علم البلد" style="max-width: 30px; max-height: 20px; object-fit: contain;">`;
                            formGroup.appendChild(newPreview);
                        }
                    }
                } else {
                    // Update existing preview
                    const img = previewDiv.querySelector('img');
                    if (img) {
                        img.src = flagImagePath;
                    } else {
                        previewDiv.innerHTML = `<img src="${flagImagePath}" alt="علم البلد" style="max-width: 30px; max-height: 20px; object-fit: contain;">`;
                    }
                }
                
                // Update badge if country name exists
                if (countryInput && countryInput.value.trim()) {
                    updateCountryBadgeFromInput(certificateId, countryInput.value);
                }
            } else if (previewDiv) {
                // Remove preview if no image
                previewDiv.remove();
                
                // Update badge to use emoji flag if country name exists
                if (countryInput && countryInput.value.trim()) {
                    updateCountryBadgeFromInput(certificateId, countryInput.value);
                }
            }
        }

        function selectAllGraduates() {
            // Select all checkboxes, not just visible ones
            const allCheckboxes = document.querySelectorAll('.graduate-checkbox');
            const visibleCheckboxes = document.querySelectorAll('.graduate-item:not([style*="display: none"]) .graduate-checkbox');
            
            console.log('=== Select All Graduates ===');
            console.log('Total checkboxes found:', allCheckboxes.length);
            console.log('Visible checkboxes found:', visibleCheckboxes.length);
            console.log('Hidden checkboxes:', allCheckboxes.length - visibleCheckboxes.length);
            
            // Log all checkbox values
            const checkboxValues = Array.from(allCheckboxes).map(cb => cb.value);
            console.log('All checkbox values count:', checkboxValues.length);
            console.log('First 10 values:', checkboxValues.slice(0, 10));
            console.log('Last 10 values:', checkboxValues.slice(-10));
            
            let selectedCount = 0;
            allCheckboxes.forEach(checkbox => {
                if (!checkbox.checked) {
                    checkbox.checked = true;
                    selectedCount++;
                }
            });
            
            console.log('Newly selected:', selectedCount);
            console.log('Total selected now:', allCheckboxes.length);
            
            updateSelectedCount();
        }

        function deselectAllGraduates() {
            const checkboxes = document.querySelectorAll('.graduate-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            updateSelectedCount();
        }
        
        function updateSelectedCount() {
            const checkedBoxes = document.querySelectorAll('.graduate-checkbox:checked');
            const countElement = document.getElementById('selectedCount');
            if (countElement) {
                countElement.textContent = 'محدد: ' + checkedBoxes.length;
            }
            console.log('Currently selected:', checkedBoxes.length);
        }
        
        // Update count on page load and when checkboxes change
        document.addEventListener('DOMContentLoaded', function() {
            updateSelectedCount();
            
            // Add event listeners to all checkboxes
            document.querySelectorAll('.graduate-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', updateSelectedCount);
            });
            
            // Handle form submission - collect all selected graduates as JSON
            const form = document.getElementById('graduatesSettingsForm');
            if (form) {
                form.addEventListener('submit', function(e) {
                    // Collect all checked checkbox values
                    const allCheckboxes = document.querySelectorAll('.graduate-checkbox:checked');
                    const selectedIds = Array.from(allCheckboxes).map(cb => parseInt(cb.value));
                    
                    console.log('Form Submit - Selected IDs count:', selectedIds.length);
                    console.log('Form Submit - First 10 IDs:', selectedIds.slice(0, 10));
                    console.log('Form Submit - Last 10 IDs:', selectedIds.slice(-10));
                    
                    // Set the JSON value
                    document.getElementById('selected_graduates_json').value = JSON.stringify(selectedIds);
                    
                    // Remove all checkbox inputs from form to avoid max_input_vars issue
                    const checkboxes = document.querySelectorAll('.graduate-checkbox');
                    checkboxes.forEach(checkbox => {
                        checkbox.disabled = true; // Disable instead of remove to keep form structure
                    });
                });
            }
        });
    </script>
@endpush


