@extends('agency.layouts.app')

@section('title', $folder->name)

@section('content')
    <div class="container-fluid px-4">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-0 text-gray-800 d-flex align-items-center">
                    <i class="fas fa-folder me-2" style="color: {{ $folder->color_code ?? '#6c757d' }}"></i>
                    {{ $folder->name }}
                    @if($folder->icon)
                        <i class="fas fa-{{ $folder->icon }} ms-2 text-white bg-primary rounded px-1" style="font-size: 0.8rem;"></i>
                    @endif
                </h1>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item"><a href="{{ route('agency.disk.index') }}">Disk</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('agency.disk.folders.index') }}">Klasörler</a></li>
                        @if(isset($breadcrumbs))
                            @foreach($breadcrumbs as $crumb)
                                @if($loop->last)
                                    <li class="breadcrumb-item active">{{ $crumb['name'] }}</li>
                                @else
                                    <li class="breadcrumb-item">
                                        <a href="{{ route('agency.disk.folders.show', $crumb['id']) }}">{{ $crumb['name'] }}</a>
                                    </li>
                                @endif
                            @endforeach
                        @endif
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
                <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
                    <i class="fas fa-plus"></i> Yeni
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#" onclick="showUploadModal()">
                            <i class="fas fa-upload"></i> Dosya Yükle
                        </a></li>
                    <li><a class="dropdown-item" href="{{ route('agency.disk.folders.create') }}?parent_id={{ $folder->id }}">
                            <i class="fas fa-folder-plus"></i> Alt Klasör Oluştur
                        </a></li>
                </ul>
                <a href="{{ route('agency.disk.folders.edit', $folder) }}" class="btn btn-warning">
                    <i class="fas fa-edit"></i> Düzenle
                </a>
            </div>
        </div>

        <!-- Folder Info -->
        <div class="row mb-4">
            <div class="col-lg-8">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                @if($folder->description)
                                    <p class="text-muted mb-2">{{ $folder->description }}</p>
                                @endif
                                <div class="d-flex flex-wrap gap-2 mb-2">
                                <span class="badge bg-{{ $folder->folder_type == 'tour' ? 'primary' : ($folder->folder_type == 'hotel' ? 'success' : 'secondary') }}">
                                    {{ ucfirst($folder->folder_type) }}
                                </span>
                                    @if($folder->is_public)
                                        <span class="badge bg-success">Herkese Açık</span>
                                    @else
                                        <span class="badge bg-warning">Özel</span>
                                    @endif
                                    @if($folder->level > 0)
                                        <span class="badge bg-info">Seviye {{ $folder->level }}</span>
                                    @endif
                                </div>
                            </div>
                            <div class="col-md-4 text-end">
                                <div class="row text-center">
                                    <div class="col-4">
                                        <div class="text-muted small">Dosyalar</div>
                                        <div class="h5 mb-0">{{ $folder->item_count }}</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="text-muted small">Boyut</div>
                                        <div class="h5 mb-0">{{ number_format($folder->total_size_kb / 1024, 1) }} MB</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="text-muted small">Alt Klasör</div>
                                        <div class="h5 mb-0">{{ $folder->children->count() }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <h6 class="card-title">Hızlı İşlemler</h6>
                        <div class="list-group list-group-flush">
                            <a href="#" class="list-group-item list-group-item-action border-0 px-0" onclick="showUploadModal()">
                                <i class="fas fa-upload text-primary me-2"></i> Dosya Yükle
                            </a>
                            <a href="#" class="list-group-item list-group-item-action border-0 px-0" onclick="selectAllImages()">
                                <i class="fas fa-check-square text-success me-2"></i> Tümünü Seç
                            </a>
                            <a href="#" class="list-group-item list-group-item-action border-0 px-0" onclick="downloadSelected()">
                                <i class="fas fa-download text-info me-2"></i> Seçilenleri İndir
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Alt Klasörler -->
        @if($folder->children->count() > 0)
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Alt Klasörler ({{ $folder->children->count() }})</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        @foreach($folder->children as $child)
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <div class="card border-0 shadow-sm h-100">
                                    <div class="card-body text-center p-2">
                                        <i class="fas fa-folder fa-2x mb-2" style="color: {{ $child->color_code ?? '#6c757d' }}"></i>
                                        <h6 class="card-title small mb-1">{{ Str::limit($child->name, 15) }}</h6>
                                        <p class="card-text small text-muted mb-2">{{ $child->item_count }} dosya</p>
                                        <a href="{{ route('agency.disk.folders.show', $child) }}" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        @endif

        <!-- Dosyalar -->
        <div class="card shadow">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    Dosyalar ({{ $folder->items->count() }})
                </h6>
                <div class="d-flex gap-2">
                    <div class="btn-group btn-group-sm" role="group">
                        <input type="radio" class="btn-check" name="itemView" id="grid-view" checked>
                        <label class="btn btn-outline-secondary" for="grid-view">
                            <i class="fas fa-th"></i>
                        </label>
                        <input type="radio" class="btn-check" name="itemView" id="list-view">
                        <label class="btn btn-outline-secondary" for="list-view">
                            <i class="fas fa-list"></i>
                        </label>
                    </div>
                    <select class="form-select form-select-sm" id="sortSelect" style="width: auto;">
                        <option value="created_at">Yükleme Tarihi</option>
                        <option value="title">Başlık</option>
                        <option value="file_size">Dosya Boyutu</option>
                        <option value="view_count">Görüntülenme</option>
                    </select>
                </div>
            </div>
            <div class="card-body">
                @if($folder->items->count() > 0)
                    <!-- Grid Görünüm -->
                    <div id="grid-content">
                        <div class="row" id="items-container">
                            @foreach($folder->items as $item)
                                <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 mb-3 item-item"
                                     data-created="{{ $item->created_at->timestamp }}"
                                     data-title="{{ $item->title ?? $item->original_name }}"
                                     data-size="{{ $item->file_size }}"
                                     data-views="{{ $item->view_count }}">
                                    <div class="card border-0 shadow-sm h-100 item-card">
                                        <div class="position-relative">
                                            <img src="{{ $item->thumbnail_url }}"
                                                 alt="{{ $item->alt_text ?? $item->title }}"
                                                 class="card-img-top"
                                                 style="height: 150px; object-fit: cover; cursor: pointer;"
                                                 onclick="openImageModal({{ $item->id }})">

                                            <!-- Seçim checkbox -->
                                            <div class="position-absolute top-0 start-0 p-2">
                                                <input type="checkbox" class="form-check-input item-select"
                                                       value="{{ $item->id }}" id="img_{{ $item->id }}">
                                            </div>

                                            <!-- Badges -->
                                            <div class="position-absolute top-0 end-0 p-2">
                                                @if($item->is_featured)
                                                    <span class="badge bg-warning"><i class="fas fa-star"></i></span>
                                                @endif
                                                @if(!$item->is_public)
                                                    <span class="badge bg-danger"><i class="fas fa-lock"></i></span>
                                                @endif
                                            </div>

                                            <!-- Hover overlay -->
                                            <div class="position-absolute bottom-0 start-0 end-0 bg-dark bg-opacity-75 text-white p-2 item-overlay">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <small>{{ $item->formatted_file_size }}</small>
                                                    <div class="btn-group btn-group-sm">
                                                        <button class="btn btn-sm btn-light" onclick="viewImage({{ $item->id }})">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                        <button class="btn btn-sm btn-light" onclick="downloadImage({{ $item->id }})">
                                                            <i class="fas fa-download"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="card-body p-2">
                                            <h6 class="card-title small mb-1">
                                                {{ Str::limit($item->title ?? $item->original_name, 20) }}
                                            </h6>
                                            <p class="card-text small text-muted mb-1">
                                                {{ $item->width }} x {{ $item->height }}
                                            </p>
                                            <p class="card-text small text-muted">
                                                <i class="fas fa-eye"></i> {{ $item->view_count }}
                                                <i class="fas fa-download ms-2"></i> {{ $item->download_count }}
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>

                    <!-- Liste Görünüm -->
                    <div id="list-content" style="display: none;">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-light">
                                <tr>
                                    <th width="30">
                                        <input type="checkbox" class="form-check-input" id="selectAll">
                                    </th>
                                    <th>Dosya</th>
                                    <th>Boyut</th>
                                    <th>Boyutlar</th>
                                    <th>Görüntülenme</th>
                                    <th>Tarih</th>
                                    <th>İşlemler</th>
                                </tr>
                                </thead>
                                <tbody>
                                @foreach($folder->items as $item)
                                    <tr>
                                        <td>
                                            <input type="checkbox" class="form-check-input item-select" value="{{ $item->id }}">
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <img src="{{ $item->thumbnail_url }}"
                                                     alt="{{ $item->alt_text }}"
                                                     class="me-2 rounded"
                                                     style="width: 40px; height: 40px; object-fit: cover;">
                                                <div>
                                                    <div class="fw-bold">{{ Str::limit($item->title ?? $item->original_name, 30) }}</div>
                                                    <small class="text-muted">{{ $item->extension }}</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>{{ $item->formatted_file_size }}</td>
                                        <td>{{ $item->width }} x {{ $item->height }}</td>
                                        <td>{{ $item->view_count }}</td>
                                        <td>{{ $item->created_at->format('d.m.Y') }}</td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-primary" onclick="viewImage({{ $item->id }})">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                <a href="{{ route('agency.disk.items.edit', $item) }}"
                                                   class="btn btn-outline-warning">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <button class="btn btn-outline-success" onclick="downloadImage({{ $item->id }})">
                                                    <i class="fas fa-download"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                @else
                    <!-- Boş Durum -->
                    <div class="text-center py-5">
                        <i class="fas fa-items fa-4x text-gray-400 mb-4"></i>
                        <h4 class="text-gray-600">Bu Klasörde Dosya Yok</h4>
                        <p class="text-gray-500 mb-4">Bu klasöre dosya yükleyerek başlayın.</p>
                        <button class="btn btn-primary" onclick="showUploadModal()">
                            <i class="fas fa-upload"></i> İlk Dosyayı Yükle
                        </button>
                    </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Upload Modal -->
    <div class="modal fade" id="uploadModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Dosya Yükle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="uploadForm" enctype="multipart/form-data">
                        @csrf
                        <div class="mb-3">
                            <label for="files" class="form-label">Dosyalar</label>
                            <input type="file" class="form-control" id="files" name="files[]"
                                   multiple accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.zip,.rar" required>
                            <div class="form-text">Birden fazla dosya seçebilirsiniz. (Resim, Video, Döküman - Max: 50MB)</div>
                        </div>
                        <div id="preview-container" class="row"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="button" class="btn btn-primary" id="uploadBtn">
                        <i class="fas fa-upload"></i> Yükle
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Image View Modal -->
    <div class="modal fade" id="itemModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="itemModalTitle">Dosya</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <img id="modalImage" src="" alt="" class="img-fluid">
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Görünüm değiştirme
            document.getElementById('grid-view').addEventListener('change', function() {
                if (this.checked) {
                    document.getElementById('grid-content').style.display = 'block';
                    document.getElementById('list-content').style.display = 'none';
                }
            });

            document.getElementById('list-view').addEventListener('change', function() {
                if (this.checked) {
                    document.getElementById('grid-content').style.display = 'none';
                    document.getElementById('list-content').style.display = 'block';
                }
            });

            // Sıralama
            document.getElementById('sortSelect').addEventListener('change', function() {
                sortImages(this.value);
            });

            // Tümünü seç
            document.getElementById('selectAll')?.addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.item-select');
                checkboxes.forEach(cb => cb.checked = this.checked);
            });
        });

        function showUploadModal() {
            new bootstrap.Modal(document.getElementById('uploadModal')).show();
        }

        function openImageModal(itemId) {
            // AJAX ile dosya bilgilerini al ve modalda göster
            fetch(`/agency/disk/items/${itemId}`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('itemModalTitle').textContent = data.title || data.original_name;
                    document.getElementById('modalImage').src = data.full_url;
                    new bootstrap.Modal(document.getElementById('itemModal')).show();
                });
        }

        function viewImage(itemId) {
            window.open(`/agency/disk/items/${itemId}`, '_blank');
        }

        function downloadImage(itemId) {
            window.open(`/agency/disk/items/${itemId}/download`, '_blank');
        }

        function selectAllImages() {
            const checkboxes = document.querySelectorAll('.item-select');
            checkboxes.forEach(cb => cb.checked = true);
        }

        function downloadSelected() {
            const selected = Array.from(document.querySelectorAll('.item-select:checked')).map(cb => cb.value);
            if (selected.length === 0) {
                alert('Lütfen en az bir dosya seçin.');
                return;
            }
            // Seçili Dosyalari zip olarak indir
            console.log('Selected items:', selected);
        }

        function sortImages(criteria) {
            const container = document.getElementById('items-container');
            const items = Array.from(container.children);

            items.sort((a, b) => {
                let aVal, bVal;
                switch(criteria) {
                    case 'title':
                        aVal = a.dataset.title.toLowerCase();
                        bVal = b.dataset.title.toLowerCase();
                        return aVal.localeCompare(bVal);
                    case 'file_size':
                        aVal = parseInt(a.dataset.size);
                        bVal = parseInt(b.dataset.size);
                        return bVal - aVal; // Büyükten küçüğe
                    case 'view_count':
                        aVal = parseInt(a.dataset.views);
                        bVal = parseInt(b.dataset.views);
                        return bVal - aVal; // Çoktan aza
                    default: // created_at
                        aVal = parseInt(a.dataset.created);
                        bVal = parseInt(b.dataset.created);
                        return bVal - aVal; // Yeniden eskiye
                }
            });

            items.forEach(item => container.appendChild(item));
        }

        // Upload functionality
        document.getElementById('uploadBtn')?.addEventListener('click', function() {
            const form = document.getElementById('uploadForm');
            const fileInput = document.getElementById('files');

            // Check if files are selected
            if (!fileInput.files || fileInput.files.length === 0) {
                alert('Lütfen en az bir dosya seçin.');
                return;
            }

            const formData = new FormData(form);
            const uploadBtn = this;

            // Disable button and show loading
            uploadBtn.disabled = true;
            uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Yükleniyor...';

            fetch(`/agency/disk/folders/{{ $folder->id }}/upload`, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            .then(response => {
                console.log('Response status:', response.status);
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log('Upload response:', data);
                if (data.success) {
                    alert(data.message || 'Dosyalar başarıyla yüklendi!');
                    location.reload();
                } else {
                    alert('Yükleme hatası: ' + (data.message || 'Bilinmeyen hata'));
                    uploadBtn.disabled = false;
                    uploadBtn.innerHTML = '<i class="fas fa-upload"></i> Yükle';
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                alert('Yükleme sırasında bir hata oluştu: ' + error.message);
                uploadBtn.disabled = false;
                uploadBtn.innerHTML = '<i class="fas fa-upload"></i> Yükle';
            });
        });
    </script>
@endpush

@push('styles')
    <style>
        .item-card .item-overlay {
            opacity: 0;
            transition: opacity 0.3s;
        }

        .item-card:hover .item-overlay {
            opacity: 1;
        }

        .item-card:hover {
            transform: translateY(-2px);
            transition: transform 0.2s;
        }
    </style>
@endpush
