@extends('layouts.app')

@section('content')
<div class="container mx-auto px-4 py-6">
    <div class="mb-8">
        <div class="flex items-center justify-between mb-6">
            <div>
                <h1 class="text-3xl font-bold text-gray-900 mb-2">البحث في الترجمات</h1>
                <p class="text-gray-600">ابحث عن الترجمات حسب النص أو المفتاح أو مسار الصفحة</p>
            </div>
        </div>
    </div>

    <!-- خيارات البحث الرئيسية -->
    <form method="GET" class="mb-6 bg-white rounded-lg shadow-md p-6">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
            <!-- نوع البحث -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">نوع البحث</label>
                <select name="search_type" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="all" @selected($searchType === 'all')>جميع الحقول</option>
                    <option value="text" @selected($searchType === 'text')>قيمة الترجمة</option>
                    <option value="key" @selected($searchType === 'key')>مفتاح الترجمة</option>
                    <option value="view_path" @selected($searchType === 'view_path')>مسار الصفحة</option>
                </select>
            </div>

            <!-- حقل البحث -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">نص البحث</label>
                <input type="text" name="search" placeholder="ابحث..." value="{{ request('search') }}" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- اختيار مسار الصفحة -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">مسار الصفحة</label>
                <select id="view_path_select" name="view_path" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 select2-searchable"
                        data-ajax-url="{{ route('localization.api.view-paths') }}"
                        data-placeholder="ابحث عن صفحة...">
                    <option value="">جميع الصفحات</option>
                    @if($viewPath)
                        <option value="{{ $viewPath }}" selected>{{ $viewPath }}</option>
                    @endif
                </select>
            </div>

            <!-- اختيار اللغة -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">اللغة</label>
                <select name="language_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">كل اللغات</option>
                    @foreach($languages as $lang)
                        <option value="{{ $lang->id }}" @selected($languageId == $lang->id)>
                            {{ $lang->flag_emoji }} {{ $lang->name }}
                        </option>
                    @endforeach
                </select>
            </div>
        </div>

        <div class="flex gap-2">
            <button type="submit" class="px-6 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-semibold rounded-lg hover:from-blue-700 hover:to-blue-800 transition-all">
                <i class="fas fa-search ml-2"></i>بحث
            </button>
            <a href="{{ route('localization.translations.index') }}" class="px-6 py-2 bg-gray-600 text-white font-semibold rounded-lg hover:bg-gray-700 transition-all">
                <i class="fas fa-redo ml-2"></i>إعادة تعيين
            </a>
        </div>
    </form>
@php
    // Section removed as all companies now inherit from Company 1 automatically
@endphp

    <div class="overflow-x-auto">
        <table class="w-full border">
            <thead class="bg-gray-200">
                <tr>
                    <th class="border px-4 py-2 text-right">#</th>
                    <th class="border px-4 py-2 text-right">مفتاح الترجمة</th>
                    <th class="border px-4 py-2 text-right">مسار الصفحة</th>
                    <th class="border px-4 py-2 text-right">اللغة</th>
                    <th class="border px-4 py-2 text-right">الترجمة</th>
                    @if($arabicLanguage)
                        <th class="border px-4 py-2 text-right">العربية</th>
                    @endif
                    @if($englishLanguage)
                        <th class="border px-4 py-2 text-right">الإنجليزية</th>
                    @endif
                    @if($hindiLanguage)
                        <th class="border px-4 py-2 text-right">الهندية</th>
                    @endif
                    <th class="border px-4 py-2 text-right">الحالة</th>
                    <th class="border px-4 py-2 text-center">الإجراءات</th>
                </tr>
            </thead>
            <tbody>
                @forelse($translations as $translation)
                    @php
                        $arabicTranslation = null;
                        $englishTranslation = null;
                        $hindiTranslation = null;

                        if ($translation->translationKey) {
                            $allTranslations = $translation->translationKey->translations;
                            if ($arabicLanguage) {
                                $arabicTranslation = $allTranslations->firstWhere('language_id', $arabicLanguage->id);
                            }
                            if ($englishLanguage) {
                                $englishTranslation = $allTranslations->firstWhere('language_id', $englishLanguage->id);
                            }
                            if ($hindiLanguage) {
                                $hindiTranslation = $allTranslations->firstWhere('language_id', $hindiLanguage->id);
                            }
                        }
                    @endphp
                    <tr class="hover:bg-gray-50 transition">
                        <td class="border px-4 py-2 text-right">{{ $loop->iteration }}</td>
                        <td class="border px-4 py-2 text-right">
                            <span class="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs font-mono">
                                {{ $translation->translationKey?->key ?? 'N/A' }}
                            </span>
                        </td>
                        <td class="border px-4 py-2 text-right">
                            @if($translation->translationKey?->view_path)
                                <span class="bg-green-100 text-green-800 px-2 py-1 rounded text-xs font-mono">
                                    {{ $translation->translationKey->view_path }}
                                </span>
                            @else
                                <span class="text-gray-400">-</span>
                            @endif
                        </td>
                        <td class="border px-4 py-2 text-right">{{ $translation->language->flag_emoji }} {{ $translation->language->name }}</td>
                        <td class="border px-4 py-2 text-right">{{ $translation->value }}</td>
                        @if($arabicLanguage)
                            <td class="border px-4 py-2 text-right">{{ $arabicTranslation?->value ?? '-' }}</td>
                        @endif
                        @if($englishLanguage)
                            <td class="border px-4 py-2 text-right">{{ $englishTranslation?->value ?? '-' }}</td>
                        @endif
                        @if($hindiLanguage)
                            <td class="border px-4 py-2 text-right">{{ $hindiTranslation?->value ?? '-' }}</td>
                        @endif
                        <td class="border px-4 py-2 text-right">
                            @if($translation->status === 'published')
                                <span class="bg-green-100 text-green-800 px-2 py-1 rounded text-xs">✓ منشور</span>
                            @elseif($translation->status === 'approved')
                                <span class="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">✓ موافق</span>
                            @else
                                <span class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded text-xs">○ مسودة</span>
                            @endif
                        </td>
                        <td class="border px-4 py-2 text-center whitespace-nowrap">
                            <a href="{{ route('localization.translations.edit', $translation) }}"
                               class="inline-block px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 transition">
                                <i class="fas fa-edit"></i>
                            </a>
                            <form action="{{ route('localization.translations.destroy', $translation) }}" method="POST" class="inline"
                                  onsubmit="return confirm('هل تريد حذف هذه الترجمة؟');">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700 transition">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                             @empty
                    @php
                        $colspan = 7;
                        if ($arabicLanguage) $colspan++;
                        if ($englishLanguage) $colspan++;
                        if ($hindiLanguage) $colspan++;
                    @endphp
                    <tr>
                        <td colspan="{{ $colspan }}" class="border px-4 py-2 text-center">لا توجد نتائج</td>
                    </tr>

                @endforelse
            </tbody>
        </table>
    </div>

    {{ $translations->links() }}
</div>

@push('scripts')
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // تفعيل Select2 مع البحث الديناميكي
    const viewPathSelect = $('#view_path_select');
    
    viewPathSelect.select2({
        ajax: {
            url: viewPathSelect.data('ajax-url'),
            type: 'GET',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    q: params.term || ''
                };
            },
            processResults: function(data) {
                console.log('تم استقبال البيانات:', data.results?.length || 0, 'صفحة');
                return {
                    results: data.results || []
                };
            },
            cache: true,
            error: function(err) {
                console.error('خطأ في جلب البيانات:', err);
            }
        },
        minimumInputLength: 0,
        placeholder: viewPathSelect.data('placeholder'),
        allowClear: true,
        dir: 'rtl',
        language: {
            noResults: function() {
                return 'لم يتم العثور على نتائج';
            },
            searching: function() {
                return 'جاري البحث...';
            },
            inputTooShort: function(args) {
                return '';
            }
        },
        templateResult: function(data) {
            if (!data.id) {
                return data.text;
            }
            // عرض النص الكامل مع اسم الملف في التلميح
            const fileName = data.text.split('/').pop();
            return $('<span title="' + data.text + '">' + data.text + '</span>');
        },
        templateSelection: function(data) {
            return data.text || 'اختر صفحة...';
        }
    });

    // تحميل البيانات الأولية عند فتح القائمة (بدون loop غير نهائي)
    let isLoading = false;
    viewPathSelect.on('select2:opening', function(e) {
        if (isLoading) return; // منع Loop غير نهائي
        
        isLoading = true;
        setTimeout(() => {
            const searchInput = $(this).data('select2').$dropdown?.find('.select2-search__field');
            if (searchInput && searchInput.length) {
                searchInput.focus().val('').trigger('input');
            }
            isLoading = false;
        }, 50);
    });
});
</script>

<style>
.select2-container--default .select2-selection--single {
    border-color: #d1d5db;
    border-radius: 0.5rem;
    min-height: 2.5rem;
}

.select2-container--default.select2-container--focus .select2-selection--single {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.select2-dropdown {
    border-color: #d1d5db;
    border-radius: 0.5rem;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.select2-results__option--highlighted {
    background-color: #3b82f6 !important;
}

.select2-results__option {
    padding: 0.75rem;
    font-size: 0.875rem;
}

.select2-container--default .select2-search--dropdown .select2-search__field {
    border-color: #d1d5db;
    border-radius: 0.375rem;
}
</style>
@endpush

@endsection
