<?php $__env->startSection('title', 'Home : Header'); ?>
<?php $__env->startSection('content'); ?>
    <style>
        .video-preview video {
            width: 100%;
            height: 309px;
            object-fit: cover;
        }

        .video-preview {
            height: 309px;
            width: 100%;
        }

        .image-preview img {
            width: 100%;
            /* height: 309px; */
            object-fit: contain;
        }

        .image-preview {
            height: 309px;
            width: 100%;
        }

        .dragging {
            border: 2px dashed #999;
            background: #f0f0f0;
        }

        .header-slider .close-upload-item {
            top: -3px;
            right: 0;
            width: 20px;
            height: 20px;
        }
        .header-slider .image-preview{
            height: 92px;
        }
        .header-slider .image-preview img{
            height: 92px;
            border-radius: 10px;
            object-fit: cover;
        }
    </style>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
    <div class="middle-part-wrap">
        <form id="headerForm" enctype="multipart/form-data">
            <?php echo csrf_field(); ?>
            <input type="hidden" name="id" id="id"
                value="<?php echo e(!empty($headerDetails) && !empty($headerDetails->id) ? $headerDetails->id : ''); ?>">
            <div class="header-page-detail home-header-page-wrap">
                <div class="scroll">
                    <div class="header-page-top-section">
                        <div class="header-page-top-section-detail-left">
                            <h4>Header Video</h4>
                            <?php
                                $videoVisible =
                                    !empty($headerDetails) &&
                                    $headerDetails->fileType == 2 &&
                                    !empty($headerDetails->filePath)
                                        ? ''
                                        : 'none';
                            ?>
                            <div class="uploader-wrap" id="video-upload" data-type="video">
                                <div class="uploader-button upBtnVideo">
                                    <a href="javascript:void(0);" class="file-input" data-type="video">
                                        <img src="<?php echo e(asset('images/play-icon.png')); ?>"
                                            style="display:<?php echo e(!empty($headerDetails) && $headerDetails->fileType == 2 && !empty($headerDetails->filePath) ? 'none' : ''); ?>;">
                                    </a>
                                    <input type="file" id="video-file" name="video" accept="video/*"
                                        data-value="<?php echo e(!empty($headerDetails) && $headerDetails->fileType == 2 && !empty($headerDetails->filePath) ? $headerDetails->filePath : ''); ?>"
                                        style="display:none;">
                                </div>
                                <div class="uploader-text"
                                    style="display:<?php echo e(!empty($headerDetails) && $headerDetails->fileType == 2 && !empty($headerDetails->filePath) ? 'none' : ''); ?>;">
                                    <p>Upload video (under <?php echo e(config('app.videoMaxSize')); ?>MB).</p>
                                </div>
                                <div class="close-upload-item">
                                    <a href="javascript:void(0);" class="remove-video"
                                        style="display:<?php echo e($videoVisible); ?>;"><img src="<?php echo e(asset('images/close.png')); ?>"></a>
                                </div>
                                <div class="video-preview" style="display:<?php echo e($videoVisible); ?>;">
                                    <video
                                        <?php if(!empty($headerDetails) && $headerDetails->fileType == 2): ?> src="<?php echo e(getMedia($headerDetails->filePath)); ?>" <?php endif; ?>
                                        controls id="video-preview"></video>
                                </div>
                            </div>
                        </div>
                        <div class="saprator">
                            <p>OR</p>
                        </div>
                        <div id="headerRightSection" class="header-page-top-section-detail-right">
                            <h4>Header Image</h4>
                            <div class="header-slider" style="display: none;" id="sliderDiv">
                                <div class="swiper mySwiper">
                                    <div class="swiper-wrapper">
                                    </div>
                                    <div class="swiper-button-next"></div>
                                    <div class="swiper-button-prev"></div>
                                </div>
                            </div>
                            <?php
                                $imageVisible =
                                    !empty($headerDetails) &&
                                    $headerDetails->fileType == 1 &&
                                    !empty($headerDetails->filePath)
                                        ? ''
                                        : 'none';
                            ?>
                            <div class="uploader-wrap" id="image-upload" data-type="image">
                                <div class="uploader-button">
                                    <a href="javascript:void(0);" class="uploadImages" data-type="image">
                                        <img src="<?php echo e(asset('images/image-icon.png')); ?>"
                                            style="display:<?php echo e(!empty($headerDetails) && $headerDetails->fileType == 1 && !empty($headerDetails->filePath) ? 'none' : ''); ?>;">
                                    </a>
                                    <input type="file" id="fileUploader" name="image" accept="image/*"
                                        data-value="<?php echo e(!empty($headerDetails) && $headerDetails->fileType == 1 && !empty($headerDetails->filePath) ? $headerDetails->filePath : ''); ?>"
                                        style="display:none;" multiple>
                                </div>
                                <div class="uploader-text"
                                    style="display:<?php echo e(!empty($headerDetails) && $headerDetails->fileType == 1 && !empty($headerDetails->filePath) ? 'none' : ''); ?>;">
                                    <p>Upload 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:<?php echo e($imageVisible); ?>;"><img
                                            src="<?php echo e(asset('images/close.png')); ?>"></a>
                                </div>
                                <div class="image-preview" style="display:<?php echo e($imageVisible); ?>;">
                                    <img <?php if(!empty($headerDetails) && $headerDetails->fileType == 1 && !empty($headerDetails->filePath)): ?> src="<?php echo e(getMedia($headerDetails->filePath)); ?>" <?php endif; ?>
                                        id="image-preview">
                                </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($headerDetails) && !empty($headerDetails->tagLine) ? $headerDetails->tagLine : ''); ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="submit-button">
                    <button type="submit" class="submit-btn"
                        id="submitBtn"><?php echo e(!empty($headerDetails) && !empty($headerDetails->id) ? 'Update' : 'Add'); ?></button>
                </div>
            </div>
        </form>
    </div>

    <script type="text/javascript">
        var videoElement = $('#video-file');
        var imageElement = $('#image-file');
        var videoFile = null;
        var imageFile = null;
        var originalFileName = null;
        var errorMessage = '';
        var isFileValid = false;

        //for slider
        var mediaPath = "<?php echo e(config('app.AWS_S3_URL')); ?>";
        var sliderImages = [];
        var removeSliderImages = [];
        var heroImages = <?php echo json_encode($heroImages, 15, 512) ?>;

        var swiper = new Swiper(".mySwiper", {
            slidesPerView: 3,
            spaceBetween: 21,
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
        });
        loadSliderImages();
        $(document).ready(function() {
            activeLi('home');
            $('textarea').addClass('removeSameValueAndSpace');
            $('#headerForm').validate({
                rules: {
                    tagLine: {
                        required: true
                    }
                },
                messages: {
                    tagLine: {
                        required: "Please enter a tagline."
                    }
                },
                submitHandler: function(form) {}
            });

            $(document).on('click', '.file-input', function(event) {                
                event.stopPropagation();
                if(sliderImages.length > 0){
                    displayMessageModal(`Please remove existing slider images before add video.`, 'error');
                    return;
                }
                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 validationResult = {
                    isFileValid: false,
                    errorMessage: ''
                };
                if (type === 'video') {
                    validationResult = validateVideoFile(file);
                } else if (type === 'image') {
                    validationResult = validateImageFile(file);
                }
                if (validationResult.isFileValid) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        if (type === 'video') {
                            $(`.${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);

                            $(`.file-input`).closest(`[data-type="image"]`).parent().next().find('p').parent()
                                .css('display', '');
                            $(`.file-input[data-type="image"]`).find('img').attr('src',
                                "<?php echo e(asset('images/image-icon.png')); ?>").show();
                            $(`#image-preview`).attr('src', "");
                            $(`.image-preview`).hide();
                            $(`#image-file`).val('');
                            $(`#image-file`).attr('data-value', "");
                            $(`#image-file`).attr('data-filename', "");
                            $(`#image-file`).prop('readonly', false);
                            $('.remove-image').hide();
                            $(`.file-input[data-type="image"]`).parent().show();
                        } else 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);
                            $(`.file-input`).closest(`[data-type="video"]`).parent().next().find('p').parent()
                                .css('display', '');
                            $(`.file-input[data-type="video"]`).find('img').attr('src',
                                "<?php echo e(asset('images/play-icon.png')); ?>").show();
                            $(`#video-preview`).attr('src', "");
                            $(`.video-preview`).hide();
                            $(`#video-file`).val('');
                            $(`#video-file`).attr('data-value', "");
                            $(`#video-file`).attr('data-filename', "");
                            $(`#video-file`).prop('readonly', false);
                            $('.upBtnVideo').show();
                            $('.remove-video').hide();
                        }
                    };
                    reader.readAsDataURL(file);
                } else {
                    displayMessageModal(validationResult.errorMessage, 'error');
                }
            }

            $(document).on('click', '.remove-video,.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();
            });

            function validateVideoFile(file) {
                const validTypes = [
                    'video/mp4',
                ];
                const maxSize = videoMaxSize * 1024 * 1024;

                if (!validTypes.includes(file.type)) {
                    return {
                        isFileValid: false,
                        errorMessage: 'Invalid video format. Allowed only mp4 video format.'
                    };
                }

                if (file.size > maxSize) {
                    return {
                        isFileValid: false,
                        errorMessage: `Video file size exceeds ${videoMaxSize}MB.`
                    };
                }

                return {
                    isFileValid: true,
                    errorMessage: ''
                };
            }

            function validateImageFile(file) {
                const validTypes = [
                    'image/png',
                    'image/jpeg',
                    'image/jpg',
                ];
                const maxSize = imageMaxSize * 1024 * 1024;

                if (!validTypes.includes(file.type)) {
                    return {
                        isFileValid: false,
                        errorMessage: 'Invalid image format. Allowed formats are png, jpg, jpeg.'
                    };
                }

                if (file.size > maxSize) {
                    return {
                        isFileValid: false,
                        errorMessage: `Image file size exceeds ${imageMaxSize}MB.`
                    };
                }

                return {
                    isFileValid: true,
                    errorMessage: ''
                };
            }
        });

        $('#headerForm').on('submit', function(event) {
            event.preventDefault();
            var isFormValid = true;
            if (!$('#tagLine').valid()) {
                isFormValid = false;
            }
            videoFile = videoElement.attr('data-value');
            if (!videoFile && sliderImages.length == 0) {
                displayMessageModal('Please upload at least one video or slider images.',
                    'error');
                isFormValid = false;
                return;
            }
            if (isFormValid) {
                var url = "<?php echo e(url('admin/saveHeaderDetails')); ?>";
                var formData = new FormData($('#headerForm')[0]);
                $('body').prepend('<div class="loader"></div>');
                if (videoFile) {
                    originalFileName = videoElement.attr('data-filename');
                    formData.append('video', videoFile);
                    formData.append('fileType', 'video');
                } else if (sliderImages.length > 0) {
                    formData.append('heroImages', JSON.stringify(sliderImages));
                    formData.append('deletedHeroImages', JSON.stringify(removeSliderImages));
                    formData.append('fileType', 'image');
                }
                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');
                        $('.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');
                    }
                });
            }
        });

        function truncateFileName(fileName, modalName = "") {
            const awsType = "<?php echo e(config('app.AWS_CONFIG.AWS_TYPE')); ?>";

            if (fileName.includes("/")) {
                const fileParts = fileName.split("/");
                const removeStrings = (awsType === "local") ?
                    `${fileParts[0]}/${fileParts[1]}/` :
                    `${fileParts[0]}/`;
                fileName = fileName.replace(removeStrings, "");
            }

            const lastDotIndex = fileName.lastIndexOf(".");
            if (lastDotIndex === -1) return fileName;

            const fileExtension = fileName.substring(lastDotIndex + 1);
            let nameWithoutExtension = fileName.substring(0, lastDotIndex).replace(/^\d+_/, "");

            const truncateLength = modalName === "errorModal" ? 20 : 40;
            const displayLength = modalName === "errorModal" ? 15 : 35;

            if (nameWithoutExtension.length > truncateLength) {
                nameWithoutExtension =
                    `${nameWithoutExtension.substring(0, displayLength)}.....${modalName != "errorModal" ? nameWithoutExtension.slice(-7) : nameWithoutExtension.slice(-3)}`;
            }

            return `${nameWithoutExtension}.${fileExtension}`;
        }


        function handleSliderFilesUpload(files) {
            $('body').prepend('<div class="loader"></div>');
            let errorIndex = 0;
            let errorMessages = '<p>Errors found from following uploaded files:</p>';
            errorMessages += '<p>Allowed image formats are png and jpg.</p>';
            console.log(files);
            $.each(files, function(index, file) {
                let validationErrors = validateSliderImageFile(file);
                let file_name = file.name.replace(/\s/g, "_");
                if (validationErrors.length > 0) {
                    errorIndex++;
                    if (errorIndex <= 5) {
                        errorMessages +=
                            `<tr><td>${errorIndex}</td><td>${truncateFileName(file_name,'errorModal')}</td><td>${validationErrors.join(', ')}</td></tr>`;
                    }
                } else {
                    $('#headerRightSection').addClass('header-image-small-uploader');
                    $('#sliderUploadDiv').hide();
                    $('#sliderDiv').show();
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        let slideId = `slide-${sliderImages.length}`;
                        let newSlide = `<div class="swiper-slide" id="${slideId}">
                                            <div class="close-upload-item">
                                                <a href="javascript:void(0);" class="remove-image remove-slider-image" data-id="${slideId}">
                                                    <img src="<?php echo e(asset('images/close.png')); ?>">
                                                </a>
                                            </div>
                                            <div class="image-preview hero-image-preview" data-id="${slideId}">
                <img src="${e.target.result}" data-id="${slideId}" alt="Uploaded Image">
            </div>
                                        </div>`;
                        $('.swiper-wrapper').prepend(newSlide);

                        sliderImages.push({
                            fileName: file_name,
                            filePath: e.target.result,
                            sliderId: slideId,
                            record_id: 0,
                            page: "home"
                        });
                        swiper.update();
                        swiper.slideTo(0, 0, false);
                    };
                    $('.loader').remove();
                    reader.readAsDataURL(file);
                }
            });
            if (errorMessages.includes('<tr>')) {
                $('.loader').remove();
                displayMessageModal(`
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">File Name</th>
                    <th scope="col">Error Message</th>
                </tr>
            </thead>
            <tbody id="errorMessages">${errorMessages}</tbody>
        </table>`, 'error');
            }
        }

        $(document).on('click', '.uploadImages', function(event) {
            event.stopPropagation();
            if(videoElement.attr('data-value')){
                displayMessageModal(`Please remove existing video before add slider images.`, 'error');
                return;
            }
            $('#fileUploader').click();
        });

        $(document).on('change', '#fileUploader', function(event) {
            event.stopPropagation();
            handleSliderFilesUpload(event.target.files);
            $(this).val('');
        });

        $(document).on('click', '.remove-slider-image', function(event) {
            event.stopPropagation();
            let slideId = $(this).data('id');
            $(`#${slideId}`).remove();
            let index = sliderImages.findIndex(img => img.sliderId === slideId);
            if (index > -1) {
                updateRemoveSliderImages(index);
                sliderImages.splice(index, 1);
            }
            if (!sliderImages.length) {
                $('#headerRightSection').removeClass('header-image-small-uploader');
                $('#sliderDiv').hide();
                $('#sliderUploadDiv').show();
            }
            swiper.update();
        });

        function updateRemoveSliderImages(sliderIndex) {
            if (Object.keys(heroImages).length > 0) {
                let imageToRemove = sliderImages[sliderIndex];
                $.each(heroImages, function(index, value) {
                    if (imageToRemove.record_id === value.id) {
                        removeSliderImages.push({
                            sliderId: imageToRemove.sliderId,
                            record_id: imageToRemove.record_id,
                            filePath: imageToRemove.filePath,
                            page: imageToRemove.page
                        });
                    }
                });
            }
        }

        function validateSliderImageFile(file) {
            const validTypes = [
                'image/png',
                'image/jpeg',
                'image/jpg'
            ];
            const maxSizeMB = imageMaxSize * 1024 * 1024;
            let errors = [];
            if (file.size > maxSizeMB) {
                errors.push(`File size exceeds ${imageMaxSize} MB`);
            }
            if (!validTypes.includes(file.type)) {
                errors.push(`Invalid image format.`);
            }
            return errors;
        }

        function loadSliderImages() {
            if (Object.keys(heroImages).length > 0) {
                $('body').prepend('<div class="loader"></div>');
                $('#headerRightSection').addClass('header-image-small-uploader');
                $('#sliderUploadDiv').hide();
                $('#sliderDiv').show();
                $.each(heroImages, function(index, value) {
                    let slideId = `slide-${index}`;
                    let recordId = value.id;
                    let file_name = value.filePath;
                    file_name = truncateFileName(file_name);

                    let newSlide = `<div class="swiper-slide" id="${slideId}">
                                            <div class="close-upload-item">
                                                <a href="javascript:void(0);" class="remove-image remove-slider-image" data-id="${slideId}">
                                                    <img src="<?php echo e(asset('images/close.png')); ?>">
                                                </a>
                                            </div>
                                            <div class="image-preview hero-image-preview" data-id="${slideId}">
                                                <img src="${mediaPath + value.filePath}" data-id="${slideId}" alt="Uploaded Image">                                                
                                            </div>
                                        </div>`;

                    $('.swiper-wrapper').prepend(newSlide);

                    sliderImages.push({
                        fileName: file_name,
                        filePath: value.filePath,
                        sliderId: slideId,
                        record_id: recordId ? recordId : 0,
                        page: "about-us"
                    });
                    swiper.update();
                });
                $('.loader').remove();
            } else {
                $('#sliderUploadDiv').show();
                $('#sliderDiv').hide();
            }
        }
    </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/home-header.blade.php ENDPATH**/ ?>