<?php $__env->startSection('title', 'Media Library'); ?>

<?php $__env->startPush('extra_head'); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js"></script>
<style>
    .cropper-container { max-height: 500px; }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="container mx-auto" x-data="mediaLibrary()">
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
        <div>
            <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Media Library</h1>
            <p class="text-slate-500 mt-1">Manage all your images and documents in one place.</p>
        </div>
        
        <div class="flex items-center gap-3">
            <input type="file" id="fileUpload" multiple @change="uploadFiles" class="hidden">
            <button @click="document.getElementById('fileUpload').click()" :disabled="isLoading" class="bg-brand-primary hover:bg-brand-accent text-white font-bold py-3 px-6 rounded-xl shadow-lg shadow-brand-primary/20 transition flex items-center gap-2 disabled:opacity-50">
                <template x-if="!isLoading">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                </template>
                <template x-if="isLoading">
                    <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                </template>
                <span x-text="isLoading ? 'Uploading...' : 'Upload Files'"></span>
            </button>
        </div>
    </div>

    <!-- Filters & Search -->
    <div class="bg-white p-4 rounded-2xl shadow-sm border border-slate-100 flex flex-col md:flex-row md:items-center gap-4 mb-8">
        <div class="flex-1 relative">
            <svg class="w-5 h-5 text-slate-400 absolute left-4 top-1/2 transform -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
            <input type="text" x-model="search" @input.debounce.300ms="fetchItems()" placeholder="Search by filename..." class="w-full pl-12 pr-4 py-3 bg-slate-50 border border-slate-100 rounded-xl focus:ring-2 focus:ring-brand-primary focus:border-transparent outline-none transition">
        </div>
        <div class="flex items-center gap-2">
            <select x-model="type" @change="fetchItems()" class="bg-slate-50 border border-slate-100 rounded-xl px-4 py-3 outline-none focus:ring-2 focus:ring-brand-primary text-slate-600 font-medium">
                <option value="all">All Types</option>
                <option value="image">Images</option>
                <option value="application/pdf">PDF Documents</option>
            </select>
        </div>
    </div>

    <!-- Media Container (Grid + Pagination) -->
    <div id="mediaContainer">
        <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-6" id="mediaGrid">
            <?php echo $__env->make('admin.media.partials.items', ['mediaItems' => $mediaItems], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
        </div>

        <?php if($mediaItems->hasPages()): ?>
        <div class="mt-12 flex justify-center ajax-pagination">
            <?php echo e($mediaItems->links()); ?>

        </div>
        <?php endif; ?>
    </div>

    <!-- Crop Modal -->
    <template x-if="isCropOpen">
        <div class="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-slate-900/80 backdrop-blur-sm">
            <div class="bg-white rounded-3xl shadow-2xl w-full max-w-4xl overflow-hidden flex flex-col max-h-[90vh]">
                <div class="p-6 border-b border-slate-100 flex items-center justify-between shrink-0">
                    <h3 class="text-xl font-bold text-slate-900">Crop Image</h3>
                    <button @click="closeCropModal()" class="text-slate-400 hover:text-slate-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                    </button>
                </div>
                
                <div class="flex-1 p-6 overflow-hidden bg-slate-50 flex items-center justify-center">
                    <div class="max-w-full max-h-full">
                        <img id="cropImage" :src="cropUrl" class="max-w-full block">
                    </div>
                </div>

                <div class="p-6 border-t border-slate-100 flex items-center justify-between shrink-0">
                    <div class="flex items-center gap-2">
                        <button @click="cropper.setAspectRatio(1)" class="px-3 py-1 bg-slate-100 rounded-lg text-xs font-bold uppercase transition hover:bg-slate-200">1:1</button>
                        <button @click="cropper.setAspectRatio(16/9)" class="px-3 py-1 bg-slate-100 rounded-lg text-xs font-bold uppercase transition hover:bg-slate-200">16:9</button>
                        <button @click="cropper.setAspectRatio(4/3)" class="px-3 py-1 bg-slate-100 rounded-lg text-xs font-bold uppercase transition hover:bg-slate-200">4:3</button>
                        <button @click="cropper.setAspectRatio(NaN)" class="px-3 py-1 bg-slate-100 rounded-lg text-xs font-bold uppercase transition hover:bg-slate-200">Free</button>
                    </div>
                    <div class="flex items-center gap-3">
                        <button @click="closeCropModal()" class="px-6 py-3 text-slate-500 font-bold hover:bg-slate-100 rounded-xl transition">Cancel</button>
                        <button @click="saveCrop()" :disabled="isSaving" class="bg-brand-primary hover:bg-brand-accent text-white font-bold py-3 px-8 rounded-xl shadow-lg shadow-brand-primary/20 transition flex items-center gap-2 disabled:opacity-50">
                            <template x-if="isSaving">
                                <svg class="animate-spin h-5 w-5 text-white" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                            </template>
                            <span x-text="isSaving ? 'Saving...' : 'Save Cropped Image'"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </template>
</div>

<?php $__env->startPush('extra_scripts'); ?>
<script>
document.addEventListener('click', function(e) {
    if (e.target.closest('.ajax-pagination a')) {
        e.preventDefault();
        const url = e.target.closest('a').href;
        window.dispatchEvent(new CustomEvent('fetch-media', { detail: { url } }));
    }
});

function mediaLibrary() {
    return {
        search: '',
        type: 'all',
        isLoading: false,
        isCropOpen: false,
        isSaving: false,
        cropUrl: '',
        cropId: null,
        cropper: null,

        init() {
            window.addEventListener('fetch-media', (e) => {
                this.fetchItems(e.detail.url);
            });
            window.addEventListener('delete-media', (e) => {
                this.deleteMedia(e.detail.id);
            });
        },

        openCropModal(id, url) {
            this.cropId = id;
            this.cropUrl = url;
            this.isCropOpen = true;
            this.$nextTick(() => {
                const image = document.getElementById('cropImage');
                this.cropper = new Cropper(image, {
                    viewMode: 1,
                    dragMode: 'move',
                    aspectRatio: NaN,
                    autoCropArea: 1,
                    restore: false,
                    guides: true,
                    center: true,
                    highlight: false,
                    cropBoxMovable: true,
                    cropBoxResizable: true,
                    toggleDragModeOnDblclick: false,
                });
            });
        },

        closeCropModal() {
            if (this.cropper) {
                this.cropper.destroy();
                this.cropper = null;
            }
            this.isCropOpen = false;
            this.cropId = null;
            this.cropUrl = '';
        },

        async saveCrop() {
            this.isSaving = true;
            const canvas = this.cropper.getCroppedCanvas();
            const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.9));
            
            const formData = new FormData();
            formData.append('crop_image', blob, 'cropped.jpg');
            formData.append('_token', '<?php echo e(csrf_token()); ?>');

            try {
                const response = await fetch(`<?php echo e(url('admin/media')); ?>/${this.cropId}/crop`, {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                });
                const result = await response.json();
                if (result.success) {
                    this.closeCropModal();
                    this.fetchItems();
                } else {
                    alert('Save failed: ' + result.message);
                }
            } catch (error) {
                console.error('Crop failed:', error);
            } finally {
                this.isSaving = false;
            }
        },

        async uploadFiles(e) {
            const files = e.target.files;
            if (files.length === 0) return;

            const formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append('files[]', files[i]);
            }
            formData.append('_token', '<?php echo e(csrf_token()); ?>');

            try {
                this.isLoading = true;
                const response = await fetch('<?php echo e(route('admin.media.store')); ?>', {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                });
                const result = await response.json();
                if (result.success) {
                    this.fetchItems();
                } else {
                    alert('Upload failed: ' + result.message);
                }
            } catch (error) {
                console.error('Upload failed:', error);
                alert('Upload failed. Check the console for details.');
            } finally {
                this.isLoading = false;
                e.target.value = ''; // Reset input
            }
        },

        async fetchItems(url = null) {
            if (!url) {
                const searchUrl = new URL('<?php echo e(route('admin.media.index')); ?>');
                searchUrl.searchParams.set('search', this.search);
                searchUrl.searchParams.set('type', this.type);
                url = searchUrl.toString();
            }

            try {
                const response = await fetch(url, {
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                });
                const html = await response.text();
                document.getElementById('mediaContainer').innerHTML = html;
            } catch (error) {
                console.error('Fetch failed:', error);
            }
        },

        async deleteMedia(id) {
            if (!confirm('Are you sure you want to delete this file? This cannot be undone.')) return;

            try {
                const response = await fetch(`<?php echo e(url('admin/media')); ?>/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                const result = await response.json();
                if (result.success) {
                    document.querySelector(`[data-media-id="${id}"]`).remove();
                }
            } catch (error) {
                console.error('Delete failed:', error);
            }
        }
    }
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        alert('URL copied to clipboard!');
    });
}
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\ecs\resources\views/admin/media/index.blade.php ENDPATH**/ ?>