@extends('layouts.admin')
@section('header', 'Create Service')
@section('content')
<div class="sm:flex sm:items-center sm:justify-between mb-8">
    <div>
        <h1 class="text-2xl font-bold text-gray-900">Create New Service</h1>
        <p class="mt-2 text-sm text-gray-700">Add a new service to display on the website.</p>
    </div>
</div>

<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
    <form action="{{ route('admin.services.store') }}" method="POST" enctype="multipart/form-data" class="p-6 sm:p-8">
        @csrf
        
        <h4 class="text-md font-bold text-gray-800 mb-6 pb-2 border-b border-gray-200">Service Details</h4>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Title</label>
                <input type="text" name="title" value="{{ old('title') }}" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border-gray-300 rounded-md" required>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Slug (Optional)</label>
                <input type="text" name="slug" value="{{ old('slug') }}" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border-gray-300 rounded-md">
            </div>
            
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">Short Description</label>
                <textarea name="description" rows="2" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border border-gray-300 rounded-md p-2" required>{{ old('description') }}</textarea>
            </div>
            
            <div class="md:col-span-2 mt-4">
                <h4 class="text-md font-bold text-gray-800 mb-4 pb-2 border-b border-gray-200">Detailed Information</h4>
            </div>

            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">Overview</label>
                <textarea name="overview" rows="4" class="rich-text shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border border-gray-300 rounded-md p-2">{{ old('overview') }}</textarea>
            </div>
            
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">What to Expect</label>
                <textarea name="what_to_expect" rows="3" class="rich-text shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border border-gray-300 rounded-md p-2">{{ old('what_to_expect') }}</textarea>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Recovery Time</label>
                <input type="text" name="recovery" value="{{ old('recovery') }}" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border-gray-300 rounded-md">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Image (Upload or URL)</label>
                <input type="file" name="image_upload" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border-gray-300 rounded-md file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-teal-50 file:text-teal-700 hover:file:bg-teal-100 mb-2">
                <input type="text" name="image" value="{{ old('image') }}" placeholder="Or enter Image URL" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border-gray-300 rounded-md">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Order Index</label>
                <input type="number" name="order_index" value="{{ old('order_index', 0) }}" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border-gray-300 rounded-md">
            </div>

            <!-- FAQs Section -->
            <div class="md:col-span-2 mt-4">
                <div class="flex justify-between items-center mb-4 pb-2 border-b border-gray-200">
                    <h4 class="text-md font-bold text-gray-800">Frequently Asked Questions (FAQs)</h4>
                    <button type="button" id="add-faq-btn" class="bg-blue-600 text-white px-3 py-1.5 rounded-md hover:bg-blue-700 focus:outline-none text-sm font-medium">Add FAQ Row</button>
                </div>
                
                <div id="faq-container" class="space-y-4">
                    @if(old('faqs'))
                        @foreach(old('faqs') as $index => $faq)
                        <div class="faq-row bg-gray-50 p-4 rounded-md border border-gray-200 relative">
                            <button type="button" class="remove-faq-btn absolute top-2 right-2 text-red-500 hover:text-red-700" title="Remove FAQ">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                            </button>
                            <div class="mb-3 pr-8">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Question</label>
                                <input type="text" name="faqs[{{ $index }}][question]" value="{{ $faq['question'] ?? '' }}" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border-gray-300 rounded-md" required>
                            </div>
                            <div class="pr-8">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Answer</label>
                                <textarea name="faqs[{{ $index }}][answer]" rows="2" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border border-gray-300 rounded-md p-2" required>{{ $faq['answer'] ?? '' }}</textarea>
                            </div>
                        </div>
                        @endforeach
                    @endif
                </div>
            </div>
        </div>
        
        <div class="mt-8 pt-5 border-t border-gray-200 flex justify-end">
            <a href="{{ route('admin.services.index') }}" class="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-teal-500 mr-3">Cancel</a>
            <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-teal-600 hover:bg-teal-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-teal-500">Save Service</button>
        </div>
    </form>
</div>

<!-- Template for FAQ Row -->
<template id="faq-template">
    <div class="faq-row bg-gray-50 p-4 rounded-md border border-gray-200 relative">
        <button type="button" class="remove-faq-btn absolute top-2 right-2 text-red-500 hover:text-red-700" title="Remove FAQ">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
        </button>
        <div class="mb-3 pr-8">
            <label class="block text-sm font-medium text-gray-700 mb-1">Question</label>
            <input type="text" name="faqs[__INDEX__][question]" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border-gray-300 rounded-md" required>
        </div>
        <div class="pr-8">
            <label class="block text-sm font-medium text-gray-700 mb-1">Answer</label>
            <textarea name="faqs[__INDEX__][answer]" rows="2" class="shadow-sm focus:ring-teal-500 focus:border-teal-500 block w-full sm:text-sm border border-gray-300 rounded-md p-2" required></textarea>
        </div>
    </div>
</template>

@push('scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.3/tinymce.min.js"></script>
<script>
    tinymce.init({
        selector: 'textarea.rich-text',
        plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table code help wordcount autosave',
        toolbar: 'blocks | bold italic | bullist numlist | blockquote | alignleft aligncenter alignright | link image media | fullscreen',
        height: 500,
        menubar: false,
        branding: false,
        statusbar: true,
        image_title: true,
        automatic_uploads: true,
        image_advtab: true,
        image_caption: true,
        relative_urls: false,
        content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:16px; } img { max-width: 100%; height: auto; }',
        images_upload_handler: function (blobInfo, progress) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', '{{ route('admin.upload.image') }}');
                xhr.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').getAttribute('content'));
                xhr.onload = function() {
                    try {
                        if (xhr.status === 422) {
                            const json = JSON.parse(xhr.responseText);
                            let errMsg = 'Validation failed.';
                            if (json.errors && json.errors.file) {
                                errMsg = json.errors.file[0];
                            }
                            alert("Upload Error: " + errMsg);
                            reject(errMsg);
                            return;
                        }
                        if (xhr.status !== 200) {
                            let errMsg = 'HTTP Error: ' + xhr.status;
                            alert("Upload Error: " + errMsg);
                            reject(errMsg);
                            return;
                        }
                        const json = JSON.parse(xhr.responseText);
                        if (!json || typeof json.location != 'string') {
                            let errMsg = 'Invalid JSON: ' + xhr.responseText;
                            alert("Upload Error: " + errMsg);
                            reject(errMsg);
                            return;
                        }
                        resolve(json.location);
                    } catch (err) {
                        alert("Upload crashed: " + err.message + "\nResponse: " + xhr.responseText.substring(0, 100));
                        reject("Upload crashed: " + err.message);
                    }
                };
                const formData = new FormData();
                formData.append('file', blobInfo.blob(), blobInfo.filename());
                xhr.send(formData);
            });
        }
    });

    document.addEventListener('DOMContentLoaded', function() {
        const container = document.getElementById('faq-container');
        const template = document.getElementById('faq-template');
        const addBtn = document.getElementById('add-faq-btn');
        let faqIndex = document.querySelectorAll('.faq-row').length;

        if(addBtn && container && template) {
            addBtn.addEventListener('click', function() {
                const newRow = template.innerHTML.replace(/__INDEX__/g, faqIndex);
                container.insertAdjacentHTML('beforeend', newRow);
                faqIndex++;
            });

            container.addEventListener('click', function(e) {
                const removeBtn = e.target.closest('.remove-faq-btn');
                if (removeBtn) {
                    removeBtn.closest('.faq-row').remove();
                }
            });
        }
    });
</script>
@endpush
@endsection
