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

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

        .image-preview img, .imagePreview img {
            width: 100%;
            height: 309px;
            object-fit: cover;
            border-radius: 10px;
        }

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

        .dragging {
            border: 2px dashed #999;
            background: #f0f0f0;
        }
        .imagePreview{
            position: relative;
        }
        .bsi{
            position: relative;
        }
        #business_image {
            position: absolute;
            opacity: 0;
            width: 100%;
            height: 100%;
        }
        .close-upload-item.remove_business_image a img{
            width: 30px;
            height:30px;
        }
    </style>
    <div class="middle-part-wrap small-business-page-wrap">
        <form id="smallBusinessPartnersForm" enctype="multipart/form-data">
            <?php echo csrf_field(); ?>
            <input type="hidden" name="id" id="id"
                value="<?php echo e(!empty($businessDetails) && !empty($businessDetails->id) ? $businessDetails->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>
                            <?php
                                $videoVisible =
                                    !empty($businessDetails) &&
                                    $businessDetails->fileType == 2 &&
                                    !empty($businessDetails->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($businessDetails) && $businessDetails->fileType == 2 && !empty($businessDetails->filePath) ? 'none' : ''); ?>;">
                                    </a>
                                    <input type="file" id="video-file" name="video" accept="video/*"
                                        data-value="<?php echo e(!empty($businessDetails) && $businessDetails->fileType == 2 && !empty($businessDetails->filePath) ? $businessDetails->filePath : ''); ?>"
                                        style="display:none;"
                                        class="file_upload">
                                </div>
                                <div class="uploader-text"
                                    style="display:<?php echo e(!empty($businessDetails) && $businessDetails->fileType == 2 && !empty($businessDetails->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($businessDetails) && $businessDetails->fileType == 2): ?> src="<?php echo e(getMedia($businessDetails->filePath)); ?>" <?php endif; ?>
                                        controls id="video-preview"></video>
                                </div>
                            </div>
                        </div>
                        <div class="saprator">
                            <p>OR</p>
                        </div>
                        <div class="header-page-top-section-detail-right">
                            <h4>Header Image</h4>
                            <?php
                                $imageVisible =
                                    !empty($businessDetails) &&
                                    $businessDetails->fileType == 1 &&
                                    !empty($businessDetails->filePath)
                                        ? ''
                                        : 'none';
                            ?>
                            <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')); ?>"
                                            style="display:<?php echo e(!empty($businessDetails) && $businessDetails->fileType == 1 && !empty($businessDetails->filePath) ? 'none' : ''); ?>;">
                                    </a>
                                    <input type="file" id="image-file" name="image" accept="image/*"
                                        data-value="<?php echo e(!empty($businessDetails) && $businessDetails->fileType == 1 && !empty($businessDetails->filePath) ? $businessDetails->filePath : ''); ?>"
                                        style="display:none;" class="file_upload">
                                </div>
                                <div class="uploader-text"
                                    style="display:<?php echo e(!empty($businessDetails) && $businessDetails->fileType == 1 && !empty($businessDetails->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($businessDetails) && $businessDetails->fileType == 1 && !empty($businessDetails->filePath)): ?> src="<?php echo e(getMedia($businessDetails->filePath)); ?>" <?php endif; ?>
                                        id="image-preview">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="add-new-service-detail-bottom">
                        <div class="add-new-service-detail-bottom-box">
                            <h4>Header Title</h4>
                            <div class="form-group">
                                <input type="text" name="title" class="form-control" id="pageTitle"
                                    value="<?php echo e(!empty($businessDetails) && !empty($businessDetails->title) ? $businessDetails->title : ''); ?>"
                                    placeholder="Enter page title.">
                            </div>
                        </div>
                        <div class="add-new-service-detail-bottom-box mt-2">
                            <h4>Header TagLine</h4>
                            <div class="form-group">
                                <input type="text" name="tagLine" class="form-control" id="tagLine"
                                    value="<?php echo e(!empty($businessDetails) && !empty($businessDetails->tagLine) ? $businessDetails->tagLine : ''); ?>"
                                    placeholder="Enter page tagline.">
                            </div>
                        </div>
                    </div>

                    <div class="header-page-top-section">
                        <div class="header-page-top-section-detail-right">
                            <div class="header-page-middle-section-detail">
                                <h4>Small Business Overview</h4>
                                <div class="form-group">
                                    <textarea class="form-control required" placeholder="Enter Small Business Overview." id="businessOverview" name="businessOverview"><?php echo e(!empty($businessDetails) && !empty($businessDetails->businessOverview) ? $businessDetails->businessOverview : ''); ?></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="header-page-top-section-detail-left ">
                            <h4>Business Image</h4>
                            <div class="bsi">
                                <input type="file" id="business_image" name="business_image" accept="image/*"
                                        data-value="<?php echo e(!empty($businessDetails) && !empty($businessDetails->business_image) ? $businessDetails->business_image : ''); ?>"
                                        >
                                <div class="uploader-wrap" id="businessImage" style="display:<?php echo e(!empty($businessDetails) && !empty($businessDetails->business_image) ? 'none' : ''); ?>">
                                    <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 class="imagePreview" style="display:<?php echo e(!empty($businessDetails) && !empty($businessDetails->business_image) ? '' : 'none'); ?>">
                                    <img src="<?php echo e(getMedia($businessDetails->business_image)); ?>" id="imagePreview">
                                    <div class="close-upload-item remove_business_image">
                                        <a href="#"><img src="<?php echo e(asset('images/close.png')); ?>"></a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="submit-button">
                    <button type="submit" class="submit-btn"
                        id="submitBtn"><?php echo e(!empty($businessDetails) && !empty($businessDetails->id) ? 'Update' : 'Add'); ?></button>
                </div>
            </div>
        </form>
    </div>
    <script type="text/javascript" src="<?php echo asset('js/tinymce.min.js'); ?>"></script>
    <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;
        var currentUrl = window.location.pathname.replace("/", "");
        $(document).ready(function() {
            $('input:not([type="file"])').addClass('removeSameValueAndSpace');
            $('#pageTitle').addClass('required');
            $('#tagLine').addClass('required');
            $('textarea').addClass('removeSameValueAndSpace').addClass('required');
            activeLi('contracting');
            if (currentUrl.includes("small-business-partners")) {
                $('#small-business-partners').addClass("active");
            }
            $('textarea').addClass('removeSameValueAndSpace');
            $('#smallBusinessPartnersForm').validate({
                rules: {
                    title: {
                        required: true
                    },
                    tagLine:{
                        required: true
                    },
                    businessOverview: {
                        required: true
                    }
                },
                messages: {
                    title: {
                        required: "Please enter a title."
                    },
                    tagLine: {
                        required: "Please enter a tagline."
                    },
                    businessOverview: {
                        required: "Please enter a overview."
                    }
                },
                submitHandler: function(form) {}
            });

            $(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', '.file_upload', 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();
                        } 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: ''
                };
            }

            $(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).attr('data-type');
                    const mockEvent = {
                        target: {
                            files: [file]
                        }
                    };
                    handleFileUpload(mockEvent, type, `${type}-preview`);
                }
            });
        });


        $('#smallBusinessPartnersForm').on('submit', function(event) {
            event.preventDefault();
            var formData = new FormData($('#smallBusinessPartnersForm')[0]);
            var isFormValid = true;
            if (!$('#pageTitle').valid() || !$('#businessOverview').valid() || !$('#tagLine').valid()) {
                isFormValid = false;
                return;
            }
            videoFile = videoElement.attr('data-value');
            imageFile = imageElement.attr('data-value');
            if (!videoFile && !imageFile) {
                displayMessageModal('Please upload at least one video or one image file.',
                    'error');
                isFormValid = false;
                return;
            }
            if (!validateEditorValue('businessOverview')) {
                isValid = false;
                return;
            }
            var businessOverviewContent = tinymce.get('businessOverview').getContent();
            if (!businessOverviewContent || businessOverviewContent.trim() === '') {
                displayMessageModal('Please enter a description.', 'error');
                isFormValid = false;
                return;
            }
            if(!$("#business_image").attr('data-value')){
                displayMessageModal('Please select a business image file.', 'error');
                isFormValid = false;
                return;
            }
            formData.append('businessOverview', businessOverviewContent);
            if (isFormValid) {
                var url = "<?php echo e(url('admin/contracting/saveSmallBusinessDetails')); ?>";
                $('body').prepend('<div class="loader"></div>');
                if (videoFile) {
                    originalFileName = videoElement.attr('data-filename');
                    formData.append('video', videoFile);
                    formData.append('fileType', 'video');
                } else if (imageFile) {
                    originalFileName = imageElement.attr('data-filename');
                    formData.append('image', imageFile);
                    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 tinyEditor(selector) {
            $('body').prepend('<div class="loader"></div>');
            tinymce.init({
                selector: `#${selector}`,
                height: 500,
                plugins: [
                    "advlist autolink link image lists charmap print preview hr anchor pagebreak",
                    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
                    "table emoticons template paste help directionality",
                    "charmap quickbars colorpicker textcolor autosave",
                ],
                toolbar: [
                    "undo redo | styleselect | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist | forecolor backcolor",
                    "outdent indent| fontselect fontsizeselect formatselect | link image media emoticons | fullscreen preview",
                    "table | hr pagebreak | code | insertdatetime anchor nonbreaking charmap",
                    "searchreplace visualblocks visualchars | removeformat | directionality ltr rtl | help",
                ].join(" | "),
                menubar: "file edit view insert format tools table help",
                branding: false,
                autosave_ask_before_unload: true,
                toolbar_mode: "sliding",
                visual: true,
                setup: (editor) => {
                    editor.on("init", () => {
                        const value = $(`#${selector}`).data("value");
                        if (value) {
                            editor.setContent(value);
                        }
                        $(".tox-promotion-link").remove();
                        $(".loader").remove();
                    });
                },
            });
        }
        
        tinyEditor("businessOverview");
        function validateEditorValue(selector) {
            const value = tinymce.get(`${selector}`).getContent();
            if (!value || value.trim() === "") {
                displayMessageModal(
                    `Please enter a description.`,
                    "error"
                );
                return false;
            }
            return true;
        }

        $(document).on('click', '#businessImage', function(){
            $('#business_image').click();
        });
        $(document).on('change', '#business_image', function(){
            var $this = $(this);
            var imageFile = this.files[0];
            let checkMedia = validateMedia(imageFile, 'image');
            if(checkMedia){
                var reader = new FileReader();
                reader.onload = function(e) {
                    $this.attr('data-value', e.target.result);
                    $('#businessImage').hide();
                    $("#imagePreview").attr('src', e.target.result)
                    $(".imagePreview").show();
                };
                reader.readAsDataURL(imageFile);
            }else{
                //console.log('checkMedia')
            }
        });
        $(document).on('click', '.remove_business_image', function(){
            $("#business_image").attr('src', '').attr('data-value', '');
            $(".imagePreview").hide();
            $('#businessImage').show();
        });
    </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/contracting/small-business/add.blade.php ENDPATH**/ ?>