<div class="page-header page-header-dark">
	<div class="page-header-content header-elements-md-inline">
		<div class="page-title d-flex">
			<h4><i class="icon-arrow-left52 mr-2"></i> <span class="font-weight-semibold">{$title}</span></h4>
			<a href="#" class="header-elements-toggle text-default d-md-none"><i class="icon-more"></i></a>
		</div>

		<div class="header-elements d-none">
    		<div class="d-flex justify-content-center">
        		
			</div>
		</div>
	</div>

	<div class="breadcrumb-line breadcrumb-line-dark header-elements-md-inline">
		<div class="d-flex">
			<div class="breadcrumb">
				<a href="{$adminUrl}/files" class="breadcrumb-item"><i class="icon-home2 mr-2"></i> {$title}</a>

                {if $upPath ne $path}
                    {assign var="folderPaths" value="/"|explode:$upPath}
	                {foreach from=$folderPaths item=folderPath key=idx name=folderPaths}
		                {if $smarty.foreach.folderPaths.first}
			                {assign var="newFolderPath" value=$folderPath}
		                {else}
			                {assign var="newFolderPath" value="$newFolderPath/$folderPath"}
		                {/if}
	                <a href="{$adminUrl}/files?path={$newFolderPath}" class="breadcrumb-item">{$folderPath|@ucfirst}</a>
	                {/foreach}
                {/if}
			</div>
			<a href="#" class="header-elements-toggle text-default d-md-none"><i class="icon-more"></i></a>
		</div>
		
		<div class="header-elements d-none">
			<div class="breadcrumb justify-content-center">
    			<a class="breadcrumb-elements-item new_folder" href="javascript:;"
				data-path="{if isset($path)}{$path|escape}{else}/{/if}"
				data-folder=""
				data-action="new_folder"
				data-confirm="{fileManager:addFolder}"
				data-popup="tooltip"
				data-placement="top"
				data-trigger="hover"
				data-original-title="{fileManager:addFolder}"
				><i class="icon-folder-plus"></i> {fileManager:addFolder} </a>
                <a class="breadcrumb-elements-item read-more" href="javascript:;"  data-toggle="collapse" data-target="#showFileUpload"><i class="icon-file-plus2"></i> Загрузить файл </a>
			</div>
		</div>

	</div>
</div>

<div class="content">	
    <div class="row files-list-box">
    	<div class="col-md-12">

        	<div id="addFolderRow" class="collapse">
        		<div class="card">
            		<div class="card-header bg-transparent header-elements-inline">
        				<h6 class="card-title">{fileManager:addFolder}</b></h6>
        				<div class="header-elements">
    						<div class="list-icons">
    	                		<a class="list-icons-item" data-action="collapse"></a>
                    		</div>
                		</div>
        			</div>
                    <div class="card-body">
              		    <form method="post">
                            <div class="row justify-content-md-center">
                                <div class="col-md-6"><input class="form-control" type="text" name="folder[name]" placeholder="{fileManager:folderName}"></div>
                                <div class="col-md-2">
                                    <button class="btn btn-sm btn-primary" type="submit" name="action" value="add_folder"><i class="icon-folder-plus2"></i> {fileManager:add}</button>
                                </div>
                            </div>
            			</form>
        			</div>
        		</div>
        	</div> 

        	<div class="card collapse" id="showFileUpload">
            	<div class="card-header bg-transparent header-elements-inline">
    				<h6 class="card-title">Загрузить файл</h6>
    				<div class="header-elements">
						<div class="list-icons"><a class="list-icons-item" data-action="collapse"></a></div>
            		</div>
    			</div>
{*             	<div id="upload_files" class="dropzone dropzone-product"><div class="dz-default dz-message"></div></div>*}
		        <div id="upload_files" class="dropzone">
			        <div class="dz-default dz-message"></div>
			        <input type="hidden" name="send_path" value="{if isset($path)}{$path|escape}{else}/{/if}" id="send_path">
		        </div>
        	</div>
        	
        	<div id="files-list" class="row">
			    {if isset($list)}
				    {* folder *}
    			    {if isset($list.dirs)}{include file="module/folder-list.tpl"}{/if}

                    {* files *}
                    {if isset($list.files)}{include file="module/file-list.tpl"}{/if}
                {/if}
            </div>
		    <div id="show_more_trigger" data-page="1" data-max="" data-path="{if $upPath ne $path}{$path}{/if}"></div>
    	</div>
    
    </div>
</div>


{* Подключаем filemanager *}
{*{include file='uploads_init.tpl'}*}

<style>
    a.no-after:after{ content:none; }
</style>

{if isset($messages.saved)}<span id="savedMessage" onclick="new Noty({ text: '{fileManager:messages:4}', type: 'success' }).show();"></span>{/if}

{if isset($errors.upload)}<span id="uploadError" onclick="new Noty({ text: '{fileManager:errors:0}', type: 'error' }).show();"></span>{/if}

{if isset($errors.save)}<span id="saveError" onclick="new Noty({ text: '{fileManager:errors:4}', type: 'error' }).show();"></span>{/if}
{if isset($errors.fileNameCharacters)}<span id="fileNameCharactersError" onclick="new Noty({ text: '{fileManager:errors:5}', type: 'error' }).show();"></span>{/if}
{if isset($errors.fileNameNoDot)}<span id="fileNameNoDotError" onclick="new Noty({ text: '{fileManager:errors:6}', type: 'error' }).show();"></span>{/if}
{if isset($errors.fileNameProhibited)}<span id="fileNameProhibitedError" onclick="new Noty({ text: '{fileManager:errors:7}', type: 'error' }).show();"></span>{/if}
{if isset($errors.accessDenied)}<span id="accessDeniedError" onclick="new Noty({ text: '{fileManager:errors:8}', type: 'error' }).show();"></span>{/if}
{if isset($errors.fileNotFound)}<span id="fileNotFoundError" onclick="new Noty({ text: '{fileManager:errors:9}', type: 'error' }).show();"></span>{/if}

<script>
    $(document).ready(function () {
        {if isset($errors.upload)} $('#uploadError').click();{/if}

        {if isset($errors.save)} $('#saveError').click();{/if}
        {if isset($errors.fileNameCharacters)} $('#fileNameCharactersError').click();{/if}
        {if isset($errors.fileNameNoDot)} $('#fileNameNoDotError').click();{/if}
        {if isset($errors.fileNameProhibited)} $('#fileNameProhibitedError').click();{/if}
        {if isset($errors.accessDenied)} $('#accessDeniedError').click();{/if}
        {if isset($errors.fileNotFound)} $('#fileNotFoundError').click();{/if}

        {if isset($messages.saved)} $('#savedMessage').click();{/if}
    });

    var block_show = false, selector = '#files-list';

    function scrollMore() {
        var $target = $('#show_more_trigger');

        if (block_show) {
            return false;
        }

        var wt = $(window).scrollTop(), wh = $(window).height(), et = $target.offset().top, eh = $target.outerHeight(), dh = $(document).height();
        if (wt + wh >= et || wh + wt === dh || eh + et < wh) {
            var page = $target.attr('data-page');
            page++;
            block_show = true;

            $.ajax({
                type: "POST",
                url: '{$adminUrl}/files?page=' + page,
                dataType: 'json',
	            data : { action: "read_files", path: $target.data("path") },
                beforeSend: function() {
                    $('.files-list-box').block({
                        centerY: false,
                        centerX: false,
                        message: '<i class="icon-spinner9 spinner"></i>',
                        overlayCSS: { 'z-index' : 98, backgroundColor: '#fff', opacity: 0.8, cursor: 'wait'},
                        css: { 'z-index' : 99,  border: 0, padding: 0, backgroundColor: 'none', position: 'fixed', margin: 'auto' }
                    });
                },
                success: function(response){
                    if (response.status === 200) {
                        $(selector).append(response.items);
                        window.setTimeout(function () {
                            $('.files-list-box').unblock();
                        }, 400);

                        block_show = false;
                    } else {
                        block_show = true;
                        window.setTimeout(function () {
                            $('.files-list-box').unblock();
                        }, 400);
                    }
                }
            });

            $target.attr('data-page', page);
            if (page === $target.attr('data-max')) {
                $target.remove();
            }
        }
    }

    $(window).scroll(function(){
        scrollMore();
    });

    $(document).ready(function(){
        scrollMore();
    });

    // удаление файла
    $(document).on('click','.remove-item-file',function() {
        var $target = $(this), blockList = $target.closest('.file-manager-list');
        bootbox.confirm({
            message: $target.data("confirm"),
            buttons: { confirm: { label: '{general:yes}', className: 'btn-sm btn-primary' }, cancel: { label: '{general:cancel}', className: 'btn-sm btn-secondary' } },
            callback: function(result) {
                if (result === true) {
                    $.post("{$adminUrl}/files", { action: "remove", path: $target.data("path"), id: $target.data("id") }).done(function (response) {
                        if (response.status === 200) {
                            blockList.stop().animate({ opacity: 0 }, 500, function() {
                                blockList.remove();
                            });
                        } else {
                            bootbox.confirm({ message: result.message });
                        }
                    }).fail( function(xhr, textStatus, errorThrown) {
                        console.log(xhr.responseText);
                        console.log(textStatus);
                    });
                }
            }
        })
    });

    // добавление папки
    $(document).on('click', '.new_folder', function() {
        var confirm = $(this).attr("data-confirm"), path = $(this).attr("data-path") ;
        bootbox.prompt({
            title: confirm,
            callback: function (name) {
                if (name !== null) {
                    $.post("{$adminUrl}/files", { action: 'new_folder', path: path, name: name }).done(function (response) {
	                    if (response.status === 200) {
                            new Noty({
	                            text: response.message,
	                            type: 'success',
	                            animation: {
                                    close: function () {
                                        window.setTimeout(function () {
                                            window.location.reload();
                                        }, 200);
                                    }
	                            }
                            }).show();

	                    } else {
		                    bootbox.alert({ message: response.error, buttons: { ok: { label: "OK", className: "btn-danger" } } });
	                    }
                    });
                }
            }
        })
    });

    // удаление файла или папки
    $(document).on('click','a.remove_folder',function() {
        var confirm = $(this).attr("data-confirm"), action = $(this).attr("data-action"), path = $(this).attr("data-path"), folder = $(this).attr("data-folder");
        console.log(folder)
        bootbox.confirm({
	        message: confirm,
	        buttons: { confirm: { label: '{general:yes}', className: 'btn-sm btn-primary' }, cancel: { label: '{general:cancel}', className: 'btn-sm btn-secondary' } },
            callback: function(res) {
                if (res === true) {
                    $.post("{$adminUrl}/files", { action: action, path: path, folder: folder }).done(function (response) {
                        console.log('data => ', response)
                        if (response.status === 100) {
                            bootbox.confirm({
                                message: response.message,
                                buttons: { confirm: { label: '{general:yes}', className: 'btn-sm btn-success' }, cancel: { label: '{general:no}', className: 'btn-sm btn-danger' } },
                                callback: function(confirm) {
                                    if (confirm === true) {
                                        $.post("{$adminUrl}/files", { action: 'confirm_remove', path: path, folder: folder }).done(function (response) {
                                            console.log('confirm => ', response)
                                            if (response.status === 200) {
                                                new Noty({
                                                    text: response.message, type: 'success',
                                                    animation: {
                                                        close: function () {
                                                            window.location.reload();
                                                        }
                                                    }
                                                }).show();
                                            } else {
                                                console.log(response.message);
                                                new Noty({ text: response.message, type: 'error' }).show();
                                            }
                                        }, 'json');
                                    }
                                }
                            });
                        } else if (response.status === 200) {
	                        new Noty({
		                        text: response.message, type: 'success',
		                        animation: {
		                            close: function () {
		                                window.location.reload();
		                            }
		                        }
	                        }).show();
                        } else if (response.status === 403) {
                            new Noty({ text: response.message, type: 'error' }).show();
                        }
                    }, 'json');
                }
            }
        })
    });

    Dropzone.autoDiscover = false;
    $(document).ready(function () {
	    $("#upload_files").dropzone({
            dictDefaultMessage:             lang['dictDefaultMessage'],
            dictFallbackMessage:            lang['dictFallbackMessage'],
            dictFallbackText:               lang['dictFallbackText'],
            dictFileTooBig:                 lang['dictFileTooBig'],
            dictInvalidFileType:            lang['dictInvalidFileType'],
            dictResponseError:              lang['dictResponseError'],
            dictCancelUpload:               lang['dictCancelUpload'],
            dictCancelUploadConfirmation:   lang['dictCancelUploadConfirmation'],
            dictRemoveFile:                 lang['dictRemoveFile'],
            dictRemoveFileConfirmation:     lang['dictRemoveFileConfirmation'],
            dictMaxFilesExceeded:           lang['dictMaxFilesExceeded'],
		    paramName: "file",
		    url: "{$adminUrl}/files",
		    addRemoveLinks: true,
		    maxFilesize: 32,
		    maxFiles: 30,
		    params: { action: 'upload' },
		    init: function () {
			    this.on('sending', function (file, xhr, formData) {
				    $('.dz-message').css('opacity', 0);
				    formData.append('path', $('#send_path').val());
			    });
			    this.on("success", function (file, response) {
				    console.log('dropzone success => ', response)
                    if (response.status === 200) {
                        new Noty({ text: response.message, type: 'success' }).show();
                        var d = new Date();
                        $('#files-list').append('<div class="file-manager-list">' +
                            '<div class="card">' +
                            '<div class="card-img-actions mx-1 mt-1"><div class="card-img card-file-upload" style="background-image: url(' + file.dataURL + ');background-size: cover;"></div></div>' +
                            '<div class="card-file-upload-body text-left">' +
                            '<a href="' + file.dataURL + '" data-popup="lightbox" rel="group">' +
                            '<div>' +
                            '<div class="font-weight-semibold">' + file.name+ '</div>' +
                            '<div class="font-size-sm text-muted">Size: ' + humanFileSize(file.size, true, 2) + '</div>' +
                            '<span class="font-size-sm text-muted">Дата: ' + d.toLocaleDateString() + '</span>' +
                            '</div>' +
                            '</a>' +
                            '</div>' +
                            '</div>'+
                            '</div>')
                    } else {
                        $(file.previewElement).find('.dz-error-mark').css('display', 'block').css('opacity', 1);
                        new Noty({ text: response.message, type: 'error' }).show();
                    }
			    });
			    this.on("queuecomplete", function () {

				    setTimeout(function () { $('.dz-success').fadeOut('slow'); }, 1000);
				    setTimeout(function () {
				        $('.dz-message').css('opacity', 1);
                        window.location.reload();
				    }, 1500);

			    });
			    this.on('error', function (file, response) {
                    $(file.previewElement).find('.dz-error-message');
				    new Noty({ text: response.error, type: 'error' }).show();
			    });
		    },
            accept: function(file, done) {
                return done();
            }
	    });
    });

    function humanFileSize(bytes, si=false, dp=1) {
        const thresh = si ? 1000 : 1024;

        if (Math.abs(bytes) < thresh) {
            return bytes + ' B';
        }

        const units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
        let u = -1;
        const r = 10**dp;

        do {
            bytes /= thresh;
            ++u;
        } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);


        return bytes.toFixed(dp) + ' ' + units[u];
    }

</script>


















