@extends('admin.layouts.app')

@section('title', 'Edit Impact Numbers Section')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0">Edit Impact Numbers Section</h1>
    <a href="{{ route('admin.impact-numbers.index') }}" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-2"></i>Back to Overview
    </a>
</div>

@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        {{ session('success') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
@endif

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

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Section Settings</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="{{ route('admin.impact-numbers.update') }}">
                    @csrf
                    @method('PUT')
                    
                    <div class="row">
                        <div class="col-md-8">
                            <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', $impactSection->title ?? '') }}" required>
                                <div class="form-text">This will be displayed as the main heading of the section</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="is_active" class="form-label">Status</label>
                                <select class="form-select" id="is_active" name="is_active">
                                    <option value="1" {{ old('is_active', $impactSection->is_active ?? 1) == 1 ? 'selected' : '' }}>Active</option>
                                    <option value="0" {{ old('is_active', $impactSection->is_active ?? 1) == 0 ? 'selected' : '' }}>Inactive</option>
                                </select>
                            </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="Optional description or subtitle for the section">{{ old('content', $impactSection->content ?? '') }}</textarea>
                        <div class="form-text">This will appear below the title (optional)</div>
                    </div>
                    
                    <hr class="my-4">
                    
                    <h6 class="mb-3">Statistics Management</h6>
                    <div id="statistics-container" class="sortable-container">
                        @if($impactSection && isset($impactSection->data['statistics']))
                            @foreach($impactSection->data['statistics'] as $index => $statistic)
                                <div class="statistic-item border rounded p-3 mb-3" data-index="{{ $index }}" draggable="true">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <div class="d-flex align-items-center">
                                            <i class="bi bi-grip-vertical text-muted me-2 drag-handle" style="cursor: move;"></i>
                                            <h6 class="mb-0">Statistic #{{ $index + 1 }}</h6>
                                        </div>
                                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeStatisticItem(this)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-3">
                                            <label class="form-label">Number/Value *</label>
                                            <input type="text" class="form-control" name="statistics[{{ $index }}][number]" 
                                                   value="{{ $statistic['number'] }}" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Label *</label>
                                            <input type="text" class="form-control" name="statistics[{{ $index }}][label]" 
                                                   value="{{ $statistic['label'] }}" required>
                                        </div>
                                        <div class="col-md-5">
                                            <label class="form-label">Description</label>
                                            <input type="text" class="form-control" name="statistics[{{ $index }}][description]" 
                                                   value="{{ $statistic['description'] ?? '' }}">
                                        </div>
                                    </div>
                                    
                                    <div class="row mt-2">
                                        <div class="col-md-6">
                                            <label class="form-label">Icon Class</label>
                                            <input type="text" class="form-control" name="statistics[{{ $index }}][icon]" 
                                                   value="{{ $statistic['icon'] ?? 'bi bi-building-check' }}">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Color</label>
                                            <input type="color" class="form-control form-control-color" name="statistics[{{ $index }}][color]" 
                                                   value="{{ $statistic['color'] ?? '#D4AF37' }}">
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        @endif
                    </div>
                    
                    <div class="mb-3">
                        <button type="button" class="btn btn-outline-success" onclick="addStatisticItem()">
                            <i class="bi bi-plus-circle me-2"></i>Add New Statistic
                        </button>
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <a href="{{ route('admin.impact-numbers.index') }}" class="btn btn-outline-secondary">
                            Cancel
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle me-2"></i>Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
let statisticIndex = {{ $impactSection && isset($impactSection->data['statistics']) ? count($impactSection->data['statistics']) : 0 }};

function addStatisticItem() {
    const container = document.getElementById('statistics-container');
    const newItem = document.createElement('div');
    newItem.className = 'statistic-item border rounded p-3 mb-3';
    newItem.setAttribute('data-index', statisticIndex);
    newItem.setAttribute('draggable', 'true');
    
    newItem.innerHTML = `
        <div class="d-flex justify-content-between align-items-start mb-2">
            <div class="d-flex align-items-center">
                <i class="bi bi-grip-vertical text-muted me-2 drag-handle" style="cursor: move;"></i>
                <h6 class="mb-0">Statistic #${statisticIndex + 1}</h6>
            </div>
            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeStatisticItem(this)">
                <i class="bi bi-trash"></i>
            </button>
        </div>
        
        <div class="row">
            <div class="col-md-3">
                <label class="form-label">Number/Value *</label>
                <input type="text" class="form-control" name="statistics[${statisticIndex}][number]" required>
            </div>
            <div class="col-md-4">
                <label class="form-label">Label *</label>
                <input type="text" class="form-control" name="statistics[${statisticIndex}][label]" required>
            </div>
            <div class="col-md-5">
                <label class="form-label">Description</label>
                <input type="text" class="form-control" name="statistics[${statisticIndex}][description]">
            </div>
        </div>
        
        <div class="row mt-2">
            <div class="col-md-6">
                <label class="form-label">Icon Class</label>
                <input type="text" class="form-control" name="statistics[${statisticIndex}][icon]" value="bi bi-building-check">
            </div>
            <div class="col-md-6">
                <label class="form-label">Color</label>
                <input type="color" class="form-control form-control-color" name="statistics[${statisticIndex}][color]" value="#D4AF37">
            </div>
        </div>
    `;
    
    container.appendChild(newItem);
    statisticIndex++;
    updateStatisticNumbers();
}

function removeStatisticItem(button) {
    if (confirm('Are you sure you want to remove this statistic?')) {
        button.closest('.statistic-item').remove();
        updateStatisticNumbers();
    }
}

function updateStatisticNumbers() {
    const items = document.querySelectorAll('.statistic-item');
    items.forEach((item, index) => {
        const title = item.querySelector('h6');
        title.textContent = `Statistic #${index + 1}`;
        
        // Update input names to maintain proper indexing
        const inputs = item.querySelectorAll('input');
        inputs.forEach(input => {
            const name = input.getAttribute('name');
            if (name) {
                const newName = name.replace(/\[\d+\]/, `[${index}]`);
                input.setAttribute('name', newName);
            }
        });
    });
}

// Drag and Drop Functionality
let draggedElement = null;

document.addEventListener('DOMContentLoaded', function() {
    const container = document.getElementById('statistics-container');
    
    container.addEventListener('dragstart', function(e) {
        if (e.target.classList.contains('statistic-item')) {
            draggedElement = e.target;
            e.target.style.opacity = '0.5';
        }
    });
    
    container.addEventListener('dragend', function(e) {
        if (e.target.classList.contains('statistic-item')) {
            e.target.style.opacity = '1';
            draggedElement = null;
        }
    });
    
    container.addEventListener('dragover', function(e) {
        e.preventDefault();
    });
    
    container.addEventListener('drop', function(e) {
        e.preventDefault();
        
        if (draggedElement && e.target !== draggedElement) {
            const targetItem = e.target.closest('.statistic-item');
            
            if (targetItem && targetItem !== draggedElement) {
                const rect = targetItem.getBoundingClientRect();
                const midpoint = rect.top + rect.height / 2;
                
                if (e.clientY < midpoint) {
                    container.insertBefore(draggedElement, targetItem);
                } else {
                    container.insertBefore(draggedElement, targetItem.nextSibling);
                }
                
                updateStatisticNumbers();
            }
        }
    });
    
    // Add visual feedback during drag
    container.addEventListener('dragenter', function(e) {
        if (e.target.classList.contains('statistic-item') && e.target !== draggedElement) {
            e.target.style.borderColor = '#007bff';
            e.target.style.backgroundColor = '#f8f9fa';
        }
    });
    
    container.addEventListener('dragleave', function(e) {
        if (e.target.classList.contains('statistic-item')) {
            e.target.style.borderColor = '';
            e.target.style.backgroundColor = '';
        }
    });
});
</script>

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

.statistic-item {
    transition: all 0.3s ease;
    cursor: default;
}

.statistic-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.statistic-item.dragging {
    opacity: 0.5;
    transform: rotate(2deg);
}

.drag-handle:hover {
    color: #007bff !important;
}

.drop-zone {
    border: 2px dashed #007bff;
    background-color: #f8f9fa;
    min-height: 60px;
    margin: 10px 0;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #6c757d;
}
</style>
@endsection