<!DOCTYPE html>
<html lang="en">
<?php echo $__env->make('includes.head', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<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">
            <?php echo $__env->make('includes.side-nav', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
            <div class="wrapper d-flex flex-column flex-row-fluid" id="kt_wrapper">
                <?php echo $__env->make('includes.header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                <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 d-flex align-items-center flex-wrap me-3 mb-5 mb-lg-0">
                                <h1 class="d-flex align-items-center text-dark fw-bolder fs-3 my-1">
                                    Artist Management
                                    <span class="h-20px border-gray-200 border-start ms-3 mx-2"></span>
                                    <small class="text-muted fs-7 fw-bold my-1 ms-1">Artists</small>
                                </h1>
                            </div>
                            <div class="d-flex align-items-center py-1">
                                <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#artistModal" onclick="resetArtistForm()">
                                    Add Artist
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="post d-flex flex-column-fluid" id="kt_post">
                        <div id="kt_content_container" class="container-xxl">
                            <div class="card">
                                <?php echo $__env->make('includes.messages', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                                <!-- Filter form -->
                                <div class="card-header border-0 pt-6">
                                    <div class="card-title">
                                        <form method="GET" action="<?php echo e(route('artist.list')); ?>" class="d-flex align-items-center flex-wrap">
                                            <div class="d-flex align-items-center position-relative me-5 mb-2 mb-md-0">
                                                <span class="svg-icon svg-icon-1 position-absolute ms-6">
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                                                        <rect opacity="0.5" x="17.0365" y="15.1223" width="8.15546" height="2" rx="1" transform="rotate(45 17.0365 15.1223)" fill="black" />
                                                        <path d="M11 19C6.55556 19 3 15.4444 3 11C3 6.55556 6.55556 3 11 3C15.4444 3 19 6.55556 19 11C19 15.4444 15.4444 19 11 19ZM11 5C7.53333 5 5 7.53333 5 11C5 14.4667 7.53333 17 11 17C14.4667 17 17 14.4667 17 11C17 7.53333 14.4667 5 11 5Z" fill="black" />
                                                    </svg>
                                                </span>
                                                <input type="text" name="search" value="<?php echo e(request('search')); ?>" class="form-control form-control-solid w-250px ps-15" placeholder="Search artist..." />
                                            </div>
                                            <div class="me-5 mb-2 mb-md-0">
                                                <select name="tag_id" class="form-select form-select-solid">
                                                    <option value="">All Tags</option>
                                                    <?php $__currentLoopData = $allTags; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tag): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <option value="<?php echo e($tag->id); ?>" <?php echo e(request('tag_id') == $tag->id ? 'selected' : ''); ?>><?php echo e($tag->name_en); ?></option>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                </select>
                                            </div>
                                            <button type="submit" class="btn btn-primary me-2">Filter</button>
                                            <a href="<?php echo e(route('artist.list')); ?>" class="btn btn-secondary">Reset</a>
                                        </form>
                                    </div>
                                </div>

                                <!-- Table -->
                                <div class="card-body pt-0">
                                    <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>Photo</th>
                                                <th>Artist Name</th>
                                                <th>Tags</th>
                                                <th>Art Work</th>
                                                <th>Status</th>
                                                <th class="text-end">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody class="fw-bold text-gray-600">
                                            <?php $__currentLoopData = $artists; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $artist): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <tr id="artist-row-<?php echo e($artist->id); ?>">
                                                <td><?php echo e($artist->id); ?></td>
                                                <td>
                                                    <?php if($artist->profile_pic): ?>
                                                        <img src="<?php echo e($baseImgPath ?? ''); ?><?php echo e($artist->profile_pic); ?>" style="width: 50px; height: 50px; object-fit: cover;" class="rounded">
                                                    <?php else: ?>
                                                        <span class="badge badge-light">No Image</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?php echo e($artist->artist_name); ?></td>
                                                <td>
                                                    <?php
                                                        $tagNames = [];
                                                        $tagIds = explode(',', $artist->tag_ids ?? '');
                                                        foreach($tagIds as $tid) {
                                                            $tag = $allTags->firstWhere('id', $tid);
                                                            if($tag) $tagNames[] = $tag->name_en;
                                                        }
                                                        echo implode(', ', $tagNames);
                                                    ?>
                                                </td>
                                                <td><?php echo e($artist->art_work ?? 0); ?></td>
                                                <td>
                                                    <span class="badge <?php echo e($artist->status ? 'badge-success' : 'badge-danger'); ?>">
                                                        <?php echo e($artist->status ? 'Active' : 'Inactive'); ?>

                                                    </span>
                                                </td>
                                                <td class="text-end">
                                                    <button class="btn btn-sm btn-primary edit-artist" data-id="<?php echo e($artist->id); ?>">
                                                        <i class="fas fa-edit"></i> Edit
                                                    </button>
                                                    <button class="btn btn-sm btn-danger delete-artist" data-id="<?php echo e($artist->id); ?>">
                                                        <i class="fas fa-trash"></i> Delete
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </tbody>
                                    </table>
                                    <?php echo e($artists->links('pagination::bootstrap-4')); ?>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php echo $__env->make('includes.footer', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
            </div>
        </div>
    </div>
    <?php echo $__env->make('includes.scripts', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>

    <!-- Select2 CSS/JS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <!-- Modal for Add/Edit Artist -->
    <div class="modal fade" id="artistModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="artistModalTitle">Add Artist</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="artistForm" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="id" id="artistId">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label required">Artist Name</label>
                                <input type="text" name="artist_name" id="artist_name" class="form-control" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Profile Picture</label>
                                <input type="file" name="profile_pic" id="profile_pic" class="form-control" accept="image/*">
                                <div id="profilePreview" class="mt-2"></div>
                            </div>
                            <div class="col-md-12">
                                <label class="form-label required">Artist Address</label>
                                <input type="text" name="address" id="address" class="form-control">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Tags (Select2 - can add new)</label>
                                <select name="tag_ids[]" id="tag_ids" class="form-select" multiple></select>
                                <small class="text-muted">Type to search or create new tag</small>
                            </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" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Art Work (count)</label>
                                <input type="number" name="art_work" id="art_work" class="form-control" value="0">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Exhibitions</label>
                                <input type="number" name="exhibitions" id="exhibitions" class="form-control" value="0">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Awards</label>
                                <input type="number" name="awards" id="awards" class="form-control" value="0">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-3">
                                <label class="form-label">Facebook</label>
                                <input type="url" name="facebook" id="facebook" class="form-control" placeholder="https://...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Instagram</label>
                                <input type="url" name="instagram" id="instagram" class="form-control" placeholder="https://...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">YouTube</label>
                                <input type="url" name="youtube" id="youtube" class="form-control" placeholder="https://...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Twitter</label>
                                <input type="url" name="twitter" id="twitter" class="form-control" placeholder="https://...">
                            </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">Close</button>
                    <button type="button" class="btn btn-primary" id="saveArtistBtn">Save</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function resetArtistForm() {
            $('#artistForm')[0].reset();
            $('#artistId').val('');
            $('#tag_ids').val(null).trigger('change');
            $('#profilePreview').html('');
            $('#artistModalTitle').text('Add Artist');
        }

        $(document).ready(function() {
            // Initialize Select2 for tags
           $('#tag_ids').select2({
    dropdownParent: $('#artistModal'),
    ajax: {
        url: "<?php echo e(route('artTag.ajaxList')); ?>",
        dataType: 'json',
        delay: 250,
        data: function(params) { return { search: params.term }; },
        processResults: function(data) {
            return { results: data.map(item => ({ id: item.id, text: item.name_en })) };
        },
        cache: true
    },
    tags: true,
    createTag: function(params) {
        var term = $.trim(params.term);
        if (term === '') return null;
        // Check if term already exists in current options
        var existing = this.$element.find('option').filter(function() {
            return $(this).text().toLowerCase() === term.toLowerCase();
        }).first();
        if (existing.length) {
            return { id: existing.val(), text: existing.text(), existing: true };
        }
        return { id: term, text: term, newTag: true };
    },
    templateResult: function(data) {
        if (data.existing) return $('<span>' + data.text + ' (already exists)</span>');
        if (data.newTag) return $('<span>Create: ' + data.text + '</span>');
        return data.text;
    },
    templateSelection: function(data) {
        return data.text;
    }
});

            // Preview profile picture
            $('#profile_pic').on('change', function() {
                let file = this.files[0];
                if (file) {
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        $('#profilePreview').html('<img src="' + e.target.result + '" style="max-width: 100px; max-height: 100px;" class="img-thumbnail">');
                    };
                    reader.readAsDataURL(file);
                } else {
                    $('#profilePreview').html('');
                }
            });

            // Save Artist (create or update)
            $('#saveArtistBtn').click(function() {
                let id = $('#artistId').val();
                let formData = new FormData($('#artistForm')[0]);

                // Handle tags: we must send tag_ids as JSON array of IDs, and for newly created tags,
                // we need to create them on server first. However, simplest: send tag_names array.
                // We'll extract selected tag texts from select2.
                let selectedTags = $('#tag_ids').select2('data');
                let tagNames = selectedTags.map(item => item.text);
                // Remove existing tag_ids[] from formData and append tag_names[]
                formData.delete('tag_ids[]');
                tagNames.forEach(name => formData.append('tag_names[]', name));

                let url = id ? "<?php echo e(route('artist.update', '')); ?>/" + id : "<?php echo e(route('artist.store')); ?>";
                if (id) formData.append('_method', 'PUT');

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res.success) {
                            $('#artistModal').modal('hide');
                            location.reload();
                        } else {
                            alert('Error saving artist');
                        }
                    },
                    error: function(xhr) {
                        let errors = xhr.responseJSON.errors;
                        if (errors) alert(Object.values(errors).flat().join('\n'));
                        else alert('Something went wrong');
                    }
                });
            });

            // Edit button click
            $('.edit-artist').click(function() {
    let id = $(this).data('id');
    $.get("<?php echo e(route('artist.edit', '')); ?>/" + id, function(res) {
        if (res.success) {
            let a = res.artist;

            // Populate all other fields
            $('#artistId').val(a.id);
            $('#artist_name').val(a.artist_name);
            $('#address').val(a.address);
            $('#description').val(a.description);
            $('#art_work').val(a.art_work);
            $('#exhibitions').val(a.exhibitions);
            $('#awards').val(a.awards);
            $('#facebook').val(a.facebook);
            $('#instagram').val(a.instagram);
            $('#youtube').val(a.youtube);
            $('#twitter').val(a.twitter);
            $('#status').val(a.status);

            // Show profile picture preview if exists
            if (a.profile_pic_url) {
                $('#profilePreview').html('<img src="'+a.profile_pic_url+'" style="max-width:100px;" class="img-thumbnail">');
            } else {
                $('#profilePreview').html('');
            }

            // ---- ADD THIS PART ----
            // Pre-select tags in Select2
            let tagIds = a.tag_ids ? a.tag_ids.split(',') : [];
            $('#tag_ids').val(tagIds).trigger('change');
            // ------------------------

            // Change modal title and show
            $('#artistModalTitle').text('Edit Artist');
            $('#artistModal').modal('show');
        } else {
            alert('Artist not found');
        }
    });
});

            // Delete button click
            $('.delete-artist').click(function() {
                if (confirm('Are you sure you want to delete this artist?')) {
                    let id = $(this).data('id');
                    $.ajax({
                        url: "<?php echo e(route('artist.delete', '')); ?>/" + id,
                        type: 'DELETE',
                        data: { _token: '<?php echo e(csrf_token()); ?>' },
                        success: function(res) {
                            if (res.success) {
                                $('#artist-row-' + id).remove();
                                if ($('tbody tr').length === 0) location.reload();
                            } else {
                                alert('Delete failed');
                            }
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>
<?php /**PATH D:\xampp\htdocs\creativeValley9\resources\views/Admin/Artist/list.blade.php ENDPATH**/ ?>