<?php 
/**
 * @version        1.7.2
 * @package        Joomla
 * @subpackage     EDocman
 * @author         Tuan Pham Ngoc
 * @copyright	   Copyright (C) 2011 - 2025 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Toolbar\ToolbarHelper;

$document = Factory::getApplication()->getDocument();
ToolbarHelper::title(Text::_('EDOCMAN_BATCH_UPLOAD_STEP_1'), 'upload');
ToolbarHelper::save('edit_documents', Text::_('EDOCMAN_NEXT_STEP'));
HTMLHelper::_('jquery.framework');
$bootstrapHelper = new EDocmanHelperBootstrap(EDocmanHelperHtml::getAdminBootstrapHelper());
?>

<div class="edocman-upload-container">
    <form action="<?php echo Route::_('index.php?option=com_edocman&view=upload');?>" method="post" name="adminForm" id="adminForm">
        
        <div class="upload-header">
            <h1><?php echo Text::_('EDOCMAN_BATCH_UPLOAD'); ?></h1>
            <p><?php echo Text::_('EDOCMAN_BULK_UPLOAD_INSTRUCTIONS'); ?></p>
        </div>

        <div class="upload-settings">
            <div class="settings-grid">
                <div class="setting-group">
                    <label class="setting-label"><?php echo Text::_('EDOCMAN_CATEGORY');?></label>
                    <div class="setting-control">
                        <?php echo EdocmanHelper::getChoicesJsSelect($this->lists['category_id']); ?>
                    </div>
                </div>

                <?php if(!$this->config->access_level_inheritance) { ?>
                <div class="setting-group">
                    <label class="setting-label"><?php echo Text::_('EDOCMAN_ACCESS'); ?></label>
                    <div class="setting-control">
                        <div class="access-toggle">
                            <div class="access-option active" onclick="updateRadioButton('0')" id="presets-tab">
                                <?php echo Text::_('EDOCMAN_PRESETS'); ?>
                            </div>
                            <div class="access-option" onclick="updateRadioButton('1')" id="groups-tab">
                                <?php echo Text::_('EDOCMAN_GROUPS'); ?>
                            </div>
                        </div>
                        <div id="presetsdiv" class="access-content">
                            <?php echo $this->lists['access']; ?>
                        </div>
                        <div id="groupsdiv" class="access-content" style="display:none;">
                            <?php echo $this->lists['groups']; ?>
                        </div>
                    </div>
                </div>
                <?php } ?>

                <div class="setting-group">
                    <label class="setting-label"><?php echo Text::_('EDOCMAN_PUBLISHED'); ?></label>
                    <div class="setting-control">
                        <?php echo $this->lists['published']; ?>
                    </div>
                </div>
            </div>

            <div class="upload-zone" id="upload-drop-zone">
                <svg class="upload-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                    <polyline points="7,10 12,15 17,10"></polyline>
                    <line x1="12" y1="15" x2="12" y2="3"></line>
                </svg>
                
                <div class="upload-text">Drag and drop files here</div>
                <div class="upload-subtext">or click to browse files (Max: <?php echo $this->maxFilesize; ?>MB per file)</div>
                
                <div class="upload-buttons">
                    <button type="button" class="btn-upload" id="add-files-btn">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path d="M12 5v14m-7-7h14"></path>
                        </svg>
                        Add Files
                    </button>
                    <button type="button" class="btn-upload btn-start" id="start-upload-btn" style="display:none;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <polygon points="5,3 19,12 5,21 5,3"></polygon>
                        </svg>
                        Start Upload
                    </button>
                </div>

                <div id="uploader" style="display: none;"></div>
            </div>

            <div class="file-list" id="file-list" style="display: none;">
                <div class="file-header">
                    <div>Filename</div>
                    <div>Size</div>
                    <div>Status</div>
                </div>
                <div id="file-items"></div>
                <div class="progress-bar" id="overall-progress" style="margin: 15px 20px; display: none;">
                    <div class="progress-fill" id="progress-fill"></div>
                </div>
            </div>
        </div>

        <input type="hidden" name="task" value="" />	
        <?php echo HTMLHelper::_('form.token'); ?>
    </form>
</div>

<script>
<?php
$document->getWebAssetManager()->addInlineScript('
    Edocman.jQuery(function($) {
        var totalFiles = 0;
        var uploadedFiles = 0;
        var uploader;
        
        // Khởi tạo plupload ngay lập tức
        initializeUploader();
        
        function initializeUploader() {
            uploader = new plupload.Uploader({
                runtimes : "html5,flash,silverlight,html4",
                url : "'.Uri::root().'administrator/index.php?option=com_edocman&task=upload.upload&format=json",
                max_file_size : "'. $this->maxFilesize.'mb",
                unique_names : false,
                flash_swf_url : "'.Uri::root().'components/com_edocman/assets/js/plupload/plupload.flash.swf",
                multipart_params : {
                    "'.Session::getFormToken().'" : "1"
                },
                browse_button: "add-files-btn",
                drop_element: "upload-drop-zone",
                prevent_duplicates: true,
                filters: {
                    max_file_size: "'. $this->maxFilesize.'mb"
                }
            });
            
            // Bind events
            uploader.bind("Init", function(up, params) {
                console.log("Uploader initialized with runtime: " + params.runtime);
            });
            
            uploader.bind("FilesAdded", function(up, files) {
                totalFiles = files.length;
                uploadedFiles = 0;
                $("#file-list").show();
                $("#start-upload-btn").show();
                
                $("#file-items").empty();
                $.each(files, function(i, file) {
                    $("#file-items").append(
                        "<div class=\"file-item\" id=\"file-" + file.id + "\">" +
                            "<div class=\"file-name\">" + file.name + "</div>" +
                            "<div class=\"file-size\">" + formatFileSize(file.size) + "</div>" +
                            "<div class=\"file-status status-pending\">Pending</div>" +
                        "</div>"
                    );
                });
            });

            uploader.bind("BeforeUpload", function(up, file) {
				console.log("BeforeUpload for", file.name);
                var categoryId = $("#category_id").val();
                up.settings.multipart_params = {"category_id": categoryId, "'.Session::getFormToken().'" : "1"};
                
                $("#file-" + file.id + " .file-status")
                    .removeClass("status-pending")
                    .addClass("status-uploading")
                    .text("Uploading");
            });

            uploader.bind("UploadProgress", function(up, file) {
				console.log("UploadProgress for", file.name);
                $("#overall-progress").show();
                var overallProgress = Math.round((uploadedFiles / totalFiles) * 100);
                $("#progress-fill").css("width", overallProgress + "%");
            });

            uploader.bind("FileUploaded", function(up, file, response) {
				//console.log("FileUploaded for", file.name);
				uploadedFiles++;
				var res = response.response;
				//console.log("Response for", res);
				if (res) {
					var objResponse = jQuery.parseJSON(res);
					if (objResponse.error && objResponse.error.length > 0) {
						$("#file-" + file.id + " .file-status")
							.removeClass("status-uploading")
							.addClass("status-pending")
							.text("Error");
					} else {
						$("#file-" + file.id + " .file-status")
							.removeClass("status-uploading")
							.addClass("status-complete")
							.text("Complete");
					}
				}
				var overallProgress = Math.round((uploadedFiles / totalFiles) * 100);
				$("#progress-fill").css("width", overallProgress + "%");
			});


            uploader.bind("Error", function(up, args) {
                console.log("Upload error:", args);
                $("#file-" + args.file.id + " .file-status")
                    .removeClass("status-uploading")
                    .addClass("status-pending")
                    .text("Error");
            });
            
            // Khởi tạo uploader
            uploader.init();
        }
        
        // Ngăn chặn hành vi mặc định của trình duyệt
        $(window).on("dragover dragenter", function(e) {
            e.preventDefault();
            return false;
        });
        
        $(window).on("drop", function(e) {
            e.preventDefault();
            return false;
        });
        
        // Xử lý visual feedback cho drop zone
        $("#upload-drop-zone").on("dragover dragenter", function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).addClass("dragover");
            return false;
        });

        $("#upload-drop-zone").on("dragleave", function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).removeClass("dragover");
            return false;
        });

        $("#upload-drop-zone").on("drop", function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).removeClass("dragover");
            return false;
        });

        $("#start-upload-btn").click(function() {
            if (uploader) {
                uploader.start();
                $(this).hide();
            }
        });

        function formatFileSize(bytes) {
            if (bytes === 0) return "0 Bytes";
            var k = 1024;
            var sizes = ["Bytes", "KB", "MB", "GB"];
            var i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
        }
    });

    function updateRadioButton(select_item) {
        if (select_item == "0") {
            jQuery("#presetsdiv").slideDown();
            jQuery("#groupsdiv").slideUp();
            jQuery("#presets-tab").addClass("active");
            jQuery("#groups-tab").removeClass("active");
        } else {
            jQuery("#presetsdiv").slideUp();
            jQuery("#groupsdiv").slideDown();
            jQuery("#presets-tab").removeClass("active");
            jQuery("#groups-tab").addClass("active");
        }
    }
');
?>
</script>
