@extends('layouts.app')

@section('content')
<div class="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 py-8 px-4 md:px-8">
    <div class="max-w-4xl mx-auto">
        <!-- رأس الصفحة -->
        <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">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ImportTitle', __('Import Customers')) }}</h1>
                    <p class="text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ImportDescription', __('Import multiple customers from Excel file easily and effectively')) }}</p>
                </div>
                <a href="{{ route('customers.index') }}" class="inline-flex items-center px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                    <i class="fas fa-arrow-right ml-2"></i>
                    <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('General.Back', __('Back')) }}</span>
                </a>
            </div>
        </div>

        <!-- رسائل التنبيه -->
        @if ($errors->any())
            <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6 rounded-r-lg">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
                    </div>
                    <div class="mr-3">
                        <h3 class="text-red-700 font-bold mb-2">{{ \App\Helpers\TranslationHelper::transFromDatabase('General.ErrorsOccurred', __('Errors Occurred')) }}:</h3>
                        <ul class="text-red-600 text-sm space-y-1">
                            @foreach ($errors->all() as $error)
                                <li>• {{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        @endif

        @if (session('partial_success'))
            <div class="bg-yellow-50 border-l-4 border-yellow-500 p-4 mb-6 rounded-r-lg">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-info-circle text-yellow-500 text-xl"></i>
                    </div>
                    <div class="mr-3">
                        <h3 class="text-yellow-700 font-bold mb-2">
                            {{ str_replace(':count', session('success_count'), \App\Helpers\TranslationHelper::transFromDatabase('Customers.PartialSuccess', __('Imported :count customers successfully with some errors'))) }}
                        </h3>
                        @if (session('errors'))
                            <div class="mt-2 text-yellow-600 text-sm space-y-1 max-h-96 overflow-y-auto">
                                @foreach (session('errors') as $error)
                                    <div>{{ $error }}</div>
                                @endforeach
                            </div>
                        @endif
                        @if (session('warnings'))
                            <div class="mt-2 text-yellow-600 text-sm space-y-1 max-h-96 overflow-y-auto">
                                @foreach (session('warnings') as $warning)
                                    <div>{{ $warning }}</div>
                                @endforeach
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        @endif

        <!-- المحتوى الرئيسي -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- الجانب الأيسر - التعليمات -->
            <div class="lg:col-span-1">
                <!-- بطاقة التعليمات -->
                <div class="bg-white rounded-xl shadow-lg p-6 sticky top-8">
                    <h3 class="text-lg font-bold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-info-circle text-blue-600 ml-2"></i>
                        <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Steps', __('Import Steps')) }}</span>
                    </h3>

                    <div class="space-y-4">
                        <!-- خطوة 1 -->
                        <div class="flex gap-3">
                            <div class="flex-shrink-0 w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center font-bold">
                                1
                            </div>
                            <div>
                                <h4 class="font-semibold text-gray-900 mb-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Step1Title', __('Download Template')) }}</h4>
                                <p class="text-sm text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Step1Desc', __('Click on "Download Template" button to download the Excel file in the correct format')) }}</p>
                            </div>
                        </div>

                        <!-- خطوة 2 -->
                        <div class="flex gap-3">
                            <div class="flex-shrink-0 w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center font-bold">
                                2
                            </div>
                            <div>
                                <h4 class="font-semibold text-gray-900 mb-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Step2Title', __('Fill Data')) }}</h4>
                                <p class="text-sm text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Step2Desc', __('Add customers in rows below the table header. Follow the same order and format')) }}</p>
                            </div>
                        </div>

                        <!-- خطوة 3 -->
                        <div class="flex gap-3">
                            <div class="flex-shrink-0 w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center font-bold">
                                3
                            </div>
                            <div>
                                <h4 class="font-semibold text-gray-900 mb-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Step3Title', __('Choose File')) }}</h4>
                                <p class="text-sm text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Step3Desc', __('Select the file from your device and click on "Browse Data"')) }}</p>
                            </div>
                        </div>

                        <!-- خطوة 4 -->
                        <div class="flex gap-3">
                            <div class="flex-shrink-0 w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center font-bold">
                                4
                            </div>
                            <div>
                                <h4 class="font-semibold text-gray-900 mb-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Step4Title', __('Confirm Import')) }}</h4>
                                <p class="text-sm text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Step4Desc', __('Verify the data then click on "Import" to save customers')) }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- قائمة بالنقاط المهمة -->
                    <div class="mt-6 pt-6 border-t border-gray-200">
                        <h4 class="font-semibold text-gray-900 mb-3 flex items-center">
                            <i class="fas fa-lightbulb text-yellow-500 ml-2"></i>
                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ImportantNotes', __('Important Notes')) }}</span>
                        </h4>
                        <ul class="text-sm text-gray-600 space-y-2">
                            <li class="flex items-start">
                                <i class="fas fa-check text-green-600 ml-2 mt-0.5 flex-shrink-0"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Note1', __('Avoid leaving columns marked with * empty')) }}</span>
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check text-green-600 ml-2 mt-0.5 flex-shrink-0"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Note2', __('Email must be valid')) }}</span>
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check text-green-600 ml-2 mt-0.5 flex-shrink-0"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Note3', __('Customer Type: Company or Individual')) }}</span>
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-check text-green-600 ml-2 mt-0.5 flex-shrink-0"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Note4', __('A maximum of 1000 customers can be imported in the file')) }}</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- الجانب الأيمن - نموذج الاستيراد -->
            <div class="lg:col-span-2">
                <!-- بطاقة زر تحميل القالب -->
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 border-2 border-blue-300 rounded-xl p-8 mb-6">
                    <div class="text-center">
                        <div class="inline-flex items-center justify-center w-16 h-16 bg-white rounded-full mb-4">
                            <i class="fas fa-download text-blue-600 text-2xl"></i>
                        </div>
                        <h3 class="text-xl font-bold text-gray-900 mb-2">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.StartHere', __('Start Here')) }}</h3>
                        <p class="text-gray-600 mb-4">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.DownloadDesc', __('Click the button below to download the import template')) }}</p>
                        <a href="{{ route('customers.import.download-template') }}" class="inline-flex items-center px-6 py-3 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 duration-200 shadow-lg hover:shadow-xl">
                            <i class="fas fa-file-excel ml-2"></i>
                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.DownloadTemplate', __('Download Excel Template')) }}</span>
                        </a>
                    </div>
                </div>

                <!-- نموذج الاستيراد -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <form id="importForm" action="{{ route('customers.import.store') }}" method="POST" enctype="multipart/form-data" novalidate>
                        @csrf

                        <!-- حقل رفع الملف -->
                        <div class="mb-6">
                            <label for="file" class="block text-sm font-semibold text-gray-900 mb-3">
                                <i class="fas fa-file-upload ml-1"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ChooseFile', __('Choose Excel File')) }}</span>
                            </label>

                            <div class="relative">
                                <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition-all" id="dropZone">
                                    <input type="file" id="file" name="file" accept=".xlsx,.xls,.csv" class="hidden" required>
                                    
                                    <div id="filePreview" class="hidden">
                                        <i class="fas fa-check-circle text-green-600 text-4xl mb-2"></i>
                                        <p class="text-green-600 font-semibold" id="fileName"></p>
                                        <p class="text-sm text-gray-600 mt-2">
                                            <button type="button" class="text-blue-600 hover:underline" onclick="document.getElementById('file').click()">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ChooseAnotherFile', __('Choose another file')) }}</button>
                                        </p>
                                    </div>

                                    <div id="fileEmpty">
                                        <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
                                        <p class="text-gray-700 font-semibold mb-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.DropFileHere', __('Drop the file here or click to choose')) }}</p>
                                        <p class="text-sm text-gray-500">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.AcceptedFormats', __('Accepted formats: Excel (.xlsx, .xls) or CSV')) }}</p>
                                        <p class="text-xs text-gray-400 mt-2">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.MaxFileSize', __('Maximum size: 10MB')) }}</p>
                                    </div>
                                </div>
                            </div>

                            @error('file')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-triangle ml-1"></i>
                                    <span>{{ $message }}</span>
                                </p>
                            @enderror
                        </div>

                        <!-- خيارات متقدمة -->
                        <details class="mb-6">
                            <summary class="cursor-pointer font-semibold text-gray-900 hover:text-blue-600 transition flex items-center">
                                <i class="fas fa-cog ml-2"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.AdvancedOptions', __('Advanced Options')) }}</span>
                                <i class="fas fa-chevron-down text-xs ml-1"></i>
                            </summary>
                            
                            <div class="mt-4 p-4 bg-gray-50 rounded-lg space-y-4">
                                <label class="flex items-center gap-3 cursor-pointer">
                                    <input type="checkbox" name="skip_duplicates" id="skip_duplicates" class="w-4 h-4">
                                    <span class="text-sm text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.SkipDuplicates', __('Skip duplicate customers')) }}</span>
                                </label>

                                <label class="flex items-center gap-3 cursor-pointer">
                                    <input type="checkbox" name="activate_all" id="activate_all" checked class="w-4 h-4">
                                    <span class="text-sm text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ActivateImported', __('Activate all imported customers')) }}</span>
                                </label>
                            </div>
                        </details>

                        <!-- منطقة المعاينة -->
                        <div id="previewSection" class="mb-6 hidden">
                            <h3 class="font-semibold text-gray-900 mb-3 flex items-center">
                                <i class="fas fa-eye text-blue-600 ml-2"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.DataPreview', __('Data Preview')) }}</span>
                            </h3>

                            <div class="bg-gray-50 rounded-lg p-4 max-h-96 overflow-y-auto">
                                <div id="previewContent"></div>
                            </div>

                            <div id="previewStats" class="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-700">
                                <i class="fas fa-info-circle ml-1"></i>
                                <span id="previewStatsText"></span>
                            </div>
                        </div>

                        <!-- الأزرار -->
                        <div class="flex gap-3">
                            <button type="button" id="previewBtn" class="flex-1 inline-flex items-center justify-center px-6 py-3 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300 transition-all duration-200" onclick="previewFile()">
                                <i class="fas fa-search ml-2"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.BrowseData', __('Browse Data')) }}</span>
                            </button>

                            <button type="submit" class="flex-1 inline-flex items-center justify-center px-6 py-3 bg-gradient-to-r from-green-600 to-green-700 text-white font-semibold rounded-lg hover:from-green-700 hover:to-green-800 transition-all duration-200 shadow-lg hover:shadow-xl" id="submitBtn">
                                <i class="fas fa-upload ml-2"></i>
                                <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ImportAction', __('Import Customers')) }}</span>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- بطاقة معلومات -->
                <div class="mt-6 bg-blue-50 border-l-4 border-blue-500 p-4 rounded-r-lg">
                    <h4 class="font-semibold text-blue-900 mb-2 flex items-center">
                        <i class="fas fa-question-circle text-blue-600 ml-2"></i>
                        <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.FacingProblem', __('Facing a problem?')) }}</span>
                    </h4>
                    <p class="text-sm text-blue-800">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.FacingProblemDesc', __('Make sure the file follows the same format as the downloaded template. If the problem persists, you can contact support.')) }}</p>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('file');
        const fileEmpty = document.getElementById('fileEmpty');
        const filePreview = document.getElementById('filePreview');
        const fileName = document.getElementById('fileName');

        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('border-blue-500', 'bg-blue-50');
        });

        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('border-blue-500', 'bg-blue-50');
        });

        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('border-blue-500', 'bg-blue-50');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                fileInput.files = files;
                updateFileDisplay();
            }
        });

        dropZone.addEventListener('click', () => {
            fileInput.click();
        });

        fileInput.addEventListener('change', updateFileDisplay);

        function updateFileDisplay() {
            const file = fileInput.files[0];
            if (file) {
                fileName.textContent = file.name;
                fileEmpty.classList.add('hidden');
                filePreview.classList.remove('hidden');
            } else {
                fileEmpty.classList.remove('hidden');
                filePreview.classList.add('hidden');
            }
        }
    });

    function previewFile() {
        const fileInput = document.getElementById('file');
        const file = fileInput.files[0];

        if (!file) {
            alert("{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.PleaseChooseFile', __('Please choose a file first')) }}");
            return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('_token', document.querySelector('input[name="_token"]').value);

        const previewBtn = document.getElementById('previewBtn');
        const originalText = previewBtn.innerHTML;
        previewBtn.disabled = true;
        previewBtn.textContent = "{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Previewing', __('Previewing...')) }}";

        fetch("{{ route('customers.import.preview') }}", {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
            }
        })
        .then(response => response.json())
        .then(data => {
            previewBtn.disabled = false;
            previewBtn.innerHTML = originalText;

            if (!data.success) {
                alert(data.message || "{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.PreviewError', __('An error occurred in preview')) }}");
                return;
            }

            const previewContent = document.getElementById('previewContent');
            const previewStats = document.getElementById('previewStatsText');
            const previewSection = document.getElementById('previewSection');

            let html = '<div class="overflow-x-auto"><table class="w-full text-sm">';
            html += '<thead class="bg-gray-200"><tr>';
            html += '<th class="px-3 py-2 text-right">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Name', __('Customer Name')) }}</th>';
            html += '<th class="px-3 py-2 text-right">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Email', __('Email')) }}</th>';
            html += '<th class="px-3 py-2 text-right">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Phone', __('Phone')) }}</th>';
            html += '<th class="px-3 py-2 text-right">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Type', __('Type')) }}</th>';
            html += '</tr></thead><tbody>';

            data.data.forEach(row => {
                html += '<tr class="border-b">';
                html += `<td class="px-3 py-2">${row.name || '-'}</td>`;
                html += `<td class="px-3 py-2">${row.email || '-'}</td>`;
                html += `<td class="px-3 py-2">${row.phone || '-'}</td>`;
                html += `<td class="px-3 py-2">${row.type || '-'}</td>`;
                html += '</tr>';
            });

            html += '</tbody></table></div>';

            previewContent.innerHTML = html;
            
            let statsText = "{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ImportPreviewStats', __('Will import :total customers (:preview showing in preview)')) }}";
            statsText = statsText.replace(':total', data.total_rows).replace(':preview', data.preview_count);
            previewStats.textContent = statsText;
            
            previewSection.classList.remove('hidden');

        })
        .catch(error => {
            previewBtn.disabled = false;
            previewBtn.innerHTML = originalText;
            console.error('Error:', error);
            alert("{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.PreviewError', __('An error occurred in preview')) }}");
        });
    }
</script>
@endpush

@endsection
