<?php $__env->startSection('title', 'News : Add New'); ?>
<?php $__env->startSection('content'); ?>
    <link rel="stylesheet" type="text/css" href="<?php echo asset('plugin/datetimepicker/jquery.datetimepicker.css'); ?>">
    <style>
        .image-preview img {
            width: 100%;
            height: 309px;
            object-fit: contain;
        }

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

        .dragging {
            border: 2px dashed #999;
            background: #f0f0f0;
        }
    </style>
    <div class="middle-part-wrap news-add-page-wrap">
        <form id="addForm" 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="add-new-service">
                <div class="top-title">
                    <h3><?php echo e(!empty($details) && !empty($details->id) ? 'Updating' : 'Adding'); ?> News</h3>
                </div>
                <div class="add-new-service-wrap">
                    <div class="scroll">
                        <div class="add-new-service-detail">
                            <div class="add-new-service-detail-top">
                                <div class="add-new-service-detail-top-left">
                                    <h4>News Image</h4>
                                    <?php
                                        $imageVisible = !empty($details) && !empty($details->image) ? '' : '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($details) && !empty($details->image) ? 'none' : ''); ?>;">
                                            </a>
                                            <input type="file" id="image-file" name="image" accept="image/*"
                                                data-value="<?php echo e(!empty($details) && !empty($details->image) ? $details->image : ''); ?>"
                                                style="display:none;">
                                        </div>
                                        <div class="uploader-text"
                                            style="display:<?php echo e(!empty($details) && !empty($details->image) ? 'none' : ''); ?>;">
                                            <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:<?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($details) && !empty($details->image)): ?> src="<?php echo e(getMedia($details->image)); ?>" <?php endif; ?>
                                                id="image-preview">
                                        </div>
                                    </div>
                                </div>
                                <div class="add-new-service-detail-top-right">
                                    <h4>News Title</h4>
                                    <div class="form-group">
                                        <textarea class="form-control" id="title" name="title" placeholder="Add title" maxlength="250"><?php echo e(!empty($details) && !empty($details->title) ? $details->title : ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="add-new-service-detail-bottom">
                                <div class="add-new-service-detail-bottom-box">
                                    <?php
                                        if (!empty($details->newsDate)) {
                                            $date = $details->newsDate;
                                            if (!empty($date)) {
                                                $dateTime = new DateTime($date);
                                                $formattedDate = $dateTime->format('m/d/Y');
                                            } else {
                                                $formattedDate = '';
                                            }
                                        } else {
                                            $formattedDate = '';
                                        }
                                    ?>
                                    <h4>News Date</h4>
                                    <div class="form-group">
                                        <input type="text" name="newsDate" class="form-control newsdate" id="newsDate"
                                            value="<?php echo e(@$formattedDate); ?>" placeholder="Enter news date." readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="add-new-service-detail-bottom">
                                <div class="add-new-service-detail-bottom-box">
                                    <h4>News Short Summary</h4>
                                    <div class="form-group">
                                        <textarea class="form-control" id="summary" name="summary" placeholder="Enter news summary." maxlength="2000"><?php echo e(!empty($details) && !empty($details->summary) ? $details->summary : ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="submit-button">
                        <button type="submit"
                            class="submit-btn"><?php echo e(!empty($details) && !empty($details->id) ? 'Update' : 'Add'); ?>

                            NOW</button>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <script type="text/javascript" src="<?php echo asset('js/tinymce.min.js'); ?>"></script>
    <script type="text/javascript" src="<?php echo asset('plugin/datetimepicker/jquery.datetimepicker.full.js'); ?>"></script>
    <script>
        var type = $('#type').val();
        var imageElement = $('#image-file');
        var imageFile = null;
        var originalFileName = null;
        var errorMessage = '';
        var isFileValid = false;
        var fileType = 'image';
        $('.newsdate').datetimepicker({
            timepicker: false,
            format: 'm/d/Y',
            maxDate: new Date(),
            scrollMonth: false,
            scrollInput: false
        });

        $(document).ready(function() {
            var currentUrl = window.location.pathname.replace("/", "");            
            if (currentUrl.includes("/news")) {                
                $('#newsLi').addClass("active");
            }
            $('textarea').addClass('removeSameValueAndSpace').addClass('required');
            $('#addForm').validate({
                rules: {
                    title: {
                        required: true
                    },
                    summary: {
                        required: true
                    },
                    newsDate: {
                        required: true
                    },
                },
                messages: {
                    title: {
                        required: "Please enter news title."
                    },
                    summary: {
                        required: "Please enter news short summary."
                    },
                    newsDate: {
                        required: "Please enter news date."
                    },
                },
                submitHandler: function(form) {
                    submitNewsDetails();
                }
            });

            $(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 validationResult = {
                    isFileValid: false,
                    errorMessage: ''
                };
                if (type === 'image') {
                    validationResult = validateImageFile(file);
                }
                if (validationResult.isFileValid) {
                    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);
                } else {
                    displayMessageModal(validationResult.errorMessage, 'error');
                }
            }

            $(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();
            });

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


        function submitNewsDetails() {
            event.preventDefault();
            var isValid = true;
            imageFile = imageElement.attr('data-value');
            if (fileType == 'image') {
                if (imageFile == '' || imageFile == undefined) {
                    displayMessageModal('Please upload valid image file.', 'error');
                    isValid = false;
                    return;
                }
            }
            if (!validateEditorValue('summary')) {
                isValid = false;
                return;
            }
            if (isValid) {
                var url = "<?php echo e(url('admin/news/saveNewsDetails')); ?>";
                var formData = new FormData($('#addForm')[0]);
                $('body').prepend('<div class="loader"></div>');
                if (imageFile) {
                    originalFileName = imageElement.attr('data-filename');
                    formData.append('originalFileName', originalFileName);
                    formData.append('image', imageFile);
                }
                $('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', 'admin/news');
                    },
                    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("summary");
        function validateEditorValue(selector) {
            const value = tinymce.get(`${selector}`).getContent();
            if (!value || value.trim() === "") {
                displayMessageModal(
                    `Please enter a description.`,
                    "error"
                );
                return false;
            }
            return true;
        }
        
    </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/news/add.blade.php ENDPATH**/ ?>