@extends('layouts.yellow')
@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12 p-3">
            <div class="card">
                <div class="card-header">
                    <h2>{{ __('appointment-tags.configuration_title') }}</h2>
                </div>
            </div>
        </div>
    </div>
    
    @if(session('success'))
    <div class="row">
        <div class="col-12">
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
    </div>
    @endif
    
    <div class="row">
        <div class="col-md-5">
            <div class="card shadow-lg rounded-lg border-0 mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">{{ __('appointment-tags.add_new_tag') }}</h5>
                </div>
                <div class="card-body">
                    <form action="{{ route('appointment-tags.store') }}" method="POST">
                        @csrf
                        <div class="mb-3">
                            <label for="name" class="form-label">{{ __('appointment-tags.tag_name') }} *</label>
                            <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" name="name" value="{{ old('name') }}" required>
                            @error('name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        
                        <div class="mb-3">
                            <label for="color" class="form-label">{{ __('appointment-tags.tag_color') }} *</label>
                            <input type="color" class="form-control form-control-color @error('color') is-invalid @enderror" id="color" name="color" value="{{ old('color', '#3498db') }}">
                            @error('color')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        
                        <div class="mb-3 form-check">
                            <input type="checkbox" class="form-check-input" id="active" name="active" value="1" {{ old('active') ? 'checked' : '' }}>
                            <label class="form-check-label" for="active">{{ __('appointment-tags.active_tag') }}</label>
                        </div>
                        
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary">{{ __('appointment-tags.add_tag') }}</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-md-7">
            <div class="card shadow-lg rounded-lg border-0">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">{{ __('appointment-tags.existing_tags') }}</h5>
                </div>
                <div class="card-body">
                    @if($tags->isEmpty())
                        <div class="alert alert-info">
                            {{ __('appointment-tags.no_tags') }}
                        </div>
                    @else
                        <div class="table-responsive">
                            <table class="table table-striped" id="tags-table">
                                <thead>
                                    <tr>
                                        <th width="40">#</th>
                                        <th>{{ __('appointment-tags.name') }}</th>
                                        <th>{{ __('appointment-tags.color') }}</th>
                                        <th>{{ __('appointment-tags.status') }}</th>
                                        <th width="120">{{ __('appointment-tags.actions') }}</th>
                                    </tr>
                                </thead>
                                <tbody id="sortable-tags">
                                    @foreach($tags as $tag)
                                    <tr data-id="{{ $tag->id }}">
                                        <td><i class="bi bi-grip-vertical handle"></i></td>
                                        <td>{{ $tag->name }}</td>
                                        <td>
                                            <span class="color-preview" style="background-color: {{ $tag->color }}; display: inline-block; width: 24px; height: 24px; border-radius: 4px;"></span>
                                            <span class="ms-2">{{ $tag->color }}</span>
                                        </td>
                                        <td>{!! $tag->active ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">Inactive</span>' !!}</td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-primary edit-tag" 
                                                data-id="{{ $tag->id }}"
                                                data-name="{{ $tag->name }}"
                                                data-color="{{ $tag->color }}"
                                                data-active="{{ $tag->active }}">
                                                <i class="bi bi-pencil-square"></i>
                                            </button>
                                            <form action="{{ route('appointment-tags.destroy', $tag->id) }}" method="POST" class="d-inline delete-form">
                                                @csrf
                                                @method('DELETE')
                                                <button type="submit" class="btn btn-sm btn-danger">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Tag Modal -->
<div class="modal fade" id="editTagModal" tabindex="-1" aria-labelledby="editTagModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="edit-tag-form" action="" method="POST">
                @csrf
                @method('PUT')
                <div class="modal-header">
                    <h5 class="modal-title" id="editTagModalLabel">{{ __('appointment-tags.edit_tag') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="edit-name" class="form-label">{{ __('appointment-tags.tag_name') }} *</label>
                        <input type="text" class="form-control" id="edit-name" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit-color" class="form-label">{{ __('appointment-tags.tag_color') }} *</label>
                        <input type="color" class="form-control form-control-color" id="edit-color" name="color">
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="edit-active" name="active" value="1">
                        <label class="form-check-label" for="edit-active">{{ __('appointment-tags.active_tag') }}</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('appointment-tags.cancel') }}</button>
                    <button type="submit" class="btn btn-primary">{{ __('appointment-tags.save_changes') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Edit tag modal
        const editButtons = document.querySelectorAll('.edit-tag');
        const editForm = document.getElementById('edit-tag-form');
        
        // Ensure modal closing works
        function assignActions(modal) {
            document.querySelector('#editTagModal .btn-close').addEventListener('click', function() {
                if (modal) {
                    modal.hide();
                }
            });
            
            document.querySelector('#editTagModal .btn-secondary').addEventListener('click', function() {
                if (modal) {
                    modal.hide();
                }
            });
        };
        
        // Add click event to each edit button
        editButtons.forEach(button => {
            button.addEventListener('click', function() {
                const tagId = this.getAttribute('data-id');
                const tagName = this.getAttribute('data-name');
                const tagColor = this.getAttribute('data-color');
                const tagActive = this.getAttribute('data-active');
                
                // Set form action
                editForm.action = `/admin/appointment-tags/${tagId}`;
                
                // Fill form fields
                document.getElementById('edit-name').value = tagName;
                document.getElementById('edit-color').value = tagColor;
                document.getElementById('edit-active').checked = tagActive === '1';
                
                // Show modal
                const modal = new bootstrap.Modal(document.getElementById('editTagModal'));
                assignActions(modal);
                modal.show();
            });
        });
        
        // Make tags sortable
        const sortableTags = document.getElementById('sortable-tags');
        if (sortableTags) {
            new Sortable(sortableTags, {
                handle: '.handle',
                animation: 150,
                onEnd: function() {
                    // Get new order
                    const rows = sortableTags.querySelectorAll('tr');
                    const order = Array.from(rows).map(row => row.getAttribute('data-id'));
                    
                    // Save new order via AJAX
                    fetch('/admin/appointment-tags/order', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        },
                        body: JSON.stringify({ tags: order })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            console.log('Tag order updated successfully');
                        }
                    })
                    .catch(error => console.error('Error updating tag order:', error));
                }
            });
        }
        
        // Confirm delete
        const deleteForms = document.querySelectorAll('.delete-form');
        deleteForms.forEach(form => {
            form.addEventListener('submit', function(e) {
                if (!confirm("{{ __('appointment-tags.confirm_delete') }}")) {
                    e.preventDefault();
                }
            });
        });
    });
</script>
@endpush
@endsection
