<?php $__env->startSection('title', 'Home : Markets'); ?>
<?php $__env->startSection('content'); ?>
    <style>
        .image-preview img#image-preview {
            height: 309px;
            object-fit: contain;
            width: 100%;
        }

        .market-list-right-detail-title-box .form-group .form-control {
            border-radius: 10px;
            background: rgba(60, 21, 50, 0.10);
            padding: 17px 28px;
            border: 0;
            outline: none;
            box-shadow: none;
            color: #474747;
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
            text-transform: capitalize;
        }

        .market-list-edit-button a.deleteBtn {
            padding: 5px 49px;
            margin-top: 10px;
        }
    </style>
    <div class="middle-part-wrap markets-page-wrap">
        <div class="market-list-wrap">
            <div class="top-title">
                <h3>Markets List</h3>
            </div>
            <div class="market-list-detail">
                <div class="market-list-detail-left">
                    <div class="market-list-detail-left-data"
                        <?php if(count($markets) == 0): ?> style="visibility: hidden;" <?php endif; ?>>
                        <?php if(count($markets) > 0): ?>
                            <ul>
                                <?php $__currentLoopData = $markets; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $market): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <li>
                                        <div class="market-list-data-wrap">
                                            <div class="market-list-data">
                                                <h5><?php echo e(@$market->title); ?></h5>
                                                <div class="market-list-text">
                                                    <div class="market-list-images">
                                                        <img
                                                            src="<?php echo e(config('app.AWS_CONFIG.AWS_S3_URL') . $market->filePath); ?>">
                                                    </div>
                                                    <div class="market-list-edit-button">
                                                        <a class="editBtn" href="javascript:void(0);"
                                                            data-id="<?php echo e(@$market->id); ?>"
                                                            data-filePath="<?php echo e(@$market->filePath); ?>"
                                                            data-title="<?php echo e(@$market->title); ?>">Edit</a>
                                                        
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </li>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="market-list-detail-right">
                    <form id="marketFrm" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="id" id="id">
                        <div class="market-list-detail-right-data">
                            <div class="market-list-right-data">
                                <div class="market-list-right-image">
                                    <div class="add-new-service-detail-top-left">
                                        <h4>Market Images</h4>
                                        <div class="uploader-wrap" id="image-upload" data-type="image">
                                            <div class="uploader-button">
                                                <a href="javascript:void(0);" class="file-input" data-type="image">
                                                    <img src="<?php echo e(asset('images/image-icon.png')); ?>" class="sampleImg">
                                                </a>
                                                <input type="file" id="image-file" name="image" accept="image/*"
                                                    data-value="" style="display:none;">
                                            </div>
                                            <div class="uploader-text">
                                                <p>Upload PNG or JPEG image (under <?php echo e(config('app.imageMaxSize')); ?>MB).</p>
                                            </div>
                                            <div class="close-upload-item">
                                                <a href="javascript:void(0);" class="remove-image" style="display: none;">
                                                    <img src="<?php echo e(asset('images/close.png')); ?>">
                                                </a>
                                            </div>
                                            <div class="image-preview">
                                                <img src="" id="image-preview">
                                            </div>
                                        </div>

                                    </div>
                                </div>
                                <div class="market-list-right-detail-title-box">
                                    <h4>Market Title</h4>
                                    <div class="form-group">
                                        <input type="text" class="form-control" placeholder="Enter tag line here."
                                            id="title" name="title" value="<?php echo e(@$marketsTagline); ?>">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="submit-button">
                            <button type="submit" class="submit-btn">ADD NOW</button>
                        </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        $('input[type=text]').addClass('removeSameValueAndSpace').addClass('required');
        var imageElement = $('#image-file');
        var imageFile = null;
        var originalFileName = null;
        var fileType = 'image';
        var currentUrl = window.location.pathname.replace("/", "");
        $(document).ready(function() {
            $('#image-preview').hide();
            activeLi('home');
            if (currentUrl.includes("market")) {
                $('#markets').addClass("active");
            }
            $('#marketFrm').validate({
                rules: {
                    title: {
                        required: true
                    }
                },
                messages: {
                    title: {
                        required: "Please enter a title."
                    }
                },
                submitHandler: function(form) {
                    headerSubmit();
                }
            });

            $(document).on('click', '.file-input', function(event) {
                event.stopPropagation();
                const type = $(this).data('type');
                $(`#${type}-file`).val('');  // Reset the file input value
                $(`#${type}-file`).click();
            });

            $(document).on('change', 'input[type="file"]', function(event) {
                event.stopPropagation();
                const type = $(this).attr('id').split('-')[0];
                handleFileUpload(event, type, `${type}-preview`);
            });


            function handleFileUpload(event, type, previewElement) {
                var file = event.target.files[0];
                if (!file) return;
                var fileName = file.name.replace(/\s/g, "_");
                var valid = false;
                var errorMessage = '';

                if (type === 'image') {
                    valid = validateImageFile(file);
                    if (!valid) {
                        errorMessage = `Invalid image file. Please ensure it is under ${imageMaxSize}MB and of valid format.`;
                    }
                }
                if (valid) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        if (type === 'image') {
                            $(`.${previewElement}`).show();
                            $(`.file-input`).closest(`[data-type="${type}"]`).parent().css('display', 'none');
                            $(`.file-input`).closest(`[data-type="${type}"]`).parent().next().find('p').parent()
                                .css('display', 'none');
                            $(`.${previewElement}`).parent().find('a').show();
                            $(`#${previewElement}`).attr('src', e.target.result);
                            $(`#${type}-file`).attr('data-value', e.target.result);
                            $(`#${type}-file`).attr('data-filename', fileName);
                            $(`#${type}-file`).prop('readonly', true);
                        }
                    };
                    reader.readAsDataURL(file);
                    $('#image-preview').show();
                } else {
                    displayMessageModal(errorMessage, 'error');
                }
            }

            function validateImageFile(file) {
                const validTypes = ['image/png', 'image/jpeg', 'image/gif'];
                const maxSize = imageMaxSize * 1024 * 1024;
                return validTypes.includes(file.type) && file.size <= maxSize;
            }

            $(document).on('dragover', '.uploader-wrap', function(event) {
                event.preventDefault();
                event.stopPropagation();
                $(this).addClass('dragging');
            });

            $(document).on('dragleave', '.uploader-wrap', function(event) {
                event.preventDefault();
                event.stopPropagation();
                $(this).removeClass('dragging');
            });

            $(document).on('drop', '.uploader-wrap', function(event) {
                event.preventDefault();
                event.stopPropagation();
                $(this).removeClass('dragging');
                const files = event.originalEvent.dataTransfer.files;
                if (files.length) {
                    const file = files[0];
                    const type = $(this).data('type');
                    const mockEvent = {
                        target: {
                            files: [file]
                        }
                    };
                    handleFileUpload(mockEvent, type, `${type}-preview`);
                }
            });
        });


        function headerSubmit() {
            event.preventDefault();
            var isValid = true;
            imageFile = imageElement.attr('data-value');
            console.log("i : " + imageFile);
            console.log("fileType : " + fileType);
            if (fileType == 'image') {
                if (imageFile == '' || imageFile == undefined) {
                    displayMessageModal('Please upload valid image file.', 'error');
                    isValid = false;
                    return;
                }
            }
            if (isValid) {
                var url = "<?php echo e(url('admin/saveMarkets')); ?>";
                var formData = new FormData($('#marketFrm')[0]);
                $('body').prepend('<div class="loader"></div>');
                if (imageFile) {
                    originalFileName = imageElement.attr('data-filename');
                    formData.append('image', imageFile);
                    formData.append('originalFileName', originalFileName);
                }            
                $('button[type="submit"]').attr('disabled', 'disabled').css('cursor', 'not-allowed');
                $.ajax({
                    url: url,
                    type: "POST",
                    cache: false,
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    data: formData,
                    success: function(response) {
                        $('.loader').remove();
                        $('button[type="submit"]').removeAttr('disabled').css('cursor', 'pointer');
                        displayMessageModal(response.message, 'success', 'selfReload');
                    },
                    error: function(error) {
                        $('.loader').remove();
                        $('button[type="submit"]').removeAttr('disabled').css('cursor', 'pointer');
                        displayMessageModal(error.responseJSON.message, 'error');
                    }
                });
            }
        }

        $(document).on('click', '.editBtn', function(event) {
            $('.submit-btn').text('UPDATE NOW');
            var $this = $(this);
            $('.sampleImg').css('display', 'none');
            $('.uploader-text').css('display', 'none');
            $('#image-file').attr('data-value', $this.attr('data-filePath'));
            $('#image-preview').attr('src', "<?php echo e(config('app.AWS_CONFIG.AWS_S3_URL')); ?>" + $this.attr(
                'data-filePath'));
            $('#id').val($this.attr('data-id'));
            $('.remove-image').css('display', '');
            $('#title').val($this.attr('data-title'));
            $('.image-preview').show();
            $('#image-preview').show();
        });

        $(document).on('click', '.remove-image', function(event) {
            event.stopPropagation();
            const uploaderWrap = $(this).closest('.uploader-wrap');
            const fileInput = uploaderWrap.find('input[type="file"]');
            const previewElement = `${uploaderWrap.attr('data-type')}-preview`;
            $(`.${previewElement}`).hide();
            $(`#${previewElement}`).attr('src', '');
            $(fileInput).parent().show();
            $(fileInput).closest('.file-input').show();
            $(fileInput).parent().find('img').show();
            $(fileInput).parent().next().find('p').parent().show();
            $(fileInput).attr('data-value', '');
            $(fileInput).attr('data-filename', '');
            $(fileInput).prop('readonly', false);
            $(this).hide();
        });

        /*$(document).on('click', '.deleteBtn', function(event) {
            e.preventDefault();
            $('.activeInactiveModal').modal('hide');
            var $this = $(this);
            var id = $this.attr('data-id');
            var url = "<?php echo e(url('admin/deleteService')); ?>";
            if (id) {
                $('body').prepend('<div class="loader"></div>');
                var formData = new FormData();
                var token = "<?php echo e(csrf_token()); ?>";
                formData.append('_token', token);
                formData.append('id', id);
                $.ajax({
                    url: url,
                    type: "POST",
                    cache: false,
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    data: formData,
                    success: function(response) {
                        $('.loader').remove();
                        $('html, body').animate({
                            scrollTop: $('body').offset().top
                        }, 300);
                        displayMessageModal(response.message, 'success', 'selfReload');
                    },
                    error: function(error) {
                        $('.loader').remove();
                        displayMessageModal(error.responseJSON.message, 'error');
                    }
                });
            }
        });*/
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /Applications/XAMPP/xamppfiles/htdocs/anser-backend/resources/views/home/markets.blade.php ENDPATH**/ ?>