<!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="post d-flex flex-column-fluid" id="kt_post">
                        <div id="kt_content_container" class="container-xxl">
                            <div class="card">
                                @include('includes.messages')
                                <div class="card-header">
<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">Art Management</h1>
                            </div>
                            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#artModal" onclick="resetArtForm()">Add Art</button>
                        </div>
                    </div>

                                </div>

                                <!-- ========== FILTER FORM (ALWAYS VISIBLE) ========== -->
                                <div class="card-body pb-0">
                                    <form method="GET" action="{{ route('art.list') }}" class="row g-3 align-items-end">
                                        <div class="col-md-3">
                                            <label class="form-label">Search by Name</label>
                                            <input type="text" name="search" class="form-control form-control-solid" placeholder="Art name..." value="{{ request('search') }}">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Artist</label>
                                            <select name="artist_id" class="form-select form-select-solid">
                                                <option value="">All Artists</option>
                                                @foreach($artists as $artist)
                                                    <option value="{{ $artist->id }}" {{ request('artist_id') == $artist->id ? 'selected' : '' }}>{{ $artist->artist_name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Painting Category</label>
                                            <select name="painting_category_id" class="form-select form-select-solid">
                                                <option value="">All Categories</option>
                                                @foreach($categories as $cat)
                                                    <option value="{{ $cat->id }}" {{ request('painting_category_id') == $cat->id ? 'selected' : '' }}>{{ $cat->name_en }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="d-flex gap-2">
                                                <button type="submit" class="btn btn-primary flex-grow-1">Filter</button>
                                                <a href="{{ route('art.list') }}" class="btn btn-secondary flex-grow-1">Reset</a>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <!-- ========== END FILTER FORM ========== -->

                                <!-- Art Table -->
                                <div class="card-body pt-6">
                                    <div class="table-responsive">
                                        <table class="table align-middle table-row-dashed fs-6 gy-5">
                                            <thead>
                                                <tr class="text-start text-gray-400 fw-bolder fs-7 text-uppercase">
                                                    <th>ID</th>
                                                    <th>Unique ID</th>
                                                    <th>Name</th>
                                                    <th>Artist</th>
                                                    <th>Category</th>
                                                    <th>Price</th>
                                                    <th>Status</th>
                                                    <th class="text-end">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody class="fw-bold text-gray-600">
                                                @forelse($arts as $art)
                                                <tr id="art-row-{{ $art->id }}">
                                                    <td>{{ $art->id }}</td>
                                                    <td>{{ $art->art_unique_id }}</td>
                                                    <td>{{ $art->name_en }}</td>
                                                    <td>{{ $art->artist->artist_name ?? 'N/A' }}</td>
                                                    <td>{{ $art->category->name_en ?? 'N/A' }}</td>
                                                    <td>${{ number_format($art->price) }}</td>
                                                    <td>
                                                        <span class="badge {{ $art->status ? 'badge-success' : 'badge-danger' }}">
                                                            {{ $art->status ? 'Active' : 'Inactive' }}
                                                        </span>
                                                    </td>
                                                    <td class="text-end">
                                                        <button class="btn btn-sm btn-primary edit-art" data-id="{{ $art->id }}">
                                                            <i class="fas fa-edit"></i> Edit
                                                        </button>
                                                        <button class="btn btn-sm btn-info upload-images" data-id="{{ $art->id }}" data-name="{{ $art->name_en }}">
                                                            <i class="fas fa-images"></i> Images
                                                        </button>
                                                        <button class="btn btn-sm btn-danger delete-art" data-id="{{ $art->id }}">
                                                            <i class="fas fa-trash"></i> Delete
                                                        </button>
                                                    </td>
                                                </tr>
                                                @empty
                                                <tr>
                                                    <td colspan="8" class="text-center text-muted">No art found.</td>
                                                </tr>
                                                @endforelse
                                            </tbody>
                                        </table>
                                    </div>

                                    <!-- Pagination with fallback message -->
                                    <div class="mt-3">
                                        @if($arts->hasPages())
                                            {{ $arts->appends(request()->query())->links('pagination::bootstrap-4') }}
                                        @else
                                            <div class="text-muted text-center py-2">
                                                Showing all {{ $arts->total() }} records
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                @include('includes.footer')
            </div>
        </div>
    </div>

    @include('includes.scripts')

    <!-- ========== ADD/EDIT ART MODAL ========== -->
    <div class="modal fade" id="artModal" tabindex="-1" data-bs-backdrop="static">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="artModalTitle">Add Art</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="artForm">
                        @csrf
                        <input type="hidden" name="id" id="artId">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label required">Artist</label>
                                <select name="artist_id" id="artist_id" class="form-select" required>
                                    <option value="">Select Artist</option>
                                    @foreach($artists as $a)
                                        <option value="{{ $a->id }}">{{ $a->artist_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label required">Category</label>
                                <select name="painting_category_id" id="painting_category_id" class="form-select" required>
                                    <option value="">Select Category</option>
                                    @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 class="form-label required">Art Name</label>
                                <input type="text" name="name_en" id="name_en" class="form-control" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Medium</label>
                                <input type="text" name="medium" id="medium" class="form-control">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Width</label>
                                <input type="text" name="width" id="width" class="form-control">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Height</label>
                                <input type="text" name="height" id="height" class="form-control">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Year</label>
                                <input type="text" name="year" id="year" class="form-control">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label required">Price</label>
                                <input type="number" name="price" id="price" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Old Price</label>
                                <input type="number" name="old_price" id="old_price" class="form-control">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Description</label>
                                <textarea name="description" id="description" class="form-control editor" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">About Art</label>
                                <textarea name="about_art" id="about_art" class="form-control editor" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Shipping Package</label>
                                <textarea name="shipping_package" id="shipping_package" class="form-control editor" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Certificate of Authenticity</label>
                                <textarea name="Certificate_of_Authenticity" id="Certificate_of_Authenticity" class="form-control editor" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Return & Refund Policy</label>
                                <textarea name="return_refund_policy" id="return_refund_policy" class="form-control editor" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-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 type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="saveArtBtn">Save</button>
                </div>
            </div>
        </div>
    </div>

    <!-- ========== IMAGE UPLOAD MODAL ========== -->
    <div class="modal fade" id="imageModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" 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="currentArtId">
                    <div class="mb-3">
                        <label class="form-label">Select Images (max 2MB each, multiple allowed)</label>
                        <input type="file" id="artImages" class="form-control" accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" multiple>
                        <div id="imagePreview" 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 type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="uploadImagesBtn">Upload</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
    <script>
        function resetArtForm() {
            $('#artForm')[0].reset();
            $('#artId').val('');
            $('#artModalTitle').text('Add Art');
            for (var instance in CKEDITOR.instances) {
                CKEDITOR.instances[instance].setData('');
            }
        }

        $(document).ready(function() {
            // Initialize CKEditor
            $('.editor').each(function() {
                CKEDITOR.replace(this.id, {
                    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: 150
                });
            });

            // Save Art
            $('#saveArtBtn').click(function() {
                for (var instance in CKEDITOR.instances) {
                    CKEDITOR.instances[instance].updateElement();
                }
                let id = $('#artId').val();
                let url = id ? "{{ route('art.update', '') }}/" + id : "{{ route('art.store') }}";
                let formData = $('#artForm').serialize();
                if (id) formData += '&_method=PUT';
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: formData,
                    success: function(res) {
                        if (res.success) location.reload();
                        else alert('Error saving art');
                    },
                    error: function(xhr) {
                        let errors = xhr.responseJSON.errors;
                        if (errors) alert(Object.values(errors).flat().join('\n'));
                        else alert('Something went wrong');
                    }
                });
            });

            // Edit Art
            $('.edit-art').click(function() {
                let id = $(this).data('id');
                $.get("{{ route('art.edit', '') }}/" + id, function(res) {
                    if (res.success) {
                        let a = res.art;
                        $('#artId').val(a.id);
                        $('#artist_id').val(a.artist_id);
                        $('#painting_category_id').val(a.painting_category_id);
                        $('#name_en').val(a.name_en);
                        $('#medium').val(a.medium);
                        $('#width').val(a.width);
                        $('#height').val(a.height);
                        $('#year').val(a.year);
                        $('#price').val(a.price);
                        $('#old_price').val(a.old_price);
                        $('#status').val(a.status);
                        CKEDITOR.instances['description'].setData(a.description || '');
                        CKEDITOR.instances['about_art'].setData(a.about_art || '');
                        CKEDITOR.instances['shipping_package'].setData(a.shipping_package || '');
                        CKEDITOR.instances['Certificate_of_Authenticity'].setData(a.Certificate_of_Authenticity || '');
                        CKEDITOR.instances['return_refund_policy'].setData(a.return_refund_policy || '');
                        $('#artModalTitle').text('Edit Art');
                        $('#artModal').modal('show');
                    } else {
                        alert('Art not found');
                    }
                });
            });

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

            // Image handling
            let currentArtId = null;
            $('.upload-images').click(function() {
                currentArtId = $(this).data('id');
                $('#currentArtId').val(currentArtId);
                $('#imageModalTitle').text('Images for ' + $(this).data('name'));
                loadExistingImages(currentArtId);
                $('#imageModal').modal('show');
            });

            function loadExistingImages(artId) {
                $.get("{{ route('art.images', '') }}/" + artId, 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('art.deleteImage', '') }}/" + imageId,
                        type: 'DELETE',
                        data: { _token: '{{ csrf_token() }}' },
                        success: function(res) {
                            if (res.success) loadExistingImages(currentArtId);
                            else alert('Delete failed');
                        }
                    });
                }
            };

            $('#artImages').on('change', function() {
                let preview = $('#imagePreview');
                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]);
                }
            });

            $('#uploadImagesBtn').click(function() {
                let formData = new FormData();
                let files = $('#artImages')[0].files;
                if (files.length === 0) {
                    alert('Select at least one image');
                    return;
                }
                for (let i = 0; i < files.length; i++) {
                    formData.append('images[]', files[i]);
                }
                formData.append('_token', '{{ csrf_token() }}');
                $.ajax({
                    url: "{{ route('art.uploadImages', '') }}/" + currentArtId,
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res.success) {
                            $('#artImages').val('');
                            $('#imagePreview').empty();
                            loadExistingImages(currentArtId);
                            alert('Images uploaded successfully');
                        } else {
                            alert('Upload failed');
                        }
                    },
                    error: function() {
                        alert('Error uploading');
                    }
                });
            });
        });
    </script>
</body>
</html>
