@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>{{ __('patient-custom-fields.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">{{ __('patient-custom-fields.add_new_field') }}</h5>
                </div>
                <div class="card-body">
                    <form action="{{ route('patient-custom-fields.store') }}" method="POST">
                        @csrf
                        <div class="mb-3">
                            <label for="name" class="form-label">{{ __('patient-custom-fields.field_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="type" class="form-label">{{ __('patient-custom-fields.field_type') }} *</label>
                            <select class="form-select @error('type') is-invalid @enderror" id="type" name="type" required>
                                @foreach($fieldTypes as $value => $label)
                                    <option value="{{ $value }}" {{ old('type') == $value ? 'selected' : '' }}>{{ $label }}</option>
                                @endforeach
                            </select>
                            @error('type')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        
                        <div class="mb-3">
                            <label for="placeholder" class="form-label">{{ __('patient-custom-fields.placeholder') }}</label>
                            <input type="text" class="form-control @error('placeholder') is-invalid @enderror" id="placeholder" name="placeholder" value="{{ old('placeholder') }}">
                            @error('placeholder')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        
                        <div class="mb-3 options-container" style="display: none;">
                            <label for="options" class="form-label">{{ __('patient-custom-fields.options') }} *</label>
                            <textarea class="form-control @error('options') is-invalid @enderror" id="options" name="options" rows="3" placeholder="{{ __('patient-custom-fields.options_help') }}">{{ old('options') }}</textarea>
                            <div class="form-text">{{ __('patient-custom-fields.comma_separated') }}</div>
                            @error('options')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        
                        <div class="mb-3 form-check">
                            <input type="checkbox" class="form-check-input" id="required" name="required" value="1" {{ old('required') ? 'checked' : '' }}>
                            <label class="form-check-label" for="required">{{ __('patient-custom-fields.required_field') }}</label>
                        </div>
                        
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary">{{ __('patient-custom-fields.add_field') }}</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">{{ __('patient-custom-fields.existing_fields') }}</h5>
                </div>
                <div class="card-body">
                    @if($fields->isEmpty())
                        <div class="alert alert-info">
                            {{ __('patient-custom-fields.no_fields') }}
                        </div>
                    @else
                        <div class="table-responsive">
                            <table class="table table-striped" id="fields-table">
                                <thead>
                                    <tr>
                                        <th width="40">#</th>
                                        <th>{{ __('patient-custom-fields.name') }}</th>
                                        <th>{{ __('patient-custom-fields.type') }}</th>
                                        <th>{{ __('patient-custom-fields.required') }}</th>
                                        <th>{{ __('patient-custom-fields.status') }}</th>
                                        <th width="120">{{ __('patient-custom-fields.actions') }}</th>
                                    </tr>
                                </thead>
                                <tbody id="sortable-fields">
                                    @foreach($fields as $field)
                                    <tr data-id="{{ $field->id }}">
                                        <td><i class="bi bi-grip-vertical handle"></i></td>
                                        <td>{{ $field->name }}</td>
                                        <td>{{ $fieldTypes[$field->type] ?? $field->type }}</td>
                                        <td>{!! $field->required ? '<span class="badge bg-primary">Yes</span>' : '<span class="badge bg-secondary">No</span>' !!}</td>
                                        <td>{!! $field->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-field" 
                                                data-id="{{ $field->id }}"
                                                data-name="{{ $field->name }}"
                                                data-type="{{ $field->type }}"
                                                data-placeholder="{{ $field->placeholder }}"
                                                data-required="{{ $field->required }}"
                                                data-active="{{ $field->active }}"
                                                data-options="{{ is_array($field->options) ? implode(', ', $field->options) : '' }}">
                                                <i class="bi bi-pencil-square"></i>
                                            </button>
                                            <form action="{{ route('patient-custom-fields.destroy', $field->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 Field Modal -->
<div class="modal fade" id="editFieldModal" tabindex="-1" aria-labelledby="editFieldModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="edit-field-form" action="" method="POST">
                @csrf
                @method('PUT')
                <div class="modal-header">
                    <h5 class="modal-title" id="editFieldModalLabel">{{ __('patient-custom-fields.edit_field') }}</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">{{ __('patient-custom-fields.field_name') }} *</label>
                        <input type="text" class="form-control" id="edit-name" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit-type" class="form-label">{{ __('patient-custom-fields.field_type') }} *</label>
                        <select class="form-select" id="edit-type" name="type" required>
                            @foreach($fieldTypes as $value => $label)
                                <option value="{{ $value }}">{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit-placeholder" class="form-label">{{ __('patient-custom-fields.placeholder') }}</label>
                        <input type="text" class="form-control" id="edit-placeholder" name="placeholder">
                    </div>
                    
                    <div class="mb-3 edit-options-container" style="display: none;">
                        <label for="edit-options" class="form-label">{{ __('patient-custom-fields.options') }} *</label>
                        <textarea class="form-control" id="edit-options" name="options" rows="3" placeholder="{{ __('patient-custom-fields.options_help') }}"></textarea>
                        <div class="form-text">{{ __('patient-custom-fields.comma_separated') }}</div>
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="edit-required" name="required" value="1">
                        <label class="form-check-label" for="edit-required">{{ __('patient-custom-fields.required_field') }}</label>
                    </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">{{ __('patient-custom-fields.active_field') }}</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('patient-custom-fields.cancel') }}</button>
                    <button type="submit" class="btn btn-primary">{{ __('patient-custom-fields.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() {



        assignActions = function(modal) {
            document.querySelector('#editFieldModal .btn-close').addEventListener('click', function() {
                if (modal) {
                    modal.hide();
                }
            });
            
            document.querySelector('#editFieldModal .btn-secondary').addEventListener('click', function() {
                if (modal) {
                    modal.hide();
                }
            });
        };

        // Show/hide options based on field type
        const typeSelector = document.getElementById('type');
        const optionsContainer = document.querySelector('.options-container');
        
        function toggleOptionsVisibility(type) {
            if (['select', 'radio', 'checkbox'].includes(type)) {
                optionsContainer.style.display = 'block';
            } else {
                optionsContainer.style.display = 'none';
            }
        }
        
        // Initial check
        if (typeSelector) {
            toggleOptionsVisibility(typeSelector.value);
            
            // On change
            typeSelector.addEventListener('change', function() {
                toggleOptionsVisibility(this.value);
            });
        }
        
        // Edit field modal
        const editButtons = document.querySelectorAll('.edit-field');
        const editForm = document.getElementById('edit-field-form');
        const editTypeSelector = document.getElementById('edit-type');
        const editOptionsContainer = document.querySelector('.edit-options-container');
        
        // Add click event to each edit button
        editButtons.forEach(button => {
            button.addEventListener('click', function() {
                const fieldId = this.getAttribute('data-id');
                const fieldName = this.getAttribute('data-name');
                const fieldType = this.getAttribute('data-type');
                const fieldPlaceholder = this.getAttribute('data-placeholder');
                const fieldRequired = this.getAttribute('data-required');
                const fieldActive = this.getAttribute('data-active');
                const fieldOptions = this.getAttribute('data-options');
                
                // Set form action
                editForm.action = `/admin/patient-custom-fields/${fieldId}`;
                
                // Fill form fields
                document.getElementById('edit-name').value = fieldName;
                document.getElementById('edit-type').value = fieldType;
                document.getElementById('edit-placeholder').value = fieldPlaceholder;
                document.getElementById('edit-required').checked = fieldRequired === '1';
                document.getElementById('edit-active').checked = fieldActive === '1';
                document.getElementById('edit-options').value = fieldOptions;
                
                // Show/hide options based on field type
                if (['select', 'radio', 'checkbox'].includes(fieldType)) {
                    editOptionsContainer.style.display = 'block';
                } else {
                    editOptionsContainer.style.display = 'none';
                }
                
                // Show modal
                const modal = new bootstrap.Modal(document.getElementById('editFieldModal'));
                assignActions(modal);
                modal.show();
            });
        });
        
        // Handle edit type change
        if (editTypeSelector) {
            editTypeSelector.addEventListener('change', function() {
                if (['select', 'radio', 'checkbox'].includes(this.value)) {
                    editOptionsContainer.style.display = 'block';
                } else {
                    editOptionsContainer.style.display = 'none';
                }
            });
        }
        
        // Make fields sortable
        const sortableFields = document.getElementById('sortable-fields');
        if (sortableFields) {
            new Sortable(sortableFields, {
                handle: '.handle',
                animation: 150,
                onEnd: function() {
                    // Get new order
                    const rows = sortableFields.querySelectorAll('tr');
                    const order = Array.from(rows).map(row => row.getAttribute('data-id'));
                    
                    // Save new order via AJAX
                    fetch('/admin/patient-custom-fields/order', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        },
                        body: JSON.stringify({ fields: order })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            console.log('Field order updated successfully');
                        }
                    })
                    .catch(error => console.error('Error updating field order:', error));
                }
            });
        }
        
        // Confirm delete
        const deleteForms = document.querySelectorAll('.delete-form');
        deleteForms.forEach(form => {
            form.addEventListener('submit', function(e) {
                if (!confirm("{{ __('patient-custom-fields.confirm_delete') }}")) {
                    e.preventDefault();
                }
            });
        });
    });
        // Add a keyboard event listener to close the modal on escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                const activeModal = document.querySelector('.modal.show');
                if (activeModal) {
                    const modal = bootstrap.Modal.getInstance(activeModal);
                    if (modal) {
                        modal.hide();
                    }
                }
            }
        }); 

</script>
@endpush
@endsection
