@extends('layouts.admin')

@section('title', 'Package Server Management')

@section('content')
<div class="dashboard-container">
    <!-- Header Card -->
    <div class="dashboard-card mb-4">
        <div class="dashboard-card-header">
            <div>
                <h3><i class="fas fa-network-wired"></i> Package Server Assignments</h3>
                <p class="mt-1" style="color: var(--light-gray); font-size: 0.9rem; margin: 0;">Manage which servers each package is available on</p>
            </div>
            <div class="card-actions">
                <a href="{{ route('admin.packages.index') }}" class="btn btn-secondary btn-sm">
                    <i class="fas fa-arrow-left"></i> Back to Packages
                </a>
            </div>
        </div>
    </div>

    <!-- Assignment Grid Card -->
    <div class="dashboard-card dashboard-card-tall">
        <div class="dashboard-card-header">
            <h4><i class="fas fa-table"></i> Server Assignments</h4>
            @if($packages->count() > 0 && $servers->count() > 0)
                <div class="card-actions">
                    <span class="badge bg-primary">{{ $packages->count() }} Packages</span>
                    <span class="badge bg-info">{{ $servers->count() }} Servers</span>
                </div>
            @endif
        </div>
        <div class="dashboard-card-body">
            @if($packages->count() > 0 && $servers->count() > 0)
                <form action="{{ route('admin.packages.servers.update') }}" method="POST" id="package-server-form">
                    @csrf
                    
                    <!-- Assignment Grid -->
                    <div class="server-assignment-grid">
                        <!-- Grid Header -->
                        <div class="grid-header" style="display: grid; grid-template-columns: 1fr repeat({{ $servers->count() }}, 100px);">
                            <div class="package-column">
                                <i class="fas fa-box"></i> Package Details
                            </div>
                            @foreach($servers as $server)
                                <div class="server-column text-center">
                                    <i class="fas fa-server"></i>
                                    <span class="d-block">{{ $server->name }}</span>
                                    <small style="color: var(--light-gray);">{{ $server->short_name ?? substr($server->name, 0, 3) }}</small>
                                </div>
                            @endforeach
                        </div>
                        
                        <!-- Package Rows -->
                        @foreach($packages as $package)
                            <div class="package-row" 
                                 data-type="{{ $package->type }}" 
                                 data-package-id="{{ $package->id }}"
                                 style="display: grid; grid-template-columns: 1fr repeat({{ $servers->count() }}, 100px);">
                                
                                <!-- Package Info -->
                                <div class="package-info">
                                    <div class="d-flex align-items-center mb-2">
                                        @if($package->image)
                                            <img src="{{ asset('storage/' . $package->image) }}" 
                                                 alt="{{ $package->name }}" 
                                                 class="package-thumbnail me-3">
                                        @else
                                            <div class="no-image me-3">
                                                <i class="fas fa-image"></i>
                                            </div>
                                        @endif
                                        <div>
                                            <div class="package-name">{{ $package->name }}</div>
                                            <div class="package-meta">
                                                <span class="package-type">{{ ucfirst($package->type) }}</span>
                                                <span class="package-price">{{ currency_symbol(config_value('store_currency', 'GBP')) }}{{ number_format($package->price, 2) }}</span>
                                            </div>
                                        </div>
                                    </div>
                                    @if($package->description)
                                        <div class="package-description" style="font-size: 0.8rem; color: var(--light-gray);">
                                            {{ Str::limit($package->description, 100) }}
                                        </div>
                                    @endif
                                </div>
                                
                                <!-- Server Checkboxes -->
                                @foreach($servers as $server)
                                    <div class="server-checkbox">
                                        <input type="checkbox" 
                                               name="package_servers[{{ $package->id }}][]" 
                                               value="{{ $server->id }}"
                                               id="package_{{ $package->id }}_server_{{ $server->id }}"
                                               {{ $package->servers->contains($server->id) ? 'checked' : '' }}
                                               data-server-id="{{ $server->id }}"
                                               data-package-id="{{ $package->id }}"
                                               data-package-type="{{ $package->type }}">
                                        <label for="package_{{ $package->id }}_server_{{ $server->id }}" class="sr-only">
                                            Assign {{ $package->name }} to {{ $server->name }}
                                        </label>
                                    </div>
                                @endforeach
                            </div>
                        @endforeach
                    </div>
                    
                    <!-- Form Actions -->
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Assignments
                        </button>
                        <button type="button" class="btn btn-secondary" id="reset-form">
                            <i class="fas fa-undo"></i> Reset Changes
                        </button>
                    </div>
                </form>
            @endif
            
            <!-- Empty States -->
            @if($packages->isEmpty())
                <div class="empty-state">
                    <i class="fas fa-box-open"></i>
                    <h4>No Packages Found</h4>
                    <p>Create some packages first to manage server assignments.</p>
                    <a href="{{ route('admin.packages.create') }}" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Create Package
                    </a>
                </div>
            @elseif($servers->isEmpty())
                <div class="empty-state">
                    <i class="fas fa-server"></i>
                    <h4>No Servers Found</h4>
                    <p>Create some servers first to manage package assignments.</p>
                    <a href="{{ route('admin.servers.create') }}" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Create Server
                    </a>
                </div>
            @endif
        </div>
    </div>
    
    <!-- Quick Actions Card -->
    @if($packages->count() > 0 && $servers->count() > 0)
    <div class="dashboard-card">
        <div class="dashboard-card-header">
            <h4><i class="fas fa-bolt"></i> Quick Actions</h4>
            <small style="color: var(--light-gray);">Bulk select assignments for multiple packages</small>
        </div>
        <div class="dashboard-card-body">
            <!-- Server Selection Actions -->
            <div class="mb-4">
                <h5 class="mb-3">
                    <i class="fas fa-server"></i> Select by Server
                    <small class="ms-2" style="color: var(--light-gray); font-weight: normal;">
                        Assign all packages to specific servers
                    </small>
                </h5>
                <div class="quick-action-buttons">
                    @foreach($servers as $server)
                        <button type="button" 
                                class="btn btn-outline-primary select-all-server" 
                                data-server-id="{{ $server->id }}"
                                title="Select all packages for {{ $server->name }}">
                            <i class="fas fa-check-circle"></i> All for {{ $server->name }}
                        </button>
                    @endforeach
                </div>
            </div>

            <!-- Package Type Selection Actions -->
            <div class="mb-4">
                <h5 class="mb-3">
                    <i class="fas fa-tags"></i> Select by Package Type
                    <small class="ms-2" style="color: var(--light-gray); font-weight: normal;">
                        Select all packages of a specific type
                    </small>
                </h5>
                <div class="quick-action-buttons">
                    @php
                        $packageTypes = $packages->pluck('type')->unique();
                        $typeIcons = [
                            'vip' => 'fas fa-crown',
                            'money' => 'fas fa-dollar-sign',
                            'job' => 'fas fa-briefcase',
                            'vehicle' => 'fas fa-car',
                            'other' => 'fas fa-cube'
                        ];
                    @endphp
                    @foreach($packageTypes as $type)
                        <button type="button" 
                                class="btn btn-outline-secondary select-all-type" 
                                data-type="{{ $type }}"
                                title="Select all {{ ucfirst($type) }} packages">
                            <i class="{{ $typeIcons[$type] ?? 'fas fa-cube' }}"></i> 
                            All {{ ucfirst($type) }} ({{ $packages->where('type', $type)->count() }})
                        </button>
                    @endforeach
                </div>
            </div>

            <!-- Global Actions -->
            <div class="mb-3">
                <h5 class="mb-3">
                    <i class="fas fa-globe"></i> Global Actions
                    <small class="ms-2" style="color: var(--light-gray); font-weight: normal;">
                        Select or deselect all assignments at once
                    </small>
                </h5>
                <div class="quick-action-buttons">
                    <button type="button" class="btn btn-outline-success" id="select-all">
                        <i class="fas fa-check-double"></i> Select All
                    </button>
                    <button type="button" class="btn btn-outline-danger" id="deselect-all">
                        <i class="fas fa-times-circle"></i> Deselect All
                    </button>
                    <button type="button" class="btn btn-outline-info" id="invert-selection">
                        <i class="fas fa-exchange-alt"></i> Invert Selection
                    </button>
                </div>
            </div>

            <!-- Assignment Summary -->
            <div class="mt-4 p-3" style="background-color: rgba(var(--primary-rgb), 0.1); border-radius: var(--border-radius-md);">
                <h6 class="mb-2">
                    <i class="fas fa-chart-bar"></i> Assignment Summary
                </h6>
                <div class="row">
                    <div class="col-md-6">
                        <div class="d-flex justify-content-between">
                            <span>Total Possible Assignments:</span>
                            <strong id="total-assignments">{{ $packages->count() * $servers->count() }}</strong>
                        </div>
                        <div class="d-flex justify-content-between">
                            <span>Current Assignments:</span>
                            <strong id="current-assignments">{{ $packages->sum(function($p) { return $p->servers->count(); }) }}</strong>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex justify-content-between">
                            <span>Selected for Update:</span>
                            <strong id="selected-assignments">0</strong>
                        </div>
                        <div class="d-flex justify-content-between">
                            <span>Coverage:</span>
                            <strong id="coverage-percentage">0%</strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endif
</div>
@endsection


@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('package-server-form');
    const checkboxes = document.querySelectorAll('input[type="checkbox"]');
    const selectedCounter = document.getElementById('selected-assignments');
    const coveragePercentage = document.getElementById('coverage-percentage');
    const totalAssignments = {{ $packages->count() * $servers->count() }};
    
    // Track original state for reset functionality
    const originalState = Array.from(checkboxes).map(cb => cb.checked);
    
    // Update counters
    function updateCounters() {
        const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
        selectedCounter.textContent = selectedCount;
        
        const coverage = totalAssignments > 0 ? ((selectedCount / totalAssignments) * 100).toFixed(1) : 0;
        coveragePercentage.textContent = coverage + '%';
        
        // Update coverage color based on percentage
        if (coverage >= 75) {
            coveragePercentage.style.color = 'var(--success)';
        } else if (coverage >= 50) {
            coveragePercentage.style.color = 'var(--warning)';
        } else {
            coveragePercentage.style.color = 'var(--danger)';
        }
    }
    
    // Initial counter update
    updateCounters();
    
    // Add change listeners to all checkboxes
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateCounters);
    });
    
    // Select all for specific server
    document.querySelectorAll('.select-all-server').forEach(button => {
        button.addEventListener('click', function() {
            const serverId = this.dataset.serverId;
            const serverCheckboxes = document.querySelectorAll(`input[data-server-id="${serverId}"]`);
            serverCheckboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            updateCounters();
            
            // Visual feedback
            this.classList.add('btn-success');
            this.classList.remove('btn-outline-primary');
            setTimeout(() => {
                this.classList.remove('btn-success');
                this.classList.add('btn-outline-primary');
            }, 1000);
        });
    });
    
    // Select all for package type
    document.querySelectorAll('.select-all-type').forEach(button => {
        button.addEventListener('click', function() {
            const type = this.dataset.type;
            const typeCheckboxes = document.querySelectorAll(`input[data-package-type="${type}"]`);
            typeCheckboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            updateCounters();
            
            // Visual feedback
            this.classList.add('btn-success');
            this.classList.remove('btn-outline-secondary');
            setTimeout(() => {
                this.classList.remove('btn-success');
                this.classList.add('btn-outline-secondary');
            }, 1000);
        });
    });
    
    // Select all
    const selectAllBtn = document.getElementById('select-all');
    if (selectAllBtn) {
        selectAllBtn.addEventListener('click', function() {
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            updateCounters();
            
            // Show notification
            showNotification('All assignments selected', 'success');
        });
    }
    
    // Deselect all
    const deselectAllBtn = document.getElementById('deselect-all');
    if (deselectAllBtn) {
        deselectAllBtn.addEventListener('click', function() {
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            updateCounters();
            
            // Show notification
            showNotification('All assignments deselected', 'info');
        });
    }
    
    // Invert selection
    const invertBtn = document.getElementById('invert-selection');
    if (invertBtn) {
        invertBtn.addEventListener('click', function() {
            checkboxes.forEach(checkbox => {
                checkbox.checked = !checkbox.checked;
            });
            updateCounters();
            
            // Show notification
            showNotification('Selection inverted', 'info');
        });
    }
    
    // Reset form
    const resetBtn = document.getElementById('reset-form');
    if (resetBtn) {
        resetBtn.addEventListener('click', function() {
            if (confirm('Are you sure you want to reset all changes?')) {
                checkboxes.forEach((checkbox, index) => {
                    checkbox.checked = originalState[index];
                });
                updateCounters();
                
                // Show notification
                showNotification('Changes reset to original state', 'warning');
            }
        });
    }
    
    // Form validation before submit
    if (form) {
        form.addEventListener('submit', function(e) {
            const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('Please select at least one server assignment before saving.');
                return false;
            }
            
            // Show loading state
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
            submitBtn.disabled = true;
            
            // Restore button after 5 seconds (fallback)
            setTimeout(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }, 5000);
        });
    }
    
    // Utility function for notifications
    function showNotification(message, type = 'info') {
        // Create notification
        const notification = document.createElement('div');
        notification.className = `alert alert-${type}`;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            max-width: 300px;
            opacity: 0;
            transform: translateY(-20px);
            transition: all 0.3s ease;
        `;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // Animate in
        requestAnimationFrame(() => {
            notification.style.opacity = '1';
            notification.style.transform = 'translateY(0)';
        });
        
        // Auto remove after 3 seconds
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateY(-20px)';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }
});
</script>
@endpush