@extends('layouts.app')

@section('title', 'Manage Media - Lingel DAM')
@section('page_header', 'Manage Assets')

@section('content')

    @if(session('success'))
        <div class="bg-green-100 border-l-4 border-[#006837] text-green-700 p-4 mb-6 rounded shadow-sm">
            <p class="font-bold"><i class="fas fa-check-circle mr-2"></i>Success</p>
            <p>{{ session('success') }}</p>
        </div>
    @endif
    @if(session('error'))
        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded shadow-sm">
            <p class="font-bold"><i class="fas fa-exclamation-circle mr-2"></i>Error</p>
            <p>{{ session('error') }}</p>
        </div>
    @endif

    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-8">
        <h3 class="text-lg font-bold text-gray-800 mb-4 border-b pb-3">
            <i class="fas fa-cloud-upload-alt text-[#FBB03B] mr-2"></i> Direct Upload to Cloudflare
        </h3>
        
        <form id="uploadAjaxForm" class="grid grid-cols-1 md:grid-cols-4 gap-6 items-end">
            <div class="md:col-span-1">
                <label class="block text-sm font-semibold text-gray-700 mb-1">Asset Title</label>
                <input type="text" id="assetTitle" name="title" required placeholder="e.g., uPVC Window Promo" class="w-full border border-gray-300 rounded-lg px-4 py-2.5 focus:border-[#006837] focus:ring focus:ring-[#006837]/20 outline-none transition">
            </div>

            <div class="md:col-span-1">
                <label class="block text-sm font-semibold text-gray-700 mb-1">Category</label>
                <select id="assetCategory" name="category_id" required class="w-full border border-gray-300 rounded-lg px-4 py-2.5 focus:border-[#006837] focus:ring focus:ring-[#006837]/20 outline-none transition bg-white">
                    <option value="">-- Select --</option>
                    @foreach($categories as $cat)
                        <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                    @endforeach
                </select>
            </div>

            <div class="md:col-span-1">
                <label class="block text-sm font-semibold text-gray-700 mb-1">Select File (Any Size)</label>
                <input type="file" id="fileInput" required class="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-bold file:bg-[#006837]/10 file:text-[#006837] hover:file:bg-[#006837]/20 transition cursor-pointer">
            </div>

            <div class="md:col-span-1 flex justify-end">
                <button type="button" id="uploadDirectBtn" class="w-full bg-[#006837] hover:bg-[#00522c] text-white px-6 py-2.5 rounded-lg shadow-md transition font-bold text-sm tracking-wide">
                    Start Direct Upload
                </button>
            </div>

            <div id="progressContainer" class="col-span-1 md:col-span-4 hidden mt-2">
                <div class="flex justify-between text-xs font-bold text-gray-600 mb-1">
                    <span id="uploadStatusLabel">Initializing...</span>
                    <span id="uploadPercentLabel">0%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-3 overflow-hidden">
                    <div id="uploadProgressBar" class="bg-[#FBB03B] h-3 rounded-full transition-all duration-200" style="width: 0%"></div>
                </div>
            </div>
        </form>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
        <form action="{{ route('admin.assets') }}" method="GET" class="flex flex-wrap gap-4 items-end">
            <div class="flex-1 min-w-[200px]">
                <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Search Title</label>
                <input type="text" name="search" value="{{ request('search') }}" placeholder="Search assets..." class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:border-[#006837] outline-none text-sm">
            </div>
            
            <div class="w-full md:w-48">
                <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Category</label>
                <select name="category_id" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:border-[#006837] outline-none bg-white text-sm">
                    <option value="">All Categories</option>
                    @foreach($categories as $cat)
                        <option value="{{ $cat->id }}" {{ request('category_id') == $cat->id ? 'selected' : '' }}>{{ $cat->name }}</option>
                    @endforeach
                </select>
            </div>

            <div class="w-full md:w-48">
                <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Type</label>
                <select name="file_type" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:border-[#006837] outline-none bg-white text-sm">
                    <option value="">All Types</option>
                    <option value="video" {{ request('file_type') == 'video' ? 'selected' : '' }}>Video</option>
                    <option value="image" {{ request('file_type') == 'image' ? 'selected' : '' }}>Image</option>
                    <option value="document" {{ request('file_type') == 'document' ? 'selected' : '' }}>Document/Other</option>
                </select>
            </div>

            <div class="flex gap-2">
                <button type="submit" class="bg-gray-800 hover:bg-gray-900 text-white px-5 py-2 rounded-lg transition font-semibold text-sm">
                    Filter
                </button>
                @if(request()->hasAny(['search', 'category_id', 'file_type']))
                    <a href="{{ route('admin.assets') }}" class="bg-red-50 hover:bg-red-100 text-red-600 px-4 py-2 rounded-lg transition font-semibold text-sm flex items-center">
                        Clear
                    </a>
                @endif
            </div>
        </form>
    </div>

    @if($assets->count() > 0)
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <table class="w-full text-left border-collapse">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="px-6 py-4 text-xs tracking-wider text-gray-500 font-bold uppercase">Asset Details</th>
                        <th class="px-6 py-4 text-xs tracking-wider text-gray-500 font-bold uppercase">Category</th>
                        <th class="px-6 py-4 text-xs tracking-wider text-gray-500 font-bold uppercase">Size</th>
                        <th class="px-6 py-4 text-xs tracking-wider text-gray-500 font-bold uppercase text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @foreach($assets as $asset)
                    <tr class="hover:bg-gray-50 transition duration-150">
                        <td class="px-6 py-4 font-medium text-gray-800">
                            <div class="flex items-center gap-3">
                                @if($asset->file_type == 'video') 
                                    <div class="bg-blue-100 p-2 rounded-lg text-blue-600"><i class="fas fa-video"></i></div>
                                @elseif($asset->file_type == 'image') 
                                    <div class="bg-green-100 p-2 rounded-lg text-green-600"><i class="fas fa-image"></i></div>
                                @else 
                                    <div class="bg-red-100 p-2 rounded-lg text-red-600"><i class="fas fa-file-alt"></i></div>
                                @endif
                                <div>
                                    <span class="text-sm block">{{ $asset->title }}</span>
                                    @if(Auth::user()->role === 'super_admin')
                                        <span class="text-[10px] text-gray-400 font-normal">By: {{ $asset->user->name ?? 'Unknown' }}</span>
                                    @endif
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <span class="bg-[#FBB03B]/20 text-[#006837] px-3 py-1 rounded-full text-xs font-bold border border-[#FBB03B]/30">
                                {{ $asset->category->name ?? 'Uncategorized' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 text-gray-500 text-sm font-medium">{{ $asset->file_size }}</td>
                        <td class="px-6 py-4 text-right flex justify-end gap-2">
                            <a href="{{ $asset->file_url }}" target="_blank" class="text-blue-500 hover:text-blue-700 bg-blue-50 hover:bg-blue-100 px-3 py-1.5 rounded-md transition text-xs font-bold">
                                <i class="fas fa-external-link-alt mr-1"></i> View
                            </a>
                            <button onclick="openEditAssetModal({{ $asset->id }}, '{{ addslashes($asset->title) }}', '{{ $asset->category_id }}')" class="text-indigo-500 hover:text-indigo-700 bg-indigo-50 hover:bg-indigo-100 px-3 py-1.5 rounded-md transition text-xs font-bold">
                                <i class="fas fa-edit mr-1"></i> Edit
                            </button>
                            <form action="{{ route('admin.assets.destroy', $asset->id) }}" method="POST" onsubmit="return confirm('Are you sure you want to permanently delete this asset from Cloudflare R2?');">
                                @csrf @method('DELETE')
                                <button type="submit" class="text-red-500 hover:text-red-700 bg-red-50 hover:bg-red-100 px-3 py-1.5 rounded-md transition text-xs font-bold">
                                    <i class="fas fa-trash-alt mr-1"></i> Delete
                                </button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
        
        <div class="mt-6 mb-4">
            {{ $assets->links() }}
        </div>
    @else
        <div class="bg-white rounded-xl shadow-sm p-12 border border-gray-200 text-center">
            <div class="inline-flex items-center justify-center w-20 h-20 bg-gray-50 rounded-full mb-4">
                <i class="fas fa-photo-video text-4xl text-gray-300"></i>
            </div>
            <h3 class="text-xl text-gray-700 font-bold">No Assets Found</h3>
            <p class="text-gray-500 mt-2">No media matches your criteria or you haven't uploaded anything yet.</p>
        </div>
    @endif

    <div id="editAssetModal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-50 overflow-y-auto h-full w-full flex items-center justify-center z-50">
        <div class="bg-white p-6 rounded-xl shadow-xl w-full max-w-md border border-gray-200">
            <h3 class="text-xl font-bold mb-4 text-gray-800"><i class="fas fa-edit text-indigo-500 mr-2"></i>Edit Asset Details</h3>
            
            <form id="editAssetForm" method="POST">
                @csrf 
                @method('PUT')
                
                <div class="mb-4">
                    <label class="block text-gray-700 text-sm font-bold mb-2">Asset Title</label>
                    <input type="text" id="editAssetTitle" name="title" class="w-full px-4 py-2.5 border rounded-lg focus:outline-none focus:border-[#006837]" required>
                </div>

                <div class="mb-6">
                    <label class="block text-gray-700 text-sm font-bold mb-2">Category</label>
                    <select id="editAssetCategory" name="category_id" class="w-full px-4 py-2.5 border rounded-lg focus:outline-none focus:border-[#006837] bg-white" required>
                        @foreach($categories as $cat)
                            <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="flex justify-end gap-3">
                    <button type="button" onclick="closeEditAssetModal()" class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold px-4 py-2 rounded-lg transition">Cancel</button>
                    <button type="submit" class="bg-[#006837] hover:bg-[#00522c] text-white font-bold px-4 py-2 rounded-lg transition shadow-md">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function openEditAssetModal(id, title, categoryId) {
            document.getElementById('editAssetForm').action = '/admin/assets/' + id;
            document.getElementById('editAssetTitle').value = title;
            document.getElementById('editAssetCategory').value = categoryId;
            document.getElementById('editAssetModal').classList.remove('hidden');
            document.getElementById('editAssetModal').classList.add('flex');
        }

        function closeEditAssetModal() {
            document.getElementById('editAssetModal').classList.add('hidden');
            document.getElementById('editAssetModal').classList.remove('flex');
        }

        // Direct Upload Magic (No Server Limits)
        $(document).ready(function() {
            $('#uploadDirectBtn').on('click', async function(e) {
                // Prevent anything else from happening
                e.preventDefault(); 

                let fileInput = document.getElementById('fileInput');
                if (fileInput.files.length === 0) return alert("Bhai, pehle file select karo!");
                let file = fileInput.files[0];

                let title = $('#assetTitle').val();
                let categoryId = $('#assetCategory').val();
                if (!title || !categoryId) return alert("Title aur Category dono daalna zaroori hai!");

                let uploadBtn = $('#uploadDirectBtn');
                let progressContainer = $('#progressContainer');
                let progressBar = $('#uploadProgressBar');
                let percentLabel = $('#uploadPercentLabel');
                let statusLabel = $('#uploadStatusLabel');

                // UI Loading State
                uploadBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i> Processing...');
                progressContainer.removeClass('hidden');
                progressBar.removeClass('bg-green-500 animate-pulse').addClass('bg-[#FBB03B]').css('width', '0%');
                percentLabel.text('0%');
                statusLabel.text('Requesting secure cloud link...').removeClass('text-green-600 text-red-600').addClass('text-gray-600');

                try {
                    let fileTypeToUse = file.type || 'application/octet-stream';

                    // 1. Get Presigned URL from Laravel
                    let urlResponse = await fetch("{{ route('admin.assets.presigned') }}", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({
                            filename: file.name,
                            contentType: fileTypeToUse
                        })
                    });
                    
                    let urlData = await urlResponse.json();
                    if(!urlData.upload_url) throw new Error("Secure Link generate nahi hua.");

                    statusLabel.text('Uploading straight to Cloudflare R2... (0% Server Load)');

                    // 2. Upload directly to Cloudflare via XHR to get progress
                    await new Promise((resolve, reject) => {
                        let xhr = new XMLHttpRequest();
                        xhr.open('PUT', urlData.upload_url, true);
                        xhr.setRequestHeader('Content-Type', fileTypeToUse);
                        
                        xhr.upload.onprogress = function(evt) {
                            if (evt.lengthComputable) {
                                let percentComplete = Math.round((evt.loaded / evt.total) * 100);
                                progressBar.css('width', percentComplete + '%');
                                percentLabel.text(percentComplete + '%');
                            }
                        };
                        
                        xhr.onload = function() {
                            if (xhr.status >= 200 && xhr.status < 300) resolve(true);
                            else reject(new Error('Cloudflare rejected the upload. CORS policy error ya bad URL.'));
                        };
                        
                        xhr.onerror = () => reject(new Error('Network error. Upload failed.'));
                        xhr.send(file);
                    });

                    // 3. Prepare details
                    statusLabel.text('Saving details in database...');
                    progressBar.addClass('animate-pulse');

                    let ext = file.name.split('.').pop().toLowerCase();
                    let fileCategory = 'document';
                    if (['mp4', 'mov', 'avi', 'mkv'].includes(ext) || file.type.startsWith('video/')) fileCategory = 'video';
                    else if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext) || file.type.startsWith('image/')) fileCategory = 'image';

                    let sizeMB = (file.size / 1048576).toFixed(2);
                    let sizeStr = sizeMB > 1024 ? (file.size / 1073741824).toFixed(2) + ' GB' : sizeMB + ' MB';

                    // 4. Save metadata via AJAX
                    await $.ajax({
                        url: "{{ route('admin.assets.upload') }}",
                        type: 'POST',
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                        data: {
                            title: title,
                            category_id: categoryId,
                            file_path: urlData.path,
                            file_url: urlData.public_url,
                            file_type: fileCategory,
                            file_size: sizeStr
                        }
                    });

                    // Success!
                    statusLabel.text('Upload 100% Complete!');
                    statusLabel.removeClass('text-gray-600').addClass('text-green-600');
                    progressBar.removeClass('bg-[#FBB03B] animate-pulse').addClass('bg-green-500');
                    setTimeout(() => { window.location.reload(); }, 1000);

                } catch (error) {
                    alert('Upload Error: ' + error.message);
                    uploadBtn.prop('disabled', false).html('Start Direct Upload');
                    progressContainer.addClass('hidden');
                }
            });
        });
    </script>
@endsection