<?php $__env->startSection('title', 'Settings'); ?>

<?php $__env->startPush('css'); ?>
    <link rel="stylesheet" href="/assets/plugins/select2/css/select2.min.css">
    <link rel="stylesheet" href="/assets/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">
    <style>
        .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
            display: none !important
        }
    </style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6 offse">
                    <h1>Setting</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="<?php echo e(routeHelper('dashboard')); ?>">Home</a></li>
                        <li class="breadcrumb-item active">My Profile</li>
                    </ol>
                </div>
            </div>
        </div>
    </section>
    <section class="content">
        <form action="<?php echo e(routeHelper('setting')); ?>" method="POST">
            <?php echo csrf_field(); ?>
            <?php echo method_field('PUT'); ?>
            <input type="hidden" name="type" value="3">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Home page sorting</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-sm-8 offset-md-2">
                            <div class="card card-success">
                                <div class="card-header">
                                    <h3 class="card-title">Home page section sorting</h3>
                                </div>
                                <?php
                                    // Fetch section_sort from the database or fallback to default
                                    $section_sort_db = setting('section_sort');

                                    $default_section_sort = [
                                        "slider" => ["status" => 1, "order" => 1, "view" => 'frontend.partial.index.slider'],
                                        "custom_notices" => ["status" => 1, "order" => 2, "view" => 'frontend.partial.index.custom_notice_section'],
                                        "custom_section" => ["status" => 1, "order" => 3, "view" => 'frontend.partial.index.custom_section'],
                                        "campaign_section" => ["status" => 1, "order" => 4, "view" => 'frontend.partial.index.campaign_section'],
                                        "top_categories" => ["status" => 1, "order" => 5, "view" => 'frontend.partial.index.top_categories'],
                                        "features_slider" => ["status" => 1, "order" => 6, "view" => 'frontend.partial.index.features_slider'],
                                        "vendor_seller" => ["status" => 1, "order" => 7, "view" => 'frontend.partial.index.vendor_seller'],
                                        "latest_products" => ["status" => 1, "order" => 8, "view" => 'frontend.partial.index.latest_product'],
                                        "advertisement_home_middle" => ["status" => 1, "order" => 9, "view" => 'frontend.partial.index.advertisement.home_middle'],
                                        "featured_products" => ["status" => 1, "order" => 10, "view" => 'frontend.partial.index.featured_products'],
                                        "sub_slider" => ["status" => 1, "order" => 11, "view" => 'frontend.partial.index.sub_slider'],
                                        "classified" => ["status" => 1, "order" => 12, "view" => 'frontend.partial.index.classified'],
                                        "brands" => ["status" => 1, "order" => 13, "view" => 'frontend.partial.index.brands'],
                                        "cat_small_summery" => ["status" => 1, "order" => 14, "view" => 'frontend.partial.index.cat_small_summery'],
                                        "newsletter_section" => ["status" => 1, "order" => 15, "view" => 'frontend.partial.index.newsletter_section'],
                                        "advertisement_home_bottom" => ["status" => 1, "order" => 16, "view" => 'frontend.partial.index.advertisement.home_bottom']
                                    ];

                                    // If section_sort exists in DB and is not empty, use it. Otherwise, use default $section_sort.
                                    if (!empty($section_sort_db)) {
                                        $section_sort = json_decode($section_sort_db, true);
                                        // Compare with default sort and add missing sections
                                        foreach ($default_section_sort as $key => $default_section) {
                                            if (!array_key_exists($key, $section_sort)) {
                                                $section_sort[$key] = $default_section;
                                            }
                                        }
                                    } else {
                                        $section_sort = $default_section_sort;
                                    }

                                    // Sort sections based on 'order' key
                                    uasort($section_sort, function($a, $b) {
                                        return $a['order'] <=> $b['order'];
                                    });

                                    // Encode for the hidden input
                                    $section_sort_json = json_encode($section_sort);
                                ?>
                                
                                <ul class="px-2 my-2 rounded" id="sortable">
                                    <?php $__currentLoopData = $section_sort; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $section): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <li class="sort_item d-flex justify-content-between cursor-pointer py-2 px-2 bg-light border"
                                            data-serial="<?php echo e($section['order']); ?>" 
                                            data-name="<?php echo e($key); ?>"
                                            data-status="<?php echo e($section['status']); ?>"
                                            <?php if(isset($section['cat_type'])): ?> data-cat_type="<?php echo e($section['cat_type']); ?>" <?php endif; ?>
                                            <?php if(isset($section['cat_id'])): ?> data-cat_id="<?php echo e($section['cat_id']); ?>" <?php endif; ?>>
                                            
                                            <!-- Section Name -->
                                            <span><i class="fa fa-bars" aria-hidden="true"></i>&nbsp;&nbsp;<?php echo e(ucwords(str_replace('_', ' ', $key))); ?></span>

                                            <!-- Action Buttons -->
                                            <div class="action-buttons">
                                                <!-- Show/Hide Button -->
                                                <button class="status-toggle-btn btn btn-sm <?php echo e($section['status'] == 1 ? 'btn-warning' : 'btn-success'); ?>">
                                                    <?php echo e($section['status'] == 1 ? 'Hide' : 'Show'); ?>

                                                </button>

                                                <!-- Remove Button (only for categories with cat_type) -->
                                                <?php if(isset($section['cat_type'])): ?>
                                                    <button class="remove-btn btn btn-danger btn-sm">Remove</button>
                                                <?php endif; ?>
                                            </div>
                                        </li>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </ul>
                                <input name="section_sort" id="section_sort" type="hidden" value="<?php echo e($section_sort_json); ?>">
                                <div class="form-group col-md-12">
                                    <label for="mega" class="text-capitalize">Mega Category</label>
                                    <select name="mega[]" id="mega" class="select2 form-control" multiple>
                                        <?php $__currentLoopData = \App\Models\Category::where('status', true)->get(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($category->id); ?>"><?php echo e($category->name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="form-group col-md-12">
                                    <label for="sub" class="text-capitalize">Sub Category</label>
                                    <select name="sub[]" id="sub" class="select2 form-control" multiple>
                                        <?php $__currentLoopData = \App\Models\SubCategory::where('status', true)->get(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($category->id); ?>"><?php echo e($category->name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>



                                <div class="form-group col-md-12">
                                    <label for="mini" class="text-capitalize">Mini Category</label>
                                    <select name="mini[]" id="mini" class="select2 form-control" multiple>
                                        <?php $__currentLoopData = \App\Models\miniCategory::where('status', true)->get(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($category->id); ?>"><?php echo e($category->name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="form-group col-md-12">
                                    <label for="extra" class="text-capitalize">Extra Mini Category</label>
                                    <select name="extra[]" class="select2 form-control" id="extra" multiple>
                                        <?php $__currentLoopData = \App\Models\ExtraMiniCategory::where('status', true)->get(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($category->id); ?>"><?php echo e($category->name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>



                                <?php $__env->startPush('js'); ?>
                                    <script src="https://code.jquery.com/ui/1.13.3/jquery-ui.js"></script>
                                    <script>
                                        // Global sectionSort object to store the sortable items' data
                                        var sectionSort = <?php echo json_encode($section_sort); ?>;

                                        // Function to update the hidden input value
                                        function updateHiddenInput() {
                                            $('#section_sort').val(JSON.stringify(sectionSort));
                                        }

                                        // Function to convert category name to "Name_With_Underscores"
                                        function formatCategoryName(name) {
                                            return name.trim().replace(/\s+/g, '_');
                                        }

                                        // Function to add category to sortable <ul> and sectionSort object (with status and remove button)
                                        function addCategoryToSortable(id, name, catType) {
                                            const sortable = document.getElementById('sortable');
                                            const formattedName = formatCategoryName(name);

                                            // Check if the item is already added to avoid duplicates
                                            if (!sortable.querySelector(`[data-cat_id="${id}"][data-cat_type="${catType}"]`)) {
                                                const li = document.createElement('li');
                                                li.className = 'sort_item d-flex justify-content-between cursor-pointer py-2 px-2 bg-light border ui-sortable-handle';
                                                li.setAttribute('data-serial', id);
                                                li.setAttribute('data-name', formattedName);
                                                li.setAttribute('data-cat_type', catType);
                                                li.setAttribute('data-cat_id', id);
                                                li.setAttribute('data-status', 1);  // Default to 'Show'

                                                // Add section with status toggle and remove buttons
                                                li.innerHTML = `<span><i class="fa fa-bars" aria-hidden="true"></i>&nbsp;&nbsp;${name}</span>
                                                                <div class="action-buttons">
                                                                    <button class="status-toggle-btn btn btn-sm btn-warning">Hide</button>
                                                                    <button class="remove-btn btn btn-danger btn-sm">Remove</button>
                                                                </div>`;

                                                sortable.appendChild(li);

                                                // Add the new category to the sectionSort object
                                                sectionSort[formattedName] = {
                                                    'status': 1,  // Default to show
                                                    'order': Object.keys(sectionSort).length + 1,  // Assign order dynamically
                                                    'view': 'frontend.partial.index.default_cat',  // Placeholder for new categories
                                                    'cat_type': catType,
                                                    'cat_id': id
                                                };

                                                // Update hidden input value
                                                updateHiddenInput();
                                            }
                                        }

                                        // Listen for changes on the mega category <select>
                                        document.getElementById('mega').addEventListener('change', function () {
                                            const selectedOptions = this.selectedOptions;
                                            for (let option of selectedOptions) {
                                                addCategoryToSortable(option.value, option.text, 'mega');
                                            }
                                        });

                                        // Listen for changes on the sub category <select>
                                        document.getElementById('sub').addEventListener('change', function () {
                                            const selectedOptions = this.selectedOptions;
                                            for (let option of selectedOptions) {
                                                addCategoryToSortable(option.value, option.text, 'sub_cat');
                                            }
                                        });

                                        // Listen for changes on the mini category <select>
                                        document.getElementById('mini').addEventListener('change', function () {
                                            const selectedOptions = this.selectedOptions;
                                            for (let option of selectedOptions) {
                                                addCategoryToSortable(option.value, option.text, 'mini_cat');
                                            }
                                        });

                                        // Listen for changes on the extra category <select>
                                        document.getElementById('extra').addEventListener('change', function () {
                                            const selectedOptions = this.selectedOptions;
                                            for (let option of selectedOptions) {
                                                addCategoryToSortable(option.value, option.text, 'extra_cat');
                                            }
                                        });

                                        // Enable sorting and update the sectionSort object with new order
                                        $(document).ready(function() {
                                            $("#sortable").sortable({
                                                update: function(event, ui) {
                                                    var newSortOrder = {};

                                                    $("#sortable").children().each(function(index) {
                                                        var sectionName = $(this).data("name");
                                                        var order = index + 1;
                                                        var status = $(this).data("status");

                                                        var sectionData = {
                                                            'status': status,  // Maintain the current status
                                                            'order': order,
                                                            'view': sectionSort[sectionName]?.view || 'frontend.partial.index.default_view'  // Default view fallback
                                                        };

                                                        if ($(this).data('cat_type') && $(this).data('cat_id')) {
                                                            sectionData.cat_type = $(this).data('cat_type');
                                                            sectionData.cat_id = $(this).data('cat_id');
                                                        }

                                                        newSortOrder[sectionName] = sectionData;
                                                    });

                                                    sectionSort = newSortOrder;
                                                    updateHiddenInput();
                                                }
                                            });

                                            // Remove button functionality (only for categories)
                                            $(document).on('click', '.remove-btn', function() {
                                                const li = $(this).closest('li');
                                                const sectionName = li.data('name');

                                                // Only remove if the element has a cat_type (i.e., a category)
                                                if (li.data('cat_type')) {
                                                    delete sectionSort[sectionName];
                                                    li.remove();
                                                    updateHiddenInput();
                                                }
                                            });

                                            // Status toggle button functionality
                                            $(document).on('click', '.status-toggle-btn', function() {
                                                const li = $(this).closest('li');
                                                const sectionName = li.data('name');
                                                const currentStatus = sectionSort[sectionName]['status'];

                                                // Toggle status between 0 (hide) and 1 (show)
                                                const newStatus = currentStatus === 1 ? 0 : 1;

                                                // Update the button's text and style based on the new status
                                                $(this).toggleClass('btn-warning btn-success').text(newStatus === 1 ? 'Hide' : 'Show');

                                                // Update the status in both the li element and sectionSort object
                                                li.attr('data-status', newStatus);
                                                sectionSort[sectionName]['status'] = newStatus;

                                                // Update hidden input value
                                                updateHiddenInput();
                                            });
                                        });
                                    </script>
                                <?php $__env->stopPush(); ?>
                            </div>
                        </div>
                        
                    </div>
                </div>
                
                <div class="card-footer sticky_btn position-sticky fixed-bottom float-right text-right">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-arrow-circle-up"></i>
                        Update
                    </button>
                </div>
            </div>
        </form>
    </section>
<?php $__env->stopSection(); ?>


<?php echo $__env->make('layouts.admin.e-commerce.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/apleusbj/public_html/resources/views/admin/e-commerce/home-setting.blade.php ENDPATH**/ ?>