@extends('admin.layouts.app')

@section('title', 'Edit University Partners')

@section('content')
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1 class="h3 mb-0 text-gray-800">Edit University Partners Section</h1>
                    <a href="{{ route('admin.university-partners.index') }}" class="btn btn-secondary">
                        <i class="bi bi-arrow-left me-2"></i>Back to Overview
                    </a>
                </div>

                @if ($errors->any())
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Please fix the following errors:</strong>
                        <ul class="mb-0 mt-2">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                @endif

                <form action="{{ route('admin.university-partners.update') }}" method="POST" id="partnersForm">
                    @csrf
                    @method('PUT')

                    <!-- Section Settings -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Section Settings</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="title" class="form-label">Section Title</label>
                                        <input type="text" class="form-control" id="title" name="title"
                                            value="{{ old('title', $partnersSection->title ?? 'Our Trusted University Partners') }}"
                                            placeholder="Our Trusted University Partners" required>
                                        <div class="form-text">The main heading for the university partners section</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="is_active" name="is_active"
                                                {{ old('is_active', $partnersSection->is_active ?? true) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="is_active">
                                                Section Active
                                            </label>
                                        </div>
                                        <div class="form-text">Toggle to show/hide this section on the website</div>
                                    </div>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="content" class="form-label">Section Description</label>
                                <textarea class="form-control" id="content" name="content" rows="3"
                                    placeholder="We work directly with leading universities to provide you with the best opportunities." required>{{ old('content', $partnersSection->content ?? 'We work directly with leading universities to provide you with the best opportunities.') }}</textarea>
                                <div class="form-text">Brief description that appears below the section title</div>
                            </div>
                        </div>
                    </div>

                    <!-- University Partners Management -->
                    <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">University Partners</h6>
                            <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal"
                                data-bs-target="#addPartnerModal">
                                <i class="bi bi-plus-circle me-1"></i>Add Partner
                            </button>
                        </div>
                        <div class="card-body">
                            <div id="partnersContainer" class="sortable-container">
                                @if ($partnersSection && $partnersSection->data && isset($partnersSection->data['partners']))
                                    @foreach ($partnersSection->data['partners'] as $index => $partner)
                                        <div class="partner-item mb-3 p-3 border rounded" draggable="true"
                                            data-index="{{ $index }}">
                                            <div class="d-flex align-items-center">
                                                <div class="drag-handle me-3" style="cursor: move;">
                                                    <i class="bi bi-grip-vertical text-muted"></i>
                                                </div>
                                                <div class="me-3">
                                                    <i class="{{ $partner['icon'] ?? 'bi bi-mortarboard-fill' }}"
                                                        style="font-size: 2rem; color: {{ $partner['color'] ?? '#3b82f6' }};"></i>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-1">{{ $partner['name'] }}</h6>
                                                    <small class="text-muted">{{ $partner['country'] }}</small>
                                                    @if (!empty($partner['ranking']))
                                                        <span class="badge bg-info ms-2">Rank
                                                            #{{ $partner['ranking'] }}</span>
                                                    @endif
                                                </div>
                                                <button type="button" class="btn btn-danger btn-sm remove-partner"
                                                    data-index="{{ $index }}">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>

                                            <!-- Hidden inputs for form submission -->
                                            <input type="hidden" name="partners[{{ $index }}][name]"
                                                value="{{ $partner['name'] }}">
                                            <input type="hidden" name="partners[{{ $index }}][country]"
                                                value="{{ $partner['country'] }}">
                                            <input type="hidden" name="partners[{{ $index }}][display_name]"
                                                value="{{ $partner['display_name'] ?? '' }}">
                                            <input type="hidden" name="partners[{{ $index }}][icon]"
                                                value="{{ $partner['icon'] ?? 'bi bi-mortarboard-fill' }}">
                                            <input type="hidden" name="partners[{{ $index }}][color]"
                                                value="{{ $partner['color'] ?? '#3b82f6' }}">
                                            <input type="hidden" name="partners[{{ $index }}][badge]"
                                                value="{{ $partner['badge'] ?? 'University' }}">
                                            <input type="hidden" name="partners[{{ $index }}][ranking]"
                                                value="{{ $partner['ranking'] ?? '' }}">
                                            <input type="hidden" name="partners[{{ $index }}][logo]"
                                                value="{{ $partner['logo'] ?? '' }}">
                                        </div>
                                    @endforeach
                                @endif
                            </div>

                            @if (
                                !$partnersSection ||
                                    !$partnersSection->data ||
                                    !isset($partnersSection->data['partners']) ||
                                    count($partnersSection->data['partners']) == 0)
                                <div class="text-center py-4" id="emptyState">
                                    <i class="bi bi-mortarboard text-muted" style="font-size: 3rem;"></i>
                                    <h5 class="mt-3 text-muted">No Partners Added Yet</h5>
                                    <p class="text-muted">Click "Add Partner" to start building your university partners
                                        showcase.</p>
                                </div>
                            @endif
                        </div>
                    </div>

                    <!-- Save Button -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="bi bi-check-circle me-2"></i>Save Changes
                            </button>
                            <a href="{{ route('admin.university-partners.index') }}"
                                class="btn btn-secondary btn-lg ms-2">
                                Cancel
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Partner Modal -->
    <div class="modal fade" id="addPartnerModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add University Partner</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addPartnerForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="partner_name" class="form-label">University Name *</label>
                                    <input type="text" class="form-control" id="partner_name" name="name"
                                        placeholder="University of Oxford" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="partner_country" class="form-label">Country *</label>
                                    <input type="text" class="form-control" id="partner_country" name="country"
                                        placeholder="United Kingdom" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="partner_display_name" class="form-label">Display Name</label>
                                    <input type="text" class="form-control" id="partner_display_name"
                                        name="display_name" placeholder="University of<br><strong>Oxford</strong>">
                                    <div class="form-text">HTML formatting allowed for display</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="partner_badge" class="form-label">Badge Text</label>
                                    <input type="text" class="form-control" id="partner_badge" name="badge"
                                        placeholder="Russell Group" value="University">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="partner_icon" class="form-label">Icon Class</label>
                                    <input type="text" class="form-control" id="partner_icon" name="icon"
                                        placeholder="bi bi-mortarboard-fill" value="bi bi-mortarboard-fill">
                                    <div class="form-text">Bootstrap Icons class</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="partner_color" class="form-label">Color</label>
                                    <input type="color" class="form-control form-control-color" id="partner_color"
                                        name="color" value="#3b82f6">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="partner_ranking" class="form-label">World Ranking</label>
                                    <input type="number" class="form-control" id="partner_ranking" name="ranking"
                                        placeholder="1" min="1" max="1000">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="partner_logo" class="form-label">University Logo</label>
                            <input type="file" class="form-control" id="partner_logo" name="logo"
                                accept="image/*">
                            <div class="form-text">Upload university logo (JPG, PNG, GIF, SVG - Max 2MB)</div>
                            <div id="logo_preview" class="mt-2" style="display: none;">
                                <img id="preview_image" src="" alt="Logo Preview"
                                    style="max-width: 100px; max-height: 100px; border: 1px solid #ddd; border-radius: 4px; padding: 5px;">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="savePartner">Add Partner</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <style>
        .partner-item {
            transition: all 0.3s ease;
            background: #f8f9fc;
        }

        .partner-item:hover {
            background: #eaecf4;
            transform: translateY(-1px);
        }

        .partner-item.dragging {
            opacity: 0.5;
            transform: rotate(5deg);
        }

        .sortable-container {
            min-height: 100px;
        }

        .drag-handle {
            color: #858796;
        }

        .drag-handle:hover {
            color: #5a5c69;
        }

        .partner-item.drag-over {
            border-color: #4e73df;
            background: #e3f2fd;
        }
    </style>
@endpush

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM Content Loaded - initializing Add Partner functionality');

            const partnersContainer = document.getElementById('partnersContainer');
            const addPartnerForm = document.getElementById('addPartnerForm');
            const savePartnerBtn = document.getElementById('savePartner');
            const addPartnerModal = new bootstrap.Modal(document.getElementById('addPartnerModal'));
            let partnerIndex =
                {{ $partnersSection && $partnersSection->data && isset($partnersSection->data['partners']) ? count($partnersSection->data['partners']) : 0 }};

            console.log('Elements found:', {
                partnersContainer: !!partnersContainer,
                addPartnerForm: !!addPartnerForm,
                savePartnerBtn: !!savePartnerBtn,
                addPartnerModal: !!addPartnerModal
            });

            if (!savePartnerBtn) {
                console.error('Save Partner button not found!');
                return;
            }

            if (!addPartnerForm) {
                console.error('Add Partner form not found!');
                return;
            }

            // Initialize button functionality
            console.log('Button found and ready for event listeners');

            // Logo preview functionality
            document.getElementById('partner_logo').addEventListener('change', function(e) {
                const file = e.target.files[0];
                const preview = document.getElementById('logo_preview');
                const previewImage = document.getElementById('preview_image');

                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        previewImage.src = e.target.result;
                        preview.style.display = 'block';
                    };
                    reader.readAsDataURL(file);
                } else {
                    preview.style.display = 'none';
                }
            });

            // Add new partner
            console.log('Adding main click handler...');
            savePartnerBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                console.log('MAIN HANDLER: Add Partner button clicked!');

                try {
                    const formData = new FormData(addPartnerForm);
                    console.log('Form data created successfully');

                    console.log('Form validation - name:', formData.get('name'), 'country:', formData.get(
                        'country'));

                    if (!formData.get('name') || !formData.get('country')) {
                        alert('Please fill in the required fields (Name and Country)');
                        return;
                    }

                    // Add CSRF token to FormData
                    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute(
                        'content');
                    formData.append('_token', csrfToken);
                    console.log('CSRF token added:', csrfToken);

                    // Send AJAX request to add partner
                    console.log('Sending request to:',
                        '{{ route('admin.university-partners.add-partner') }}');
                    fetch('{{ route('admin.university-partners.add-partner') }}', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => {
                            console.log('Response received:', response.status, response.statusText);
                            if (!response.ok) {
                                throw new Error(`HTTP error! status: ${response.status}`);
                            }
                            return response.json();
                        })
                        .then(data => {
                            console.log('Response data:', data);
                            if (data.success) {
                                addPartnerToContainer(data.partner);
                                addPartnerForm.reset();
                                document.getElementById('partner_color').value = '#3b82f6';
                                document.getElementById('partner_icon').value =
                                    'bi bi-mortarboard-fill';
                                document.getElementById('partner_badge').value = 'University';
                                document.getElementById('logo_preview').style.display = 'none';
                                addPartnerModal.hide();

                                // Hide empty state
                                const emptyState = document.getElementById('emptyState');
                                if (emptyState) {
                                    emptyState.style.display = 'none';
                                }

                                // Show success message
                                alert('Partner added successfully!');
                            } else {
                                alert('Error adding partner: ' + (data.message || 'Unknown error'));
                            }
                        })
                        .catch(error => {
                            console.error('Fetch error:', error);
                            alert('Error adding partner: ' + error.message);
                        });
                } catch (error) {
                    console.error('JavaScript error:', error);
                    alert('JavaScript error: ' + error.message);
                }
            });

            function addPartnerToContainer(partner) {
                const logoDisplay = partner.logo ?
                    `<img src="{{ asset('img/university-logos/') }}/${partner.logo}" alt="${partner.name} Logo" style="width: 40px; height: 40px; object-fit: contain; border-radius: 4px; border: 1px solid #ddd;">` :
                    `<i class="${partner.icon || 'bi bi-mortarboard-fill'}" style="font-size: 2rem; color: ${partner.color || '#3b82f6'};"></i>`;

                const partnerHtml = `
            <div class="partner-item mb-3 p-3 border rounded" draggable="true" data-index="${partnerIndex}">
                <div class="d-flex align-items-center">
                    <div class="drag-handle me-3" style="cursor: move;">
                        <i class="bi bi-grip-vertical text-muted"></i>
                    </div>
                    <div class="me-3">
                        ${logoDisplay}
                    </div>
                    <div class="flex-grow-1">
                        <h6 class="mb-1">${partner.name}</h6>
                        <small class="text-muted">${partner.country}</small>
                        ${partner.ranking ? `<span class="badge bg-info ms-2">Rank #${partner.ranking}</span>` : ''}
                        ${partner.logo ? '<span class="badge bg-success ms-2"><i class="bi bi-image"></i> Logo</span>' : ''}
                    </div>
                    <button type="button" class="btn btn-danger btn-sm remove-partner" data-index="${partnerIndex}">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>

                <input type="hidden" name="partners[${partnerIndex}][name]" value="${partner.name || ''}">
                <input type="hidden" name="partners[${partnerIndex}][country]" value="${partner.country || ''}">
                <input type="hidden" name="partners[${partnerIndex}][display_name]" value="${partner.display_name || ''}">
                <input type="hidden" name="partners[${partnerIndex}][icon]" value="${partner.icon || 'bi bi-mortarboard-fill'}">
                <input type="hidden" name="partners[${partnerIndex}][color]" value="${partner.color || '#3b82f6'}">
                <input type="hidden" name="partners[${partnerIndex}][badge]" value="${partner.badge || 'University'}">
                <input type="hidden" name="partners[${partnerIndex}][ranking]" value="${partner.ranking || ''}">
                <input type="hidden" name="partners[${partnerIndex}][logo]" value="${partner.logo || ''}">
            </div>
        `;

                partnersContainer.insertAdjacentHTML('beforeend', partnerHtml);
                partnerIndex++;
            }

            // Remove partner
            partnersContainer.addEventListener('click', function(e) {
                if (e.target.closest('.remove-partner')) {
                    if (confirm('Are you sure you want to remove this partner?')) {
                        e.target.closest('.partner-item').remove();
                        updatePartnerIndices();

                        // Show empty state if no partners left
                        if (partnersContainer.children.length === 0) {
                            const emptyState = document.getElementById('emptyState');
                            if (emptyState) {
                                emptyState.style.display = 'block';
                            }
                        }
                    }
                }
            });

            // Drag and drop functionality
            let draggedElement = null;

            partnersContainer.addEventListener('dragstart', function(e) {
                if (e.target.classList.contains('partner-item')) {
                    draggedElement = e.target;
                    e.target.classList.add('dragging');
                }
            });

            partnersContainer.addEventListener('dragend', function(e) {
                if (e.target.classList.contains('partner-item')) {
                    e.target.classList.remove('dragging');
                    draggedElement = null;
                }
            });

            partnersContainer.addEventListener('dragover', function(e) {
                e.preventDefault();
                const afterElement = getDragAfterElement(partnersContainer, e.clientY);
                if (afterElement == null) {
                    partnersContainer.appendChild(draggedElement);
                } else {
                    partnersContainer.insertBefore(draggedElement, afterElement);
                }
            });

            partnersContainer.addEventListener('dragenter', function(e) {
                e.preventDefault();
                if (e.target.classList.contains('partner-item')) {
                    e.target.classList.add('drag-over');
                }
            });

            partnersContainer.addEventListener('dragleave', function(e) {
                if (e.target.classList.contains('partner-item')) {
                    e.target.classList.remove('drag-over');
                }
            });

            function getDragAfterElement(container, y) {
                const draggableElements = [...container.querySelectorAll('.partner-item:not(.dragging)')];

                return draggableElements.reduce((closest, child) => {
                    const box = child.getBoundingClientRect();
                    const offset = y - box.top - box.height / 2;

                    if (offset < 0 && offset > closest.offset) {
                        return {
                            offset: offset,
                            element: child
                        };
                    } else {
                        return closest;
                    }
                }, {
                    offset: Number.NEGATIVE_INFINITY
                }).element;
            }

            function updatePartnerIndices() {
                const partnerItems = partnersContainer.querySelectorAll('.partner-item');
                partnerItems.forEach((item, index) => {
                    item.setAttribute('data-index', index);
                    const inputs = item.querySelectorAll('input[type="hidden"]');
                    inputs.forEach(input => {
                        const name = input.getAttribute('name');
                        const newName = name.replace(/\[\d+\]/, `[${index}]`);
                        input.setAttribute('name', newName);
                    });
                });
            }
        });
    </script>
@endpush
