<style>
    .clone-card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
        background: #fff;
        overflow: hidden;
    }

    .clone-card .card-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        padding: 20px;
        border: none;
    }

    .clone-card .card-header h4 {
        margin: 0;
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    .form-control-premium {
        border-radius: 10px;
        border: 1px solid #e0e0e0;
        padding: 12px 15px;
        height: auto;
        transition: all 0.3s ease;
    }

    .form-control-premium:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.1);
    }

    .custom-checkbox-premium .custom-control-label::before {
        border-radius: 6px;
        width: 20px;
        height: 20px;
        top: 2px;
    }

    .custom-checkbox-premium .custom-control-label::after {
        width: 20px;
        height: 20px;
        top: 2px;
    }

    .btn-premium {
        border-radius: 10px;
        padding: 12px 25px;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    .btn-submit {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        border: none;
    }

    .btn-submit:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        color: #fff;
    }

    /* Steps UI */
    .clone-steps-container {
        background: var(--soft-background);
        border-radius: 15px;
        padding: 25px;
        margin-top: 30px;
        display: none;
    }

    .clone-steps {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .clone-step {
        display: flex;
        align-items: flex-start;
        margin-bottom: 20px;
        position: relative;
        opacity: 0.4;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .clone-step:not(:last-child)::after {
        content: '';
        position: absolute;
        left: 17px;
        top: 35px;
        width: 2px;
        height: calc(100% - 15px);
        background: #e0e0e0;
        z-index: 1;
    }

    .clone-step.active {
        opacity: 1;
        transform: translateX(10px);
    }

    .clone-step.completed {
        opacity: 1;
    }

    .clone-step.completed:not(:last-child)::after {
        background: #28a745;
    }

    .step-icon {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #fff;
        border: 2px solid #e0e0e0;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        font-weight: bold;
        z-index: 2;
        transition: all 0.3s ease;
        flex-shrink: 0;
    }

    .clone-step.active .step-icon {
        border-color: #667eea;
        color: #667eea;
        box-shadow: 0 0 15px rgba(102, 126, 234, 0.3);
        animation: pulse 2s infinite;
    }

    .clone-step.completed .step-icon {
        background: #28a745;
        border-color: #28a745;
        color: #fff;
    }

    .step-content h5 {
        margin: 0 0 5px 0;
        font-size: 16px;
        font-weight: 600;
    }

    .step-content p {
        margin: 0;
        font-size: 13px;
        color: #6c757d;
    }

    @keyframes pulse {
        0% {
            box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.4);
        }

        70% {
            box-shadow: 0 0 0 10px rgba(102, 126, 234, 0);
        }

        100% {
            box-shadow: 0 0 0 0 rgba(102, 126, 234, 0);
        }
    }

    .progress-premium {
        height: 10px;
        border-radius: 5px;
        background-color: #e9ecef;
        margin-bottom: 25px;
    }

    .progress-bar-premium {
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        border-radius: 5px;
    }

    .items-selection-box {
        max-height: 400px;
        overflow-y: auto;
        padding: 15px;
        border-radius: 10px;
    }
</style>

<div class="row justify-content-center">
    <div class="col-md-10">
        <div class="clone-card card">
            <div class="card-header">
                <h4><i class="fas fa-copy mr-2"></i> <?= lang('clone_selective_items'); ?></h4>
            </div>
            <form action="<?= base_url("admin/queue/run_selective_item_clone"); ?>" method="post" id="cloneItemsForm">
                <?= csrf(); ?>
                <div class="card-body p-15">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold"><?= lang('clone_from_user'); ?> </label>
                                <select name="old_user_id" id="old_user_id" class="form-control select2 form-control-premium" onchange="redirectToSource(this.value)">
                                    <option value=""><?= lang('select'); ?></option>
                                    <?php foreach ($userList as  $key => $row) : ?>
                                        <option value="<?= $row['id'] ?>" <?= isset($get['sourceId']) && $get['sourceId'] == $row['id'] ? 'selected' : '' ?>> <?= $row['username']; ?> / <?= $row['email']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold"><?= lang('clone_for_user'); ?></label>
                                <select name="new_user_id" id="new_user_id" class="form-control select2 form-control-premium">
                                    <option value=""><?= lang('select'); ?></option>
                                    <?php foreach ($newRestaurant as  $key => $new) : ?>
                                        <option value="<?= $new->user_id ?>"> <?= $new->username; ?> / <?= $new->email; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($itemList) && $itemList): ?>

                        <div id="itemsContainer">
                            <div class="form-group mt-3">
                                <div class="d-flex justify-content-between align-items-center mb-10">
                                    <label class="font-weight-bold mb-0"><?= lang('select_items_to_clone'); ?></label>
                                    <div class="d-flex align-items-center gap-20">
                                        <div class="p-relative w-50">
                                            <input type="text" id="searchItem" class="form-control form-control-sm" placeholder="Search items..." style="padding-left: 30px;">
                                            <i class="fa fa-search position-absolute" style="top: 50%; left: 10px; transform: translateY(-50%); color: #aaa;"></i>
                                        </div>
                                        <div class="custom-control custom-checkbox custom-checkbox-premium ml-3 text-nowrap">
                                            <input type="checkbox" class="custom-control-input" id="selectAllItems">
                                            <label class="custom-control-label pl-2" for="selectAllItems"><?= lang('select_all'); ?></label>
                                        </div>
                                    </div>
                                </div>
                                <div class="items-selection-box">
                                    <div class="row" id="itemsList">
                                        <table class="table table-condensed table-striped" id="itemsTable">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th><?= !empty(lang('images')) ? lang('images') : "images"; ?> </th>
                                                    <th><?= !empty(lang('title')) ? lang('title') : "title"; ?></th>
                                                    <th><?= !empty(lang('price')) ? lang('price') : "price"; ?> </th>
                                                    <th><?= !empty(lang('extra')) ? lang('extra') : "extra"; ?></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                foreach ($itemList as $key => $row) : ?>


                                                    <tr id='<?= $row['id']; ?>' class="clickable-row" style="cursor: pointer;">
                                                        <td data-label="#"><label class="custom-control custom-checkbox"><input type="checkbox" name="item_ids[]" class="item_check" value="<?= $row['id']; ?>"></label> <?= $key + 1; ?></td>
                                                        <td data-label="<?= lang('images'); ?>">
                                                            <div class="serviceImgs">
                                                                <?php if ($row['img_type'] == 1) : ?>
                                                                    <img src="<?= base_url(!empty($row['thumb']) ? $row['thumb'] : EMPTY_IMG); ?>" alt="">
                                                                <?php else : ?>
                                                                    <img src="<?= !empty($row['img_url']) ? $row['img_url'] : base_url(EMPTY_IMG); ?>" alt="">
                                                                <?php endif; ?>
                                                            </div>
                                                        </td>
                                                        <td data-label="<?= lang('title'); ?>" class="item-title">
                                                            <?= html_escape($row['title']); ?>
                                                            <?php if ($row['veg_type'] == 1) : ?>
                                                                <label class="label" data-toggle="tooltip" title="<?= !empty(lang('veg')) ? lang('veg') : "veg"; ?>"><i class="fa fa-circle veg_type c_green"></i></label>
                                                            <?php elseif ($row['veg_type'] == 2) : ?>
                                                                <label class="label" data-toggle="tooltip" title="<?= !empty(lang('non_veg')) ? lang('non_veg') : "Non veg"; ?>"><i class="fa fa-circle veg_type c_red"></i></label>
                                                            <?php endif; ?>
                                                            <?= __taxStatus($shop->is_tax, $row); ?>


                                                            <?php if (isset($row['sub_category_id']) && !empty($row['sub_category_id']) && __sub() == 1) : ?>
                                                                <div class="mt-5">
                                                                    <small class="subcat"><?= lang('sub_category'); ?> : <?= subcat($row['sub_category_id']); ?></small>
                                                                </div>
                                                            <?php endif; ?>

                                                        </td>
                                                        <td data-label="<?= lang('price'); ?>">
                                                            <?php if ($row['is_size'] == 0) : ?>
                                                                <?= __price($row, $shop->id); ?>
                                                            <?php else : ?>
                                                                <?php
                                                                $price = json_decode($row['price']); ?>
                                                                <div class="sizeTags">

                                                                    <?php if (isset($price->variant_name) && !empty($price->variant_name)) : ?>
                                                                        <p class="m-0 w_100"><?= lang('variant_name'); ?> : <?= $price->variant_name; ?></p>
                                                                        <?php foreach ($price->variant_options as $key => $value) : ?>
                                                                            <label class="label default-light-soft-active mb-3"><?= $value->name; ?> : <?= currency_position($value->price, $shop->id); ?></label>
                                                                        <?php endforeach; ?>


                                                                    <?php else : ?>


                                                                        <?php
                                                                        foreach ($price as $key => $value) :
                                                                            if (!empty($value)) :
                                                                        ?>
                                                                                <label class="label default-light-soft-active mb-3"><?= $this->admin_m->get_size_by_slug($key, auth('id')); ?> : <?= currency_position($value, $shop->id); ?></label>
                                                                        <?php
                                                                            endif;
                                                                        endforeach;
                                                                        ?>
                                                                    <?php endif; ?>
                                                                </div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td data-label="<?= lang('extras'); ?>">
                                                            <?php if (isJson($row['allergen_id'])) : ?>
                                                                <label class="label bg-primary-soft text-wrap-wrap"><?= lang('allergens'); ?> : <?= is_array(json_decode($row['allergen_id'])) ? allergens(json_decode($row['allergen_id'])) : ''; ?></label>
                                                            <?php endif; ?>

                                                            <div class="mt-5 gap-5">
                                                                <?php if ($row['is_features'] == 1) : ?>
                                                                    <label class="label bg-success-soft" data-toggle="tooltip" title="show in home page"><i class="fa fa-home"></i></label>
                                                                <?php endif; ?>

                                                                <?php if ($row['is_highlight'] == 1) : ?>
                                                                    <label class="label bg-purple-soft-active" data-toggle="tooltip" title="<?= __('mark_as_highlight') ?>"><i class="fas fa-highlighter"></i></label>
                                                                <?php endif; ?>


                                                                <?php if ($row['is_pos_only'] == 1) : ?>
                                                                    <label class="label bg-purple-soft-active" data-toggle="tooltip" title="<?= __('only_for_pos') ?>"><i class="fas fa-shopping-basket"></i></label>
                                                                <?php endif; ?>

                                                                <?php if ($row['is_pos_only'] == 2) : ?>
                                                                    <label class="label primary-light-active" data-toggle="tooltip" title="<?= __('only_for_package') ?>"><i class="fas fa-box-open"></i></label>
                                                                <?php endif; ?>
                                                                <?php $is_extra = $this->admin_m->get_my_addons($row['id'], $row['shop_id']); ?>

                                                                <?php if (sizeof($is_extra) > 0) : ?>
                                                                    <label class="label info-light-active" data-toggle="tooltip" title="<?= __('extras') ?>"><i class="icofont-library"></i></label>
                                                                <?php endif ?>




                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php
                                                endforeach ?>

                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Progress Section -->
                    <div id="progressBarContainer" style="display: none;">
                        <hr class="my-4">
                        <div class="progress progress-premium">
                            <div id="progressBar" class="progress-bar progress-bar-premium" role="progressbar" style="width: 0%"></div>
                        </div>
                        <div id="progressText" class="text-center font-weight-bold mb-4" style="color: #764ba2;">Initializing...</div>

                        <div class="clone-steps-container" style="display: block;">
                            <ul class="clone-steps" id="stepsList">
                                <!-- Steps will be dynamically added here -->
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-light p-10">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex gap-10">
                            <button type="button" id="clearQueueBtn" class="btn btn-default">
                                <i class="fas fa-broom mr-1"></i> <?= lang('clear_queue'); ?>
                            </button>
                        </div>
                        <button type="submit" class="btn btn-submit btn-primary px-5">
                            <?= lang('start_cloning'); ?> <i class="fas fa-arrow-right ml-2"></i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function redirectToSource(id) {
        if (id) {
            window.location.href = `${base_url}admin/queue/clone_items?sourceId=${id}`;
        }
    }
    $(document).ready(function() {
        var totalTasks = 0;
        var completedTasks = 0;
        var visualQueue = [];
        var isAnimating = false;


        // Click anywhere on row to toggle checkbox
        $(document).on('click', '.clickable-row', function(e) {
            // Don't trigger if clicking directly on checkbox or label
            if ($(e.target).is('input[type="checkbox"]') || $(e.target).is('label')) {
                return;
            }

            var checkbox = $(this).find('.item_check');
            checkbox.prop('checked', !checkbox.prop('checked'));
        });

        // Select All functionality
        $('#selectAllItems').change(function() {
            $('.item_check').prop('checked', $(this).prop('checked'));
        });

        // Update Select All state when individual checkboxes change
        $(document).on('change', '.item_check', function() {
            var totalCheckboxes = $('.item_check').length;
            var checkedCheckboxes = $('.item_check:checked').length;
            $('#selectAllItems').prop('checked', totalCheckboxes === checkedCheckboxes);
        });

        $('#cloneItemsForm').submit(function(event) {
            event.preventDefault();
            let url = $(this).attr('action');

            if ($('.item_check:checked').length === 0) {
                alert('Please select at least one item.');
                return;
            }

            $('#progressBarContainer').fadeIn();
            $('#progressBar').width('0%');
            $('#progressText').text('Initializing...');
            $('#stepsList').html('');
            $('.btn-premium').prop('disabled', true);

            visualQueue = [];
            isAnimating = false;

            $.ajax({
                url: url,
                method: 'POST',
                dataType: 'json',
                data: $(this).serialize(),
                success: function(response) {
                    if (response.status == 1) {
                        totalTasks = response.totalTasks;
                        completedTasks = 0;
                        updateProgress(0, totalTasks);
                        processQueue();
                    } else {
                        $('#progressText').text('Error: ' + (response.error || 'Initialization failed')).addClass('text-danger');
                        $('.btn-premium').prop('disabled', false);
                    }
                },
                error: function() {
                    $('#progressText').text('Error occurred during initialization.').addClass('text-danger');
                    $('.btn-premium').prop('disabled', false);
                }
            });
        });

        function processQueue() {
            $.ajax({
                url: '<?= base_url("admin/queue/process_queue"); ?>',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.status == 1) {
                        if (response.completed_items && response.completed_items.length > 0) {
                            response.completed_items.forEach(function(item) {
                                visualQueue.push(item);
                            });
                            if (!isAnimating) {
                                processVisualQueue();
                            }
                        }

                        if (response.pending > 0) {
                            setTimeout(processQueue, 2000);
                        }
                    } else {
                        $('#progressText').text('Error: ' + (response.error || 'Processing failed')).addClass('text-danger');
                        $('.btn-premium').prop('disabled', false);
                    }
                },
                error: function() {
                    $('#progressText').text('Error occurred during processing.').addClass('text-danger');
                    $('.btn-premium').prop('disabled', false);
                }
            });
        }

        function processVisualQueue() {
            if (visualQueue.length === 0) {
                isAnimating = false;
                checkCompletion();
                return;
            }

            isAnimating = true;
            let item = visualQueue.shift();

            // Parse the table_name which is in format "item_id:item_title"
            let displayName = item.table_name;
            if (item.table_name.includes(':')) {
                // Extract the item title after the colon
                let parts = item.table_name.split(':');
                displayName = parts.slice(1).join(':'); // In case title has colons
            }

            // Add the step as "Active"
            let stepId = 'step_' + item.table_name.replace(/[^a-z0-9]/gi, '_') + '_' + Date.now();

            // Deactivate previous active steps
            $('.clone-step.active').addClass('completed').removeClass('active').find('i').removeClass('fa-spinner fa-spin').addClass('fa-check');
            $('.clone-step.completed .step-content p').text('Completed successfully');

            let stepHtml = `
                <li class="clone-step active" id="${stepId}">
                    <div class="step-icon">
                        <i class="fas fa-spinner fa-spin"></i>
                    </div>
                    <div class="step-content">
                        <h5>${displayName}</h5>
                        <p>Processing...</p>
                    </div>
                </li>
            `;

            $(stepHtml).hide().appendTo('#stepsList').slideDown(500);

            // Update progress bar
            completedTasks++;
            updateProgress(completedTasks, totalTasks);

            setTimeout(function() {
                $('#' + stepId).addClass('completed').removeClass('active');
                $('#' + stepId + ' .step-icon i').removeClass('fa-spinner fa-spin').addClass('fa-check');
                $('#' + stepId + ' .step-content p').text('Completed successfully');

                processVisualQueue();
            }, 1000); // Speed up for individual items
        }

        function checkCompletion() {
            if (visualQueue.length === 0 && !isAnimating) {
                $.get('<?= base_url("admin/queue/process_queue"); ?>', function(response) {
                    let res = JSON.parse(response);
                    if (res.pending === 0) {
                        $('#progressText').text('Cloning complete!').css('color', '#28a745');
                        $('.btn-premium').prop('disabled', false);

                        // Uncheck all selected items
                        $('.item_check').prop('checked', false);
                        $('#selectAllItems').prop('checked', false);
                    }
                });
            }
        }

        $('#clearQueueBtn').click(function() {
            if (confirm('Are you sure you want to clear the entire cloning queue?')) {
                $.ajax({
                    url: '<?= base_url("admin/queue/clear_queue"); ?>',
                    method: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status == 1) {
                            location.reload();
                        }
                    }
                });
            }
        });

        function updateProgress(progress, total) {
            var percentage = total > 0 ? (progress / total) * 100 : 0;
            $('#progressBar').css('width', percentage + '%');
            $('#progressText').text('Cloning in progress... ' + Math.round(percentage) + '%');
        }
        $('#searchItem').on('keyup', function() {
            var value = $(this).val().toLowerCase();
            $("#itemsTable tbody tr").filter(function() {
                $(this).toggle($(this).find('.item-title').text().toLowerCase().indexOf(value) > -1)
            });
        });
    });
</script>