<?php $__env->startSection('title', 'Home : Header'); ?>
<?php $__env->startSection('content'); ?>
<link rel="stylesheet" type="text/css" media="screen" href="<?php echo asset('plugin/swiper/swiper-bundle.min.css'); ?>">
<script type="text/javascript" src="<?php echo asset('plugin/swiper/swiper-bundle.min.js'); ?>"></script>
<style>
    .video-preview video {
        width: 100%;
        height: 309px;
        object-fit: cover;
    }
    .video-preview {
        height: 309px;
        width: 100%;
        position: relative;
    }
    .image-preview img {
        width: 100%;
        object-fit: contain;
    }
    .image-preview {
        height: 309px;
        width: 100%;
    }
    .header-slider .close-upload-item {
        top: 3px;
        right: 3px;
        width: 20px;
        height: 20px;
    }
    .header-slider .image-preview{
        height: 92px;
    }
    .header-slider .image-preview img{
        height: 92px;
        border-radius: 10px;
        object-fit: cover;
    }
</style>
<div class="middle-part-wrap">
    <div class="header-page-wrap">
        <form id="headerForm" enctype="multipart/form-data">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="id" id="id" value="<?php echo e(!empty($details) && !empty($details->id) ? $details->id : ''); ?>">
            <div class="header-page-detail">
                <div class="scroll">
                    <div class="header-page-top-section">
                        <div class="header-page-top-section-detail-left">
                            <h4>Header Video</h4>
                            <input type="file" 
                                    id="video-file" 
                                    name="video" 
                                    accept="video/*"
                                    data-value="<?php if(!empty($details) && !empty($details->fileType) == 2): ?><?php echo e($details->filePath); ?><?php endif; ?>"
                                    style="display:none;"
                                    >
                            <div class="uploader-wrap file_upload" style="display:<?php if(!empty($details) && $details->fileType == 2): ?>none <?php endif; ?>">
                                <div class="uploader-button">
                                    <a href="#"><img src="<?php echo e(asset('images/play-icon.png')); ?>"></a>
                                </div>
                                <div class="uploader-text">
                                    <p>Upload MP4 video (under <?php echo e(config('app.videoMaxSize')); ?>MB).</p>
                                </div>
                            </div>
                            <div class="video-preview" style="display:<?php if(!empty($details) && $details->fileType == 2): ?> '' <?php else: ?> none <?php endif; ?>">
                                <?php if(!empty($details) && !empty($details->fileType) == 2): ?>
                                    <video controls src="<?php echo e(getMedia($details->filePath)); ?>" width="100%" height="373">

                                    </video>
                                    <div class="close-upload-item delete-video-icon">
                                        <a href="#"><img src="<?php echo e(asset('images/close_icon.png')); ?>"></a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="saprator">
                            <p>OR</p>
                        </div>
                        <!-- header-image-small-uploader -->
                        <div class="header-page-top-section-detail-right <?php if(!empty($details) && $details->fileType == 1): ?>header-image-small-uploader <?php endif; ?>">
                            <h4>Header Image</h4>
                            <div class="header-slider" style="display:<?php if(empty($details) || $details->fileType == 2): ?> none <?php endif; ?>">
                                <div class="swiper mySwiper">
                                    <div class="swiper-wrapper">
                                        <?php if(!empty($details) && $details->fileType == 1): ?>
                                            <?php $__currentLoopData = $images; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <div class="swiper-slide">
                                                <div class="close-upload-item delete_image" data-id="<?php echo e($value->id); ?>">
                                                    <a href="javascript:void(0);"><img src="<?php echo e(asset('images/close_icon.png')); ?>"></a>
                                                </div>
                                                <div class="image-preview hero-image-preview">
                                                    <img src="<?php echo e(getMedia($value->filePath)); ?>" alt="Uploaded Image">                                                
                                                </div>
                                            </div>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php endif; ?>
                                    </div>
                                    <div class="swiper-button-next"></div>
                                    <div class="swiper-button-prev"></div>
                                </div>
                            </div>
                            <input type="file" 
                                    id="image-file" 
                                    name="images[]" 
                                    multiple 
                                    accept="image/*"
                                    style="display:none;"
                                    >
                            <div class="uploader-wrap file_upload">
                                <div class="uploader-button">
                                    <a href="#"><img src="<?php echo e(asset('images/image-icon.png')); ?>"></a>
                                </div>
                                <div class="uploader-text">
                                    <p>Upload PNG or JPEG image (under <?php echo e(config('app.imageMaxSize')); ?>MB).</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="header-page-middle-section">
                        <div class="header-page-middle-section-detail">
                            <h4>Tag Line</h4>
                            <div class="form-group">
                                <textarea class="form-control required" placeholder="Enter tag line here." id="tagLine" name="tagLine"><?php echo e(!empty($details) && !empty($details->tagLine) ? $details->tagLine : ''); ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="submit-button">
                    <button type="submit" class="submit-btn" id="submitBtn"><?php echo e(!empty($details) && !empty($details->id) ? 'Update' : 'Add'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>
<?php $__env->stopSection(); ?>
<?php $__env->startSection('scripts'); ?>
<script type="text/javascript">

    var swiper = new Swiper(".mySwiper", {
        slidesPerView: 3,
        spaceBetween: 21,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
    });
    var imageArrayIndex = 0;
    var imgWrap = "";
    var selectedImages = [];
    var deleteImageIds = [];
    $(document).ready(function() {
        activeLi('home');
        $.validator.addMethod("noSpaces", function(value, element) {
            return $.trim(value) !== "";
        }, "This field is required and can not contain only spaces");
        $('#headerForm').validate({
            rules: {
                tagLine: {
                    required: true,
                    noSpaces: true
                }
            },
            submitHandler: function(form) {
                saveHeader();
            }
        });
        $(document).on('click', '.file_upload', function(){
            var $this = $(this);
            let fileType = $this.parent().find('input').attr('name');
            if(fileType == 'video'){
                let imageLength = $(".swiper-wrapper").children('.swiper-slide').length;
                if(imageLength > 0){
                    displayMessageModal(`Please remove existing slider images before add video.`, 'error');
                    return false
                }
            }else{
                if($("#video-file").attr('data-value')){
                    displayMessageModal(`Please remove existing video before add slider images.`, 'error');
                    return false;
                }
            }
            $this.parent().find('input').click();

        });
        $(document).on('change', '#video-file', function(){
            var $this = $(this);
            var videoFile = this.files[0];
            let checkMedia = validateMedia(videoFile, 'video');
            if(checkMedia){
                var reader = new FileReader();
                reader.onload = function(e) {
                    $this.attr('data-value', e.target.result);
                    $this.parent().find('.uploader-wrap').hide();
                    let html = `<video controls src="${e.target.result}" width="100%" height="373"></video>
                                <div class="close-upload-item delete-video-icon">
                                                <a href="#"><img src="<?php echo e(asset('images/close_icon.png')); ?>"></a>
                                            </div>`;
                    $('.video-preview').html(html).show();
                };
                reader.readAsDataURL(videoFile);
            }else{
                console.log('checkMedia')
            }
            
        });
        $(document).on('click', '.delete-video-icon', function(event) {
            var $this = $(this);
            $('#video-file').val('').attr('data-value', '');
            $this.parent().parent().find('.uploader-wrap').show();
            $('.video-preview').html('').hide();
        });
        
        $(document).on('change', '#image-file', function(e){
            var $this = $(this);
            var imageArray = [];
            var maxLength = 20 - $(".swiper-wrapper").children('.swiper-slide').length;
            imgWrap = $(this).parent().find('.swiper-wrapper');
            var files = [...e.target.files];
            var imageSelect = true;
            $.each(files, function(key, value) { 
                let checkFile = validateMedia(value, 'image');
                if(checkFile){
                    imageArray.push(value);
                }else{
                    imageSelect = false;
                }
            });
            if (imageSelect == true) {
                imageArray = imageArray.slice(0, maxLength);
                if (imageArray.length) {
                    selectedImages.push(...imageArray);
                    renderImages(imageArray);
                }
            }
            e.target.value = ''
        });
        function generateRandomString(length = 5) {
            return Math.random().toString(36).substring(2, 2 + length);
        }
        async function renderImages(imageArray) {
            for (let index = 0; index < imageArray.length; index++) {
                const file = imageArray[index];
                const randomString = generateRandomString();
                const uniqueFileName = `${file.name}_${randomString}`;
                var html = `<div class="swiper-slide">
                                <input type="hidden" name="images[${index}][image]">
                                <div class="close-upload-item delete_image" data-id="0" data-name="${uniqueFileName}">
                                    <a href="javascript:void(0);"><img src="<?php echo e(asset('images/close_icon.png')); ?>"></a>
                                </div>
                                <div class="image-preview hero-image-preview">
                                    <img src="${URL.createObjectURL(file)}" alt="Uploaded Image">                                                
                                </div>
                            </div>`;
                imgWrap.append(html);
                swiper.update();
                swiper.slideTo($(".swiper-wrapper").children('.swiper-slide').length - 1);
            }
            
            if($(".swiper-wrapper").children('.swiper-slide').length > 0){
                $('.header-page-top-section-detail-right').addClass('header-image-small-uploader');
                $('.header-slider').show();
            }
        }

        $(document).on('click', '.delete_image', function(){
            if($(this).attr('data-id') != 0){
                deleteImageIds.push($(this).attr('data-id'));
            }else{
                var imageName = $(this).data('name');
                var index = selectedImages.findIndex(function(image) {
                    const randomString = imageName.split('_').pop();
                    return `${image.name}_${randomString}` === imageName;
                });
                if (index !== -1) {
                    selectedImages.splice(index, 1);
                }
            }
            $(this).closest('.swiper-slide').remove();
            if($(".swiper-wrapper").children('.swiper-slide').length == 0){
                $('.header-slider').hide();
                $('.header-image-small-uploader').removeClass('header-image-small-uploader');
            }
        });
    });
    function saveHeader(){

        if( $("#video-file").attr('data-value') == '' && $(".swiper-wrapper").children('.swiper-slide').length == 0){
            displayMessageModal('Please upload at least one video or slider images.','error');
            return false;
        }else{
            var formData = new FormData($('#headerForm')[0]);
            if(selectedImages.length){
                selectedImages.forEach((file, index) => {
                    formData.append(`images[${index}][image]`, file);
                });
            }
            if(deleteImageIds.length){
                formData.append('deleteImageIds', JSON.stringify(deleteImageIds));
            }
            $('button[type="submit"]').attr('disabled', 'disabled').css('cursor', 'not-allowed');
            $('body').prepend('<div class="loader"></div>');
            $.ajax({
                url: "<?php echo e(url('admin/home/header/save')); ?>",
                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');
                    $('.closeBtn').attr('disabled', 'disabled');
                    displayMessageModal(response.message, 'success');
                    setTimeout(() => {
                        location.reload(true);
                    }, 2000);
                },
                error: function(error) {
                    $('.loader').remove();
                    $('button[type="submit"]').removeAttr('disabled').css('cursor', 'pointer');
                    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/header.blade.php ENDPATH**/ ?>