<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<!-- Bootstrap 5 Bundle JS (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>


<!-- Ring Loader -->
<div id="loaderOverlay">
    <div class="loader"></div>
</div>

<style>
    #loaderOverlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.8);
        z-index: 9999;
        display: none;
        align-items: center;
        justify-content: center;
    }

    .loader {
        border: 6px solid #f3f3f3;
        border-top: 6px solid #3498db;
        border-radius: 50%;
        width: 60px;
        height: 60px;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }
</style>


<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3>Manage Avatars</h3>
        <div class="dropdown">
            <button class="btn btn-success" type="button" data-bs-toggle="modal" data-bs-target="#addAvatarModal">
                Add Avatar
            </button>

        </div>
    </div>

    <?php foreach ($avatars as $category => $avatarList): ?>
        <div class="card mb-4">
            <div class="card-header">
                <h2 class="mb-0"><?= $category ?></h2>
            </div>
            <div class="card-body">
                <div class="row">
                    <?php foreach ($avatarList as $avatar): ?>
                        <div class="col-md-2 text-center mb-3">
                            <img src="<?= $avatar['name'] ?>" class="img-fluid img-thumbnail" height="100" width="100" alt="Avatar">
                            <p class="mt-2 mb-1"><strong>Unlock Points:</strong> <?= $avatar['unlockPoint'] ?></p>
                            <p><strong><?= $avatar['isPremium'] ? 'Premium' : 'Free' ?></strong></p>
                            <button class="btn btn-primary btn-sm" onclick='editAvatarModal(<?= json_encode($avatar) ?>)'>Edit</button>
                            <button class="btn btn-danger btn-sm" onclick="deleteAvatar('<?= $avatar['id'] ?>')">Delete</button>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<!-- Edit Avatar Modal -->
<div class="modal fade" id="editAvatarModal" tabindex="-1" aria-labelledby="editAvatarModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form id="editAvatarForm" enctype="multipart/form-data">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Avatar</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="avatarId" id="editAvatarId">

                    <div class="mb-3">
                        <label class="form-label">Category</label>
                        <select name="category" id="editCategory" class="form-select" required>
                            <option value="">-- Select Category --</option>                           
                            <option value="Starter Pack">Starter Pack</option>
                            <option value="Holiday Pack">Holiday Pack</option>
                            <option value="Exclusive Avatars">Exclusive Avatars</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Unlock Points</label>
                        <input type="number" name="unlockPoint" id="editUnlockPoint" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Change Image (optional)</label>
                        <input type="file" name="avatarImage" class="form-control" accept="image/*">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Update Avatar</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </form>
    </div>
</div>



<!-- Add Avatar Modal -->
<div class="modal fade" id="addAvatarModal" tabindex="-1" aria-labelledby="addAvatarModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form id="addAvatarForm" enctype="multipart/form-data">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Avatar</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="category" class="form-label">Category</label>
                        <select name="category" class="form-select" required>
                            <option value="">-- Select Category --</option>
                            <option value="Holiday Pack">Holiday Pack</option>
                            <option value="Starter Pack">Starter Pack</option>
                            <option value="Exclusive Avatars">Exclusive Avatars</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="unlockPoint" class="form-label">Unlock Points</label>
                        <input type="number" name="unlockPoint" class="form-control" required>
                    </div>

                    <!-- <div class="mb-3 form-check">
                        <input type="checkbox" name="isPremium" class="form-check-input" id="isPremium">
                        <label class="form-check-label" for="isPremium">Premium</label>
                    </div> -->

                    <div class="mb-3">
                        <label for="avatarImage" class="form-label">Avatar Image</label>
                        <input type="file" name="avatarImage" class="form-control" accept="image/*" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">Add Avatar</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </form>
    </div>
</div>
<!-- jQuery (Required for your script to work) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    $(document).ready(function() {
        $('#addAvatarForm').on('submit', function(e) {
            e.preventDefault();

            var formData = new FormData(this);


            $('#loaderOverlay').css('display', 'flex');

            $.ajax({
                url: '<?= base_url("Customer/addAvatar") ?>',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                dataType: 'json',
                success: function(response) {
                    $('#loaderOverlay').fadeOut(); // Hide loader
                    if (response.success) {
                        alert(response.message);
                        location.reload();
                    } else {
                        alert(response.message);
                    }
                },
                error: function(xhr) {
                    $('#loaderOverlay').fadeOut(); // Hide loader
                    alert('Something went wrong. Try again.');
                    console.error(xhr.responseText);
                }
            });
        });
    });
</script>



<script>
    function deleteAvatar(avatarId) {
        if (!confirm('Are you sure you want to delete this avatar?')) return;

        $('#loaderOverlay').css('display', 'flex'); // Show loader

        $.ajax({
            url: '<?= base_url("Customer/deleteAvatar") ?>',
            type: 'POST',
            data: {
                avatarId: avatarId
            },
            dataType: 'json',
            success: function(response) {
                $('#loaderOverlay').fadeOut(); // Hide loader

                if (response.success) {
                    alert(response.message);
                    location.reload();
                } else {
                    alert('Failed: ' + response.message);
                }
            },
            error: function(xhr) {
                $('#loaderOverlay').fadeOut(); // Hide loader

                alert('Something went wrong. Try again.');
                console.error(xhr.responseText);
            }
        });
    }
</script>

<script>
    function editAvatarModal(avatar) {
        $('#editAvatarId').val(avatar.id);
        $('#editCategory').val(avatar.category);
        $('#editUnlockPoint').val(avatar.unlockPoint);
        $('#editIsPremium').prop('checked', avatar.isPremium);

        const modal = new bootstrap.Modal(document.getElementById('editAvatarModal'));
        modal.show();
    }
</script>
<script>
    $('#editAvatarForm').on('submit', function(e) {
        e.preventDefault();

        var formData = new FormData(this);
        // $('#loaderOverlay').fadeIn().display('flex'); // Show loader
        $('#loaderOverlay').css('display', 'flex');


        $.ajax({
            url: '<?= base_url("Customer/updateAvatar") ?>',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(response) {
                $('#loaderOverlay').fadeOut(); // Hide loader

                if (response.success) {
                    alert(response.message);
                    location.reload(); // Refresh to show updated avatar
                } else {
                    alert('Update failed: ' + response.message);
                }
            },
            error: function(xhr) {
                $('#loaderOverlay').fadeOut(); // Hide loader

                alert('Something went wrong. Try again.');
                console.error(xhr.responseText);
            }
        });
    });
</script>