<!DOCTYPE html>
<html lang="en">
@include('includes.head')
<body id="kt_body" class="header-fixed header-tablet-and-mobile-fixed toolbar-enabled toolbar-fixed aside-enabled aside-fixed">
    <div class="d-flex flex-column flex-root">
        <div class="page d-flex flex-row flex-column-fluid">
            @include('includes.side-nav')
            <div class="wrapper d-flex flex-column flex-row-fluid" id="kt_wrapper">
                @include('includes.header')
                <div class="content d-flex flex-column flex-column-fluid" id="kt_content">
                    <!-- Toolbar -->
                    <div class="toolbar" id="kt_toolbar">
                        <div id="kt_toolbar_container" class="container-fluid d-flex flex-stack">
                            <div class="page-title"><h1 class="text-dark fw-bolder fs-3">Illustration Management</h1></div>
                            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#illustrationModal" onclick="resetForm()">Add Illustration</button>
                        </div>
                    </div>
                    <div class="post d-flex flex-column-fluid" id="kt_post">
                        <div id="kt_content_container" class="container-xxl">
                            <div class="card">
                                @include('includes.messages')
                                <!-- Filter -->
                                <div class="card-body pb-0">
                                    <form method="GET" action="{{ route('illustration.list') }}" class="row g-3 align-items-end">
                                        <div class="col-md-3"><label>Search</label><input type="text" name="search" class="form-control" placeholder="Name..." value="{{ request('search') }}"></div>
                                        <div class="col-md-3"><label>Artist</label><select name="artist_id" class="form-select"><option value="">All</option>@foreach($artists as $a)<option value="{{ $a->id }}" {{ request('artist_id')==$a->id?'selected':'' }}>{{ $a->artist_name }}</option>@endforeach</select></div>
                                        <div class="col-md-3"><label>Category</label><select name="illustration_category_id" class="form-select"><option value="">All</option>@foreach($categories as $c)<option value="{{ $c->id }}" {{ request('illustration_category_id')==$c->id?'selected':'' }}>{{ $c->name_en }}</option>@endforeach</select></div>
                                        <div class="col-md-3"><button type="submit" class="btn btn-primary w-100 mb-2">Filter</button><a href="{{ route('illustration.list') }}" class="btn btn-secondary w-100">Reset</a></div>
                                    </form>
                                </div>
                                <div class="card-body pt-6">
                                    <div class="table-responsive">
                                        <table class="table align-middle table-row-dashed fs-6 gy-5">
                                            <thead><tr><th>ID</th><th>Name</th><th>Artist</th><th>Category</th><th>Status</th><th class="text-end">Actions</th></tr></thead>
                                            <tbody>
                                                @forelse($illustrations as $item)
                                                <tr id="row-{{ $item->id }}">
                                                    <td>{{ $item->id }}</td>
                                                    <td>{{ $item->name_en }}</td>
                                                    <td>{{ $item->artist->artist_name ?? '' }}</td>
                                                    <td>{{ $item->category->name_en ?? '' }}</td>
                                                    <td><span class="badge {{ $item->status?'badge-success':'badge-danger' }}">{{ $item->status?'Active':'Inactive' }}</span></td>
                                                    <td class="text-end">
                                                        <button class="btn btn-sm btn-primary edit-btn" data-id="{{ $item->id }}">Edit</button>
                                                        <button class="btn btn-sm btn-info images-btn" data-id="{{ $item->id }}" data-name="{{ $item->name_en }}">Images</button>
                                                        <button class="btn btn-sm btn-danger delete-btn" data-id="{{ $item->id }}">Delete</button>
                                                    </td>
                                                </tr>
                                                @empty
                                                <tr><td colspan="6" class="text-center">No records found</td></tr>
                                                @endforelse
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-3">{{ $illustrations->appends(request()->query())->links('pagination::bootstrap-4') }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                @include('includes.footer')
            </div>
        </div>
    </div>
    @include('includes.scripts')

    <!-- Modal Add/Edit with CKEditor -->
    <div class="modal fade" id="illustrationModal" tabindex="-1" data-bs-backdrop="static">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header"><h5 id="modalTitle">Add Illustration</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <form id="illustrationForm">
                        @csrf
                        <input type="hidden" name="id" id="recordId">
                        <div class="row mb-3">
                            <div class="col-md-6"><label class="required">Name</label><input type="text" name="name_en" id="name_en" class="form-control" required></div>
                            <div class="col-md-6"><label class="required">Artist</label><select name="artist_id" id="artist_id" class="form-select" required>@foreach($artists as $a)<option value="{{ $a->id }}">{{ $a->artist_name }}</option>@endforeach</select></div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12"><label class="required">Category</label><select name="illustration_category_id" id="illustration_category_id" class="form-select" required>@foreach($categories as $c)<option value="{{ $c->id }}">{{ $c->name_en }}</option>@endforeach</select></div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12"><label>Description (Rich Text)</label>
                                <textarea name="description" id="description" class="form-control editor" rows="5"></textarea>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6"><label>Status</label><select name="status" id="status" class="form-select"><option value="1">Active</option><option value="0">Inactive</option></select></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer"><button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="saveBtn">Save</button></div>
            </div>
        </div>
    </div>

    <!-- Modal Images (unchanged) -->
    <div class="modal fade" id="imageModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header"><h5 id="imageModalTitle">Upload Images</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" id="currentId">
                    <div class="mb-3"><label>Select Images (max 2MB each, multiple)</label><input type="file" id="imagesInput" class="form-control" accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" multiple><div id="previewImages" class="mt-3 row"></div></div>
                    <div class="mb-3"><h6>Existing Images</h6><div id="existingImages" class="row g-2"></div></div>
                </div>
                <div class="modal-footer"><button class="btn btn-secondary" data-bs-dismiss="modal">Close</button><button class="btn btn-primary" id="uploadBtn">Upload</button></div>
            </div>
        </div>
    </div>

    <script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
    <script>
        let ckEditorInstance = null;

        function resetForm() {
            $('#illustrationForm')[0].reset();
            $('#recordId').val('');
            $('#modalTitle').text('Add Illustration');
            if (ckEditorInstance) {
                ckEditorInstance.setData('');
            }
        }

        $(document).ready(function() {
            // Initialize CKEditor
            ckEditorInstance = CKEDITOR.replace('description', {
                toolbar: [
                    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
                    { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Blockquote'] },
                    { name: 'links', items: ['Link', 'Unlink'] },
                    { name: 'insert', items: ['Image', 'Table'] },
                    { name: 'tools', items: ['Maximize'] }
                ],
                height: 200
            });

            // Save Illustration (create/update)
            $('#saveBtn').click(function() {
                // Update CKEditor content to textarea
                if (ckEditorInstance) {
                    ckEditorInstance.updateElement();
                }
                let id = $('#recordId').val();
                let url = id ? "{{ route('illustration.update', '') }}/" + id : "{{ route('illustration.store') }}";
                let formData = $('#illustrationForm').serialize();
                if (id) formData += '&_method=PUT';
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: formData,
                    success: (res) => { if(res.success) location.reload(); else alert('Error'); },
                    error: (xhr) => { alert('Validation error'); }
                });
            });

            // Edit - load data into form and CKEditor
            $('.edit-btn').click(function() {
                let id = $(this).data('id');
                $.get("{{ route('illustration.edit', '') }}/" + id, function(res) {
                    if(res.success) {
                        let d = res.illustration;
                        $('#recordId').val(d.id);
                        $('#name_en').val(d.name_en);
                        $('#artist_id').val(d.artist_id);
                        $('#illustration_category_id').val(d.illustration_category_id);
                        $('#status').val(d.status);
                        if (ckEditorInstance) {
                            ckEditorInstance.setData(d.description || '');
                        }
                        $('#modalTitle').text('Edit Illustration');
                        $('#illustrationModal').modal('show');
                    } else alert('Not found');
                });
            });

            // Delete
            $('.delete-btn').click(function() {
                if(confirm('Delete?')) {
                    let id = $(this).data('id');
                    $.ajax({
                        url: "{{ route('illustration.delete', '') }}/" + id, type: 'DELETE', data: { _token: '{{ csrf_token() }}' },
                        success: (res) => { if(res.success) $('#row-'+id).remove(); else alert('Delete failed'); }
                    });
                }
            });

            // Image handling (unchanged, but ensure variable name does not conflict)
            let currentId = null;
            $('.images-btn').click(function() {
                currentId = $(this).data('id');
                $('#currentId').val(currentId);
                $('#imageModalTitle').text('Images for ' + $(this).data('name'));
                loadImages(currentId);
                $('#imageModal').modal('show');
            });

            function loadImages(id) {
                $.get("{{ route('illustration.images', '') }}/" + id, function(res) {
                    let html = '';
                    if(res.success && res.images.length) {
                        res.images.forEach(img => {
                            html += `<div class="col-md-3 position-relative mb-2">
                                        <img src="${res.baseUrl}${img.image}" class="img-thumbnail" style="width:100%; height:120px; object-fit:cover;">
                                        <button class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1" onclick="deleteImage(${img.id})"><i class="fas fa-trash"></i></button>
                                    </div>`;
                        });
                    } else html = '<div class="col-12 text-muted">No images yet.</div>';
                    $('#existingImages').html(html);
                });
            }

            window.deleteImage = function(imageId) {
                if(confirm('Delete this image?')) {
                    $.ajax({
                        url: "{{ route('illustration.deleteImage', '') }}/" + imageId, type: 'DELETE', data: { _token: '{{ csrf_token() }}' },
                        success: (res) => { if(res.success) loadImages(currentId); else alert('Delete failed'); }
                    });
                }
            };

            $('#imagesInput').on('change', function() {
                let preview = $('#previewImages');
                preview.empty();
                let files = this.files;
                for(let i=0; i<files.length; i++) {
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        preview.append(`<div class="col-md-3 mb-2"><img src="${e.target.result}" class="img-thumbnail" style="width:100%; height:120px; object-fit:cover;"></div>`);
                    };
                    reader.readAsDataURL(files[i]);
                }
            });

            $('#uploadBtn').click(function() {
                let formData = new FormData();
                let files = $('#imagesInput')[0].files;
                if(files.length === 0) { alert('Select images'); return; }
                for(let i=0; i<files.length; i++) formData.append('images[]', files[i]);
                formData.append('_token', '{{ csrf_token() }}');
                $.ajax({
                    url: "{{ route('illustration.uploadImages', '') }}/" + currentId,
                    type: 'POST', data: formData, processData: false, contentType: false,
                    success: (res) => {
                        if(res.success) {
                            $('#imagesInput').val('');
                            $('#previewImages').empty();
                            loadImages(currentId);
                            alert('Uploaded');
                        } else alert('Upload failed');
                    },
                    error: () => alert('Error uploading')
                });
            });
        });
    </script>
</body>
</html>
