@extends('admin.layouts.main')
@section('section')
    <!-- Page sidebar end-->
    <style>
        .ck.ck-editor {
            width: 100%;
        }

        .ck-editor__editable {
            min-height: 320px;
        }
    </style>

    <div class="page-body">
        <div class="container-fluid">
            <div class="row page-title">
                <div class="col-sm-6">
                    <h3>{{ $title }}</h3>
                </div>
                <div class="col-sm-6">
                    <nav>
                        <ol class="breadcrumb justify-content-sm-end align-items-center">
                            <li class="breadcrumb-item"> <a href="{{ route('dashboard') }}">
                                    <svg class="svg-color">
                                        <use href="{{ asset('assets/svg/iconly-sprite.svg#Home') }}"></use>
                                    </svg></a></li>
                            <li class="breadcrumb-item">Category</li>

                            <li class="breadcrumb-item ">Title List</li>
                            <li class="breadcrumb-item active">{{ $title }}</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
        <!-- Container-fluid starts-->
        <div class="container-fluid">
            <div class="row">
                <div class="col-sm-12">
                    <div class="card">
                        <div class="card-body">
                            <!-- Display Validation Errors -->
                            @if ($errors->any())
                                <div class="alert alert-danger">
                                    <ul>
                                        @foreach ($errors->all() as $error)
                                            <li>{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                            @endif
                            <!-- Blade Form (edit.blade.php) -->
                            <form method="POST" action="{{ route('update.post', $post->id) }}"
                                enctype="multipart/form-data">
                                @csrf
                                @method('PUT')

                                <div class="row">

                                    <!-- Category -->
                                    <div class="col-md-6 mb-3">
                                        <label for="category_id">Category <span class="text-danger">*</span></label>
                                        <select name="category_id" class="form-control" required>
                                            @foreach ($categories as $category)
                                                <option value="{{ $category->id }}"
                                                    {{ $category->id == old('category_id', $post->category_id) ? 'selected' : '' }}>
                                                    {{ $category->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>

                                    <!-- Title -->
                                    <div class="col-md-6 mb-3">
                                        <label for="title">Title <span class="text-danger">*</span></label>
                                        <input type="text" name="title" class="form-control"
                                            value="{{ old('title', $post->title) }}" required />
                                    </div>

                                    <!-- Slug -->
                                    <div class="col-md-12 mb-3">
                                        <label>Slug</label>
                                        <input type="text" name="slug" class="form-control"
                                            value="{{ old('slug', $post->slug) }}" required />
                                    </div>


                                    <!-- Image Upload & Preview -->
                                    <div class="col-md-6 mb-3">
                                        <label>Image</label>
                                        <input type="file" name="post_image" class="form-control"
                                            onchange="previewImage(event)" />
                                        @if ($post->post_image)
                                            <img id="imagePreview" src="{{ asset($post->post_image) }}"
                                                style="max-width:150px; margin-top:10px;" />
                                        @else
                                            <img id="imagePreview"
                                                style="display:none; max-width:150px; margin-top:10px;" />
                                        @endif
                                    </div>

                                    {{-- tag here --}}
                                    <div class="col-md-6 mb-3">
                                        <label for="tag_id">Tags</label>
                                        <select class="form-select @error('tag_id') is-invalid @enderror" name="tag_id[]"
                                            id="tag_id" multiple>
                                            @foreach ($tags as $tag)
                                                <option value="{{ $tag->id }}"
                                                    {{ in_array($tag->id, old('tag_id', $post->tags->pluck('id')->toArray())) ? 'selected' : '' }}>
                                                    {{ $tag->name }}
                                                </option>
                                            @endforeach
                                            <option value="other"
                                                {{ in_array('other', old('tag_id', [])) ? 'selected' : '' }}>Other</option>
                                        </select>
                                        @error('tag_id')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror

                                        <div id="manual_tag_container" class="mt-2" style="display: none;">
                                            <div class="input-group">
                                                <input type="text" class="form-control" id="manual_tag_input"
                                                    placeholder="Enter new tag">
                                                <button type="button" class="btn btn-outline-primary"
                                                    id="add_tag_button">Add</button>
                                            </div>
                                        </div>
                                        @error('tag_id')
                                            <p class="invalid-feedback">{{ $message }}</p>
                                        @enderror
                                    </div>

                                    <!-- Content -->
                                    <div class="col-md-12 mb-3">
                                        <label for="editor">Content</label>
                                        <textarea name="content" class="form-control" rows="7" id="editor" required>{{ old('content', $post->content) }}</textarea>
                                    </div>


                                    {{-- meta title keywords description --}}
                                    <div class="col-md-4 mb-3">
                                        <label for="meta_title">Meta Title</label>
                                        <input type="text" class="form-control" name="meta_title"
                                            placeholder="Enter meta title"
                                            value="{{ old('meta_title', $post->meta_title) }}">
                                    </div>
                                    <!-- Meta Keywords -->
                                    <div class="col-md-8 mb-3">
                                        <label>Meta Keywords</label>
                                        <input type="text" name="meta_keywords" class="form-control"
                                            value="{{ old('meta_keywords', $post->meta_keywords) }}" />
                                    </div>

                                    <!-- Meta Description -->
                                    <div class="col-md-12 mb-3">
                                        <label>Meta Description</label>
                                        <textarea name="meta_description" class="form-control">{{ old('meta_description', $post->meta_description) }}</textarea>
                                    </div>

                                    <!-- Publish Date -->
                                    <div class="col-md-5 mb-3">
                                        <label>Publish Date</label>
                                        <input type="date" name="published_at" class="form-control"
                                            value="{{ old('published_at', optional($post->published_at)->format('Y-m-d')) }}">

                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="is_featured">Is Featured</label>
                                        <select class="form-select" name="is_featured">
                                            <option value="1"
                                                {{ old('is_featured', $post->is_featured) == '1' ? 'selected' : '' }}>
                                                Yes</option>
                                            <option value="0"
                                                {{ old('is_featured', $post->is_featured) == '0' ? 'selected' : '' }}>
                                                No</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label for="status">Status</label>
                                        <select class="form-select" name="status">
                                            <option value="1"
                                                {{ old('status', $post->status) == '1' ? 'selected' : '' }}>
                                                Published</option>
                                            <option value="0"
                                                {{ old('status', $post->status) == '0' ? 'selected' : '' }}>
                                                Draft</option>
                                        </select>
                                    </div>


                                    <!-- Submit Button -->
                                    <div class="col-md-12 mb-3">
                                        <button type="submit" class="btn btn-primary">Update Post</button>
                                    </div>
                                </div>
                            </form>


                            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                            <script>
                                function previewImage(event) {
                                    const reader = new FileReader();
                                    reader.onload = function() {
                                        const output = document.getElementById('imagePreview');
                                        output.src = reader.result;
                                        output.style.display = 'block';
                                    };
                                    reader.readAsDataURL(event.target.files[0]);
                                }
                            </script>
                            <script>
                                $(document).ready(function() {
                                    // Show the input field when 'Other' is selected
                                    $('#tag_id').change(function() {
                                        if ($(this).val().includes('other')) {
                                            $('#manual_tag_container').show();
                                        } else {
                                            $('#manual_tag_container').hide();
                                        }
                                    });

                                    // Add a new tag using AJAX
                                    $('#add_tag_button').click(function() {
                                        var newTag = $('#manual_tag_input').val();
                                        if (newTag.trim() !== '') {
                                            $.ajax({
                                                url: '{{ route('tags.store') }}',
                                                method: 'POST',
                                                data: {
                                                    name: newTag, // Send 'name' instead of 'tag'
                                                    _token: '{{ csrf_token() }}'
                                                },
                                                success: function(response) {
                                                    if (response.success) {
                                                        $('#tag_id').append('<option value="' + response.tag.id +
                                                            '" selected>' + response.tag.name + '</option>');
                                                        $('#manual_tag_input').val('');
                                                        $('#manual_tag_container').hide();
                                                    }
                                                },
                                                error: function() {
                                                    alert('Failed to add tag');
                                                }
                                            });
                                        }
                                    });
                                });
                            </script>
                            <script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>

                            <!-- Initialize CKEditor -->
                            <script>
                                ClassicEditor
                                    .create(document.querySelector('#editor'))
                                    .catch(error => {
                                        console.error('There was a problem initializing the editor:', error);
                                    });
                            </script>


                        </div>
                    </div>

                </div>
            </div>
        </div>
        <!-- Container-fluid starts -->
    </div>
@endsection
