<?php $__env->startSection('title', 'Contracting : Vehicles'); ?>
<?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: cover;
    }

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

    .dragging {
        border: 2px dashed #999;
        background: #f0f0f0;
    }
</style>
    <div class="middle-part-wrap contract-vehicle-list-page-wrap">
        <div class="vehicle-page scroll">
            <form id="contractForm" 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="header-page-top-section">
                        <div class="header-page-top-section-detail-left">
                            <h4>Header Video</h4>
                            <?php
                                $videoVisible =
                                    !empty($details) && $details->fileType == 2 && !empty($details->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($details) && $details->fileType == 2 && !empty($details->filePath) ? 'none' : ''); ?>;">
                                    </a>
                                    <input type="file" id="video-file" name="video" accept="video/*"
                                        data-value="<?php echo e(!empty($details) && $details->fileType == 2 && !empty($details->filePath) ? $details->filePath : ''); ?>"
                                        style="display:none;">
                                </div>
                                <div class="uploader-text"
                                    style="display:<?php echo e(!empty($details) && $details->fileType == 2 && !empty($details->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($details) && $details->fileType == 2): ?> src="<?php echo e(getMedia($details->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($details) && $details->fileType == 1 && !empty($details->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($details) && $details->fileType == 1 && !empty($details->filePath) ? 'none' : ''); ?>;">
                                    </a>
                                    <input type="file" id="image-file" name="image" accept="image/*"
                                        data-value="<?php echo e(!empty($details) && $details->fileType == 1 && !empty($details->filePath) ? $details->filePath : ''); ?>"
                                        style="display:none;">
                                </div>
                                <div class="uploader-text"
                                    style="display:<?php echo e(!empty($details) && $details->fileType == 1 && !empty($details->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($details) && $details->fileType == 1 && !empty($details->filePath)): ?> src="<?php echo e(getMedia($details->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($details) && !empty($details->title) ? $details->title : ''); ?>"
                                    placeholder="Enter page title.">
                            </div>
                        </div>
                    </div>
                    <div class="add-new-service-detail-bottom">
                        <div class="add-new-service-detail-bottom-box">
                            <h4>Header Overview <span>(Optional)</span></h4>
                            <div class="form-group">
                                <input type="text" class="form-control" name="tagLine" id="tagLine"
                                    value="<?php echo e(!empty($details) && !empty($details->tagLine) ? $details->tagLine : ''); ?>"
                                    placeholder="Enter service overview.">
                            </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'); ?> Now</button>
                    </div>
                </div>
            </form>
            <div class="contract-vehicle-top-title">
                <h5>Contract Vehicles</h5>
                <a href="<?php echo e(url('admin/contracting/vehicles/add')); ?>">Add Contract Vehicles</a>
            </div>
            <div class="contract-vehicle-list">
                <ul class="listRecordsUl">
                    <?php if(count($vehiclesList) > 0): ?>
                        <?php $__currentLoopData = $vehiclesList; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <li id="record_<?php echo e($key); ?>" class="listRecordsLi">
                                <div class="contract-vehicle-list-detail">
                                    <div class="contract-vehicle-top-btn">
                                        <a href="javascript:void(0);" class="delete-btn deleteRecord"
                                            data-title="<?php echo e($value->title); ?>" data-id="<?php echo e($value->id); ?>"
                                            data-key="<?php echo e($key); ?>">Delete</a>
                                        <a href="<?php echo e(url('admin/contracting/vehicles/edit/' . $value->pageUrl)); ?>"
                                            class="edit-btn">Edit</a>
                                    </div>
                                    <div class="contract-vehecle-detail-box">
                                        <div class="form-group">
                                            <textarea class="form-control" placeholder="Analytic and Technical Support Services (ATSS)" disabled readonly><?php echo e($value->title ?? ''); ?></textarea>
                                        </div>
                                    </div>
                                    <div class="contract-vehecle-detail-box">
                                        <div class="form-group">
                                            <textarea class="form-control" placeholder="Enter contract description." disabled readonly><?php echo e($value->description ?? ''); ?></textarea>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <?php else: ?>
                        <li style="width: 1650px;">
                            <div class="alert text-center alert-warning">
                                No records found.
                            </div>
                        </li>

                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </div>
    <script>
        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() {
            activeLi('contracting');
            $('input:not([type="file"])').addClass('removeSameValueAndSpace');
            $('#pageTitle').addClass('required');
            if (currentUrl.includes("vehicles") && currentUrl.includes("list")) {
                $('#contractVehicles').addClass("active");
            }
            $('#contractForm').validate({
                rules: {
                    title: {
                        required: true
                    },
                },
                messages: {
                    title: {
                        required: "Please enter title."
                    },
                },
                submitHandler: function(form) {
                    submitContractForm();
                }
            });

            $(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 === '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: ''
                };
            }

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


        function submitContractForm() {
            var isFormValid = true;
            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 (isFormValid) {
                var url = "<?php echo e(url('admin/contracting/saveContractPageDetails')); ?>";
                var formData = new FormData($('#contractForm')[0]);
                $('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');
                    }
                });
            }
        }


        $(document).on('click', '.deleteRecord', function(e) {
            e.stopPropagation();
            var $this = $(this);
            var id = $this.attr('data-id');
            var title = $this.attr('data-title');
            var key = $this.attr('data-key');
            $('#confirmActiveInactive').attr('data-id', id);
            $('#confirmActiveInactive').attr('data-key', key);
            $('.activeInactiveModal .modal-body').html(
                `Are you want to delete ${title} record?`);
            $('.activeInactiveModal').modal('show');
        });

        $(document).on('click', '.close,#cancelActiveInactive', function(e) {
            e.preventDefault();
            $('#confirmActiveInactive').attr('data-id', '');
            $('#confirmActiveInactive').attr('data-key', '');
            $('.activeInactiveModal').modal('hide');
        });

        $(document).on('click', '#confirmActiveInactive', function(e) {
            e.preventDefault();
            $('.activeInactiveModal').modal('hide');
            var $this = $(this);
            var id = $this.attr('data-id');
            var key = $this.attr('data-key');
            var url = "<?php echo e(url('admin/contracting/deleteContractVehicleRecord')); ?>";
            if (id) {
                $('body').prepend('<div class="loader"></div>');
                var formData = new FormData();
                var token = "<?php echo e(csrf_token()); ?>";
                formData.append('_token', token);
                formData.append('id', id);
                $.ajax({
                    url: url,
                    type: "POST",
                    cache: false,
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    data: formData,
                    success: function(response) {
                        $('.loader').remove();
                        $('html, body').animate({
                            scrollTop: $('body').offset().top
                        }, 300);
                        $(`#record_${key}`).remove();
                        if ($('.listRecordsLi').length == 0) {
                            $('.listRecordsUl').html(`<li style="width: 1650px;">
                            <div class="alert text-center alert-warning">
                                No records found.
                            </div>
                            </li>`);
                        }
                        $('.closeBtn').prop('disabled', true);
                        $('.closeBtn').hide();
                        displayMessageModal(response.message, 'success');
                        setTimeout(() => {
                            location.reload(true);
                        }, 2000);
                    },
                    error: function(error) {
                        $('.loader').remove();
                        displayMessageModal(error.responseJSON.message, 'error');
                    }
                });
            }
        });
    </script>
<?php $__env->stopSection(); ?>

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