@extends('admin.layouts.app')

@section('title', 'Edit Why Select LECL')

@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 Why Select LECL</h1>
                    <a href="{{ route('admin.why-lecl.index') }}" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </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 (session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                @endif

                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form id="whyLeclForm" action="{{ route('admin.why-lecl.update') }}" method="POST">
                    @csrf
                    @method('PUT')

                    <!-- Section Information -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Section Information</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="title" class="form-label">Section Title <span
                                                class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="title" name="title"
                                            value="{{ old('title', $whyLeclSection->title ?? 'Why Select LECL?') }}" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="content" class="form-label">Section Description <span
                                                class="text-danger">*</span></label>
                                        <textarea class="form-control" id="content" name="content" rows="3" required>{{ old('content', $whyLeclSection->content ?? 'Countless Benefits & Easy Processing') }}</textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Benefits Management -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3 d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">Manage Benefits</h6>
                            <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal"
                                data-bs-target="#addBenefitModal">
                                <i class="fas fa-plus"></i> Add Benefit
                            </button>
                        </div>
                        <div class="card-body">
                            <div id="benefitsContainer">
                                @if ($whyLeclSection && $whyLeclSection->data && isset($whyLeclSection->data['benefits']))
                                    @foreach ($whyLeclSection->data['benefits'] as $index => $benefit)
                                        <div class="benefit-item border rounded p-3 mb-3"
                                            data-index="{{ $index }}">
                                            <div class="row align-items-center">
                                                <div class="col-md-8">
                                                    <div class="d-flex align-items-center">
                                                        <div class="rounded-circle d-inline-flex align-items-center justify-content-center me-3"
                                                            style="width: 40px; height: 40px; background: {{ $benefit['color'] ?? 'var(--primary-navy)' }};">
                                                            <i class="{{ $benefit['icon'] ?? 'bi bi-star' }} text-white"></i>
                                                        </div>
                                                        <div>
                                                            <h6 class="mb-1 text-primary">{{ $benefit['title'] }}</h6>
                                                            <p class="mb-0 text-muted small">{{ $benefit['description'] }}</p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-4 text-end">
                                                    <button type="button" class="btn btn-sm btn-outline-danger remove-benefit"
                                                        data-index="{{ $index }}">
                                                        <i class="fas fa-trash"></i> Remove
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                @else
                                    <div class="text-center py-4" id="noBenefitsMessage">
                                        <i class="fas fa-list fa-3x text-muted mb-3"></i>
                                        <h5 class="text-muted">No Benefits Added</h5>
                                        <p class="text-muted">Click "Add Benefit" to start adding benefits.</p>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>

                    <!-- Save Button -->
                    <div class="card shadow">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <a href="{{ route('admin.why-lecl.index') }}" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> Cancel
                                </a>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Save Changes
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Benefit Modal -->
    <div class="modal fade" id="addBenefitModal" tabindex="-1" aria-labelledby="addBenefitModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addBenefitModalLabel">Add New Benefit</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addBenefitForm">
                    @csrf
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="benefitTitle" class="form-label">Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="benefitTitle" name="title" required>
                        </div>
                        <div class="mb-3">
                            <label for="benefitDescription" class="form-label">Description <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="benefitDescription" name="description" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="benefitIcon" class="form-label">Icon Class <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="benefitIcon" name="icon" 
                                placeholder="e.g., bi bi-shield-check, fas fa-star" required>
                            <small class="form-text text-muted">Use Bootstrap Icons (bi bi-*) or Font Awesome (fas fa-*) classes</small>
                        </div>
                        <div class="mb-3">
                            <label for="benefitColor" class="form-label">Background Color</label>
                            <select class="form-control" id="benefitColor" name="color">
                                <option value="var(--primary-navy)">Navy Blue (Default)</option>
                                <option value="var(--primary-blue)">Primary Blue</option>
                                <option value="var(--accent-gold)">Gold</option>
                                <option value="#28a745">Green</option>
                                <option value="#dc3545">Red</option>
                                <option value="#6f42c1">Purple</option>
                                <option value="#fd7e14">Orange</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Add Benefit
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const addBenefitForm = document.getElementById('addBenefitForm');
            const benefitsContainer = document.getElementById('benefitsContainer');
            const noBenefitsMessage = document.getElementById('noBenefitsMessage');

            // Add benefit
            addBenefitForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                
                fetch('{{ route('admin.why-lecl.add-benefit') }}', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Hide no benefits message
                        if (noBenefitsMessage) {
                            noBenefitsMessage.style.display = 'none';
                        }
                        
                        // Add new benefit to the list
                        const benefitIndex = document.querySelectorAll('.benefit-item').length;
                        const benefitHtml = `
                            <div class="benefit-item border rounded p-3 mb-3" data-index="${benefitIndex}">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <div class="d-flex align-items-center">
                                            <div class="rounded-circle d-inline-flex align-items-center justify-content-center me-3"
                                                style="width: 40px; height: 40px; background: ${data.benefit.color};">
                                                <i class="${data.benefit.icon} text-white"></i>
                                            </div>
                                            <div>
                                                <h6 class="mb-1 text-primary">${data.benefit.title}</h6>
                                                <p class="mb-0 text-muted small">${data.benefit.description}</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 text-end">
                                        <button type="button" class="btn btn-sm btn-outline-danger remove-benefit"
                                            data-index="${benefitIndex}">
                                            <i class="fas fa-trash"></i> Remove
                                        </button>
                                    </div>
                                </div>
                            </div>
                        `;
                        
                        benefitsContainer.insertAdjacentHTML('beforeend', benefitHtml);
                        
                        // Reset form and close modal
                        addBenefitForm.reset();
                        bootstrap.Modal.getInstance(document.getElementById('addBenefitModal')).hide();
                        
                        // Show success message
                        showAlert('success', data.message);
                    } else {
                        showAlert('danger', data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('danger', 'An error occurred while adding the benefit.');
                });
            });

            // Remove benefit
            benefitsContainer.addEventListener('click', function(e) {
                if (e.target.closest('.remove-benefit')) {
                    const button = e.target.closest('.remove-benefit');
                    const index = button.getAttribute('data-index');
                    const benefitItem = button.closest('.benefit-item');
                    
                    if (confirm('Are you sure you want to remove this benefit?')) {
                        fetch('{{ route('admin.why-lecl.remove-benefit') }}', {
                            method: 'DELETE',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({ index: parseInt(index) })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                benefitItem.remove();
                                
                                // Update indices
                                document.querySelectorAll('.benefit-item').forEach((item, newIndex) => {
                                    item.setAttribute('data-index', newIndex);
                                    const removeBtn = item.querySelector('.remove-benefit');
                                    if (removeBtn) {
                                        removeBtn.setAttribute('data-index', newIndex);
                                    }
                                });
                                
                                // Show no benefits message if no benefits left
                                if (document.querySelectorAll('.benefit-item').length === 0 && noBenefitsMessage) {
                                    noBenefitsMessage.style.display = 'block';
                                }
                                
                                showAlert('success', data.message);
                            } else {
                                showAlert('danger', data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            showAlert('danger', 'An error occurred while removing the benefit.');
                        });
                    }
                }
            });

            function showAlert(type, message) {
                const alertHtml = `
                    <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                        ${message}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                `;
                
                const container = document.querySelector('.container-fluid .row .col-12');
                const firstCard = container.querySelector('.card');
                firstCard.insertAdjacentHTML('beforebegin', alertHtml);
                
                // Auto-dismiss after 5 seconds
                setTimeout(() => {
                    const alert = container.querySelector('.alert');
                    if (alert) {
                        bootstrap.Alert.getInstance(alert).close();
                    }
                }, 5000);
            }
        });
    </script>
@endsection