@extends('layouts.app')

@section('title', 'رفع ملف Excel')

@section('content')
<div x-data="uploadComponent()" x-init="init()">
    <div class="px-4 py-5 sm:p-6">
        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">رفع ملف Excel جديد</h3>
        
        <div class="bg-white shadow rounded-lg p-6 mb-6">
            <form @submit.prevent="uploadFile" enctype="multipart/form-data">
                <div class="mb-4">
                    <label for="file" class="block text-sm font-medium text-gray-700 mb-2">
                        اختر ملف Excel (.xlsx أو .csv)
                    </label>
                    <input type="file" 
                           id="file" 
                           name="file" 
                           accept=".xlsx,.csv"
                           @change="fileSelected = $event.target.files[0]"
                           class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100"
                           :disabled="uploading">
                </div>

                <div x-show="error" x-cloak class="mb-4 p-4 bg-red-50 border border-red-200 rounded-md">
                    <p class="text-sm text-red-800" x-text="error"></p>
                </div>

                <div x-show="success" x-cloak class="mb-4 p-4 bg-green-50 border border-green-200 rounded-md">
                    <p class="text-sm text-green-800" x-text="success"></p>
                </div>

                <button type="submit" 
                        :disabled="!fileSelected || uploading"
                        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed">
                    <span x-show="!uploading">رفع الملف</span>
                    <span x-show="uploading" x-cloak>جاري الرفع...</span>
                </button>
            </form>
        </div>

        <!-- Upload Status -->
        <div x-show="currentUpload" x-cloak class="bg-white shadow rounded-lg p-6 mb-6">
            <h4 class="text-md font-medium text-gray-900 mb-4">حالة المعالجة</h4>
            <div class="space-y-2">
                <div class="flex justify-between text-sm">
                    <span class="text-gray-600">الحالة:</span>
                    <span class="font-medium" x-text="currentUpload.status"></span>
                </div>
                <div class="flex justify-between text-sm">
                    <span class="text-gray-600">الصفوف المعالجة:</span>
                    <span class="font-medium" x-text="currentUpload.processed_rows + ' / ' + currentUpload.total_rows"></span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div class="bg-indigo-600 h-2.5 rounded-full transition-all duration-300" 
                         :style="'width: ' + currentUpload.progress_percentage + '%'"></div>
                </div>
                <div class="text-xs text-gray-500 text-center" x-text="currentUpload.progress_percentage + '%'"></div>
            </div>
        </div>

        <!-- Recent Uploads -->
        <div class="bg-white shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">الرفوعات الأخيرة</h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">اسم الملف</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الحالة</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">التقدم</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">التاريخ</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            @forelse($uploadedFiles as $file)
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ $file->original_filename }}</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    @if($file->status === 'completed')
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">مكتمل</span>
                                    @elseif($file->status === 'processing')
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">قيد المعالجة</span>
                                    @elseif($file->status === 'failed')
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">فشل</span>
                                    @else
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">في الانتظار</span>
                                    @endif
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $file->processed_rows }} / {{ $file->total_rows }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $file->created_at->format('Y-m-d H:i') }}
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="4" class="px-6 py-4 text-center text-sm text-gray-500">لا توجد رفوعات سابقة</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function uploadComponent() {
    return {
        fileSelected: null,
        uploading: false,
        error: null,
        success: null,
        currentUpload: null,
        uploadId: null,
        statusInterval: null,

        init() {
            // Check if there's a current upload to monitor
            const urlParams = new URLSearchParams(window.location.search);
            const uploadId = urlParams.get('upload_id');
            if (uploadId) {
                this.uploadId = uploadId;
                this.startStatusPolling(uploadId);
            }
        },

        async uploadFile() {
            if (!this.fileSelected) {
                this.error = 'يرجى اختيار ملف أولاً';
                return;
            }

            this.uploading = true;
            this.error = null;
            this.success = null;

            const formData = new FormData();
            formData.append('file', this.fileSelected);
            formData.append('_token', document.querySelector('meta[name="csrf-token"]').content);

            try {
                const response = await fetch('{{ route("upload.store") }}', {
                    method: 'POST',
                    body: formData,
                });

                const data = await response.json();

                if (data.success) {
                    this.success = data.message;
                    this.uploadId = data.upload_id;
                    this.startStatusPolling(data.upload_id);
                    this.fileSelected = null;
                    document.getElementById('file').value = '';
                } else {
                    this.error = data.message || 'حدث خطأ أثناء رفع الملف';
                }
            } catch (error) {
                this.error = 'حدث خطأ أثناء رفع الملف: ' + error.message;
            } finally {
                this.uploading = false;
            }
        },

        startStatusPolling(uploadId) {
            if (this.statusInterval) {
                clearInterval(this.statusInterval);
            }

            this.statusInterval = setInterval(async () => {
                try {
                    const response = await fetch(`/upload/status/${uploadId}`);
                    const data = await response.json();
                    
                    this.currentUpload = data;

                    if (data.status === 'completed' || data.status === 'failed') {
                        clearInterval(this.statusInterval);
                        // Reload page after 2 seconds to show updated list
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    }
                } catch (error) {
                    console.error('Error fetching status:', error);
                }
            }, 2000); // Poll every 2 seconds
        }
    }
}
</script>
@endsection

