<?php
/**
 * @version        1.9.10
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2018-2025 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
// no direct access
defined('_JEXEC') or die;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Toolbar\ToolbarHelper;

ToolbarHelper::title(Text::_('EDOCMAN_IMPORT_CATEGORIES'), 'upload');
ToolbarHelper::save('save', Text::_('Import'));
ToolbarHelper::cancel('cancel');

$bootstrapHelper = new EDocmanHelperBootstrap(EDocmanHelperHtml::getAdminBootstrapHelper());
$rowFluidClass = $bootstrapHelper->getClassMapping('row-fluid');
$span12Class = $bootstrapHelper->getClassMapping('span12');
?>

<style>
/* Modern Bootstrap 4 Admin Styles */
.import-container {
    max-width: 100%;
    margin: 0 auto;
    padding: 20px;
}

.card {
    border: none;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    border-radius: 0.375rem;
    margin-bottom: 1.5rem;
}

.card-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-bottom: none;
    padding: 1.25rem 1.5rem;
    border-radius: 0.375rem 0.375rem 0 0;
}

.card-header h4 {
    margin: 0;
    font-weight: 600;
    display: flex;
    align-items: center;
}

.card-header i {
    margin-right: 0.5rem;
    font-size: 1.2em;
}

.card-body {
    padding: 2rem;
}

.form-group {
    margin-bottom: 1.5rem;
}

.form-label {
    font-weight: 600;
    color: #495057;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
}

.form-label i {
    margin-right: 0.5rem;
    color: #6c757d;
}

.required {
    color: #dc3545;
}

/* Custom File Upload Styles */
.custom-file-upload {
    position: relative;
    margin-bottom: 15px;
}

.file-drop-area {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    border: 2px dashed #dee2e6;
    border-radius: 0.375rem;
    padding: 3rem 2rem;
    text-align: center;
    transition: all 0.3s ease;
    background: #f8f9fa;
    cursor: pointer;
}

.file-drop-area:hover,
.file-drop-area.highlight {
    border-color: #667eea;
    background: #f0f4ff;
    transform: translateY(-2px);
}

.fake-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 0.75rem 1.5rem;
    border-radius: 0.375rem;
    cursor: pointer;
    margin-bottom: 0.75rem;
    display: inline-block;
    font-weight: 600;
    transition: all 0.3s ease;
}

.fake-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}

.file-msg {
    color: #6c757d;
    font-size: 0.9rem;
}

.file-input {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    cursor: pointer;
    opacity: 0;
}

.file-display {
    display: none;
    align-items: center;
    justify-content: space-between;
    padding: 1rem;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    background: #f8f9fa;
}

.file-name {
    font-weight: 500;
    color: #495057;
}

.btn-remove {
    background: #dc3545;
    color: white;
    border: none;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.btn-remove:hover {
    background: #c82333;
    transform: scale(1.1);
}

.sample-link {
    display: inline-flex;
    align-items: center;
    color: #667eea;
    text-decoration: none;
    font-size: 0.9rem;
    margin-top: 0.5rem;
    transition: all 0.3s ease;
}

.sample-link:hover {
    color: #764ba2;
    text-decoration: none;
}

.sample-link i {
    margin-right: 0.5rem;
}

/* Options Card Styles */
.options-card {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    color: white;
}

.options-card .card-body {
    background: white;
    color: #495057;
    border-radius: 0 0 0.375rem 0.375rem;
}

/* Access Control Styles */
.access-control {
    background: #f8f9fa;
    border-radius: 0.375rem;
    padding: 1.5rem;
    margin-top: 1rem;
}

.radio-group {
    display: flex;
    gap: 1rem;
    margin-bottom: 1rem;
}

.radio-item {
    display: flex;
    align-items: center;
    padding: 0.5rem 1rem;
    background: white;
    border: 2px solid #dee2e6;
    border-radius: 0.375rem;
    cursor: pointer;
    transition: all 0.3s ease;
}

.radio-item:hover {
    border-color: #667eea;
    background: #f0f4ff;
}

.radio-item input[type="radio"] {
    margin-right: 0.5rem;
}

.radio-item.active {
    border-color: #667eea;
    background: #667eea;
    color: white;
}

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 1rem;
    justify-content: center;
    margin-top: 2rem;
    padding-top: 2rem;
    border-top: 1px solid #dee2e6;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    padding: 0.75rem 2rem;
    font-weight: 600;
    border-radius: 0.375rem;
    transition: all 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
    background: #6c757d;
    border: none;
    padding: 0.75rem 2rem;
    font-weight: 600;
    border-radius: 0.375rem;
    transition: all 0.3s ease;
}

.btn-secondary:hover {
    background: #5a6268;
    transform: translateY(-2px);
}

/* Responsive Design */
@media (max-width: 768px) {
    .import-container {
        padding: 10px;
    }
    
    .card-body {
        padding: 1.5rem;
    }
    
    .file-drop-area {
        padding: 2rem 1rem;
    }
    
    .action-buttons {
        flex-direction: column;
    }
    
    .radio-group {
        flex-direction: column;
    }
}
</style>

<div class="import-container">
    <form action="index.php?option=com_edocman&view=categoryimport" method="post" name="adminForm" id="adminForm" enctype="multipart/form-data">
        
        <!-- Main Import Card -->
        <div class="card">
            <div class="card-header">
                <h4><i class="fas fa-upload"></i> <?php echo Text::_('EDOCMAN_IMPORT_CATEGORIES'); ?></h4>
            </div>
            <div class="card-body">
                
                <!-- CSV File Upload Section -->
                <div class="form-group">
                    <label for="csv_file" class="form-label">
                        <i class="fas fa-file-csv"></i> 
                        <?php echo Text::_('EDOCMAN_CSV_FILE'); ?> 
                        <span class="required">*</span>
                    </label>
                    <div class="custom-file-upload">
                        <div class="file-drop-area" id="fileDropArea">
                            <span class="fake-btn">
                                <i class="fas fa-cloud-upload-alt"></i> Choose CSV File
                            </span>
                            <span class="file-msg">or drag and drop your CSV file here</span>
                            <input type="file" name="csv_file" id="csv_file" class="file-input" accept=".csv" required>
                        </div>
                        <div class="file-display" id="fileDisplay">
                            <span class="file-name"></span>
                            <button type="button" class="btn-remove" onclick="removeFile()">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <a href="javascript:void(0)" onclick="downloadSampleCSV()" class="sample-link">
                        <i class="fas fa-download"></i> Download Sample CSV Template
                    </a>
                </div>

                <!-- Parent Category Selection -->
                <div class="form-group">
                    <label for="parent_category" class="form-label">
                        <i class="fas fa-folder-tree"></i> 
                        <?php echo Text::_('EDOCMAN_PARENT_CATEGORY'); ?>
                    </label>
                    <?php echo $this->lists['category_id']; ?>
                    <small class="form-text text-muted">
                        <i class="fas fa-info-circle"></i> 
                        Select a parent category or leave as root level. CSV can override this with hierarchical structure.
                    </small>
                </div>

            </div>
        </div>

        <!-- Access Control Options -->
        <?php if (!$this->config->access_level_inheritance) { ?>
        <div class="card options-card">
            <div class="card-header">
                <h4><i class="fas fa-shield-alt"></i> Access Control Settings</h4>
            </div>
            <div class="card-body">
                <div class="form-group">
                    <label class="form-label">
                        <i class="fas fa-users"></i> 
                        <?php echo Text::_('EDOCMAN_ACCESS'); ?>
                    </label>
                    <p class="text-muted mb-3">Choose the default access level for imported categories</p>
                    
                    <div class="access-control">
                        <?php EDocmanHelper::showCheckboxfield('accesspicker', 0, Text::_('EDOCMAN_PRESETS'), Text::_('EDOCMAN_GROUPS')); ?>
                        
                        <div id="presetsdiv" class="access-option">
                            <h6><i class="fas fa-layer-group"></i> Access Presets</h6>
                            <?php echo $this->lists['access']; ?>
                        </div>
                        
                        <div id="groupsdiv" class="access-option" style="display:none;">
                            <h6><i class="fas fa-users-cog"></i> User Groups</h6>
                            <?php echo $this->lists['groups']; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php } ?>

        <!-- Import Options -->
        <div class="card">
            <div class="card-header">
                <h4><i class="fas fa-cogs"></i> Import Options</h4>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-check mb-3">
                            <input type="checkbox" name="create_folders" id="create_folders" class="form-check-input" checked>
                            <label for="create_folders" class="form-check-label">
                                <i class="fas fa-folder-plus"></i> Create physical folders
                            </label>
                            <small class="form-text text-muted">Automatically create folder structure on server</small>
                        </div>
                        
                        <div class="form-check mb-3">
                            <input type="checkbox" name="update_existing" id="update_existing" class="form-check-input">
                            <label for="update_existing" class="form-check-label">
                                <i class="fas fa-sync-alt"></i> Update existing categories
                            </label>
                            <small class="form-text text-muted">Update categories that already exist (match by name)</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-check mb-3">
                            <input type="checkbox" name="publish_categories" id="publish_categories" class="form-check-input" checked>
                            <label for="publish_categories" class="form-check-label">
                                <i class="fas fa-eye"></i> Publish imported categories
                            </label>
                            <small class="form-text text-muted">Make categories visible immediately after import</small>
                        </div>
                        
                        <div class="form-check mb-3">
                            <input type="checkbox" name="create_aliases" id="create_aliases" class="form-check-input" checked>
                            <label for="create_aliases" class="form-check-label">
                                <i class="fas fa-link"></i> Auto-generate SEF aliases
                            </label>
                            <small class="form-text text-muted">Automatically create SEO-friendly URL aliases</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="action-buttons">
            <button type="submit" class="btn btn-primary btn-lg" onclick="Joomla.submitbutton('save')">
                <i class="fas fa-upload"></i> Import Categories
            </button>
            <button type="button" class="btn btn-secondary btn-lg" onclick="resetForm()">
                <i class="fas fa-undo"></i> Reset Form
            </button>
            <button type="button" class="btn btn-outline-secondary btn-lg" onclick="Joomla.submitbutton('cancel')">
                <i class="fas fa-times"></i> Cancel
            </button>
        </div>

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

<script type="text/javascript">
// Enhanced JavaScript functionality
document.addEventListener('DOMContentLoaded', function() {
    initializeFileUpload();
    initializeAccessControl();
});

// File Upload Enhancement
function initializeFileUpload() {
    const fileDropArea = document.getElementById('fileDropArea');
    const fileInput = document.getElementById('csv_file');
    const fileDisplay = document.getElementById('fileDisplay');

    // Drag and drop events
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        fileDropArea.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        fileDropArea.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        fileDropArea.addEventListener(eventName, unhighlight, false);
    });

    fileDropArea.addEventListener('drop', handleDrop, false);
    fileInput.addEventListener('change', function(e) {
        handleFiles(e.target.files);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    function highlight(e) {
        fileDropArea.classList.add('highlight');
    }

    function unhighlight(e) {
        fileDropArea.classList.remove('highlight');
    }

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        fileInput.files = files;
        handleFiles(files);
    }

    function handleFiles(files) {
        if (files.length > 0) {
            const file = files[0];
            if (file.type === 'text/csv' || file.name.toLowerCase().endsWith('.csv')) {
                showFileDisplay(file.name);
                validateCSVFile(file);
            } else {
                alert('Please select a valid CSV file.');
                fileInput.value = '';
            }
        }
    }

    function showFileDisplay(fileName) {
        fileDropArea.style.display = 'none';
        fileDisplay.style.display = 'flex';
        fileDisplay.querySelector('.file-name').textContent = fileName;
    }

    function validateCSVFile(file) {
        // Basic CSV validation could be added here
        console.log('CSV file selected:', file.name, 'Size:', file.size, 'bytes');
    }
}

// Access Control Enhancement
function initializeAccessControl() {
    // Enhanced radio button functionality
    window.updateRadioButton = function(select_item) {
        const presetDiv = document.getElementById('presetsdiv');
        const groupsDiv = document.getElementById('groupsdiv');
        
        if (select_item == '0') {
            jQuery(presetDiv).slideDown(300);
            jQuery(groupsDiv).slideUp(300);
        } else {
            jQuery(presetDiv).slideUp(300);
            jQuery(groupsDiv).slideDown(300);
        }
    }
}

// Utility Functions
function removeFile() {
    document.getElementById('csv_file').value = '';
    document.getElementById('fileDropArea').style.display = 'flex';
    document.getElementById('fileDisplay').style.display = 'none';
}

function resetForm() {
    if (confirm('Are you sure you want to reset the form? All entered data will be lost.')) {
        document.getElementById('adminForm').reset();
        removeFile();
        // Reset access control to default
        updateRadioButton('0');
    }
}

function downloadSampleCSV() {
    // Enhanced sample CSV with more examples
    const csvContent = `Category Name,Parent Category,Description,Access Level,Owner User ID,Folder Path,Meta Keywords,Meta Description
Electronics,,Electronic products and accessories,1,42,,electronics technology gadgets,Electronic products and accessories category
Smartphones,Electronics,Mobile phones and accessories,1,42,electronics/smartphones,mobile phone smartphone,Smartphones and mobile devices
iPhone,Smartphones,Apple iPhone products,2,42,electronics/smartphones/iphone,apple iphone ios,Apple iPhone smartphones and accessories
Samsung Galaxy,Smartphones,Samsung Galaxy series,2,42,electronics/smartphones/samsung,samsung galaxy android,Samsung Galaxy smartphones
Laptops,Electronics,Laptop computers and accessories,1,43,electronics/laptops,laptop computer notebook,Laptop computers and accessories
Gaming Laptops,Laptops,High-performance gaming laptops,2,43,electronics/laptops/gaming,gaming laptop performance,Gaming laptops for enthusiasts
Business Laptops,Laptops,Professional business laptops,2,43,electronics/laptops/business,business professional laptop,Business and professional laptops
Books,,Books and publications,1,44,,books literature reading,Books and reading materials
Fiction,Books,Fiction books and novels,1,44,books/fiction,fiction novel story,Fiction books and novels
Science Fiction,Fiction,Science fiction literature,1,44,books/fiction/scifi,science fiction scifi fantasy,Science fiction books and literature
Mystery,Fiction,Mystery and thriller books,1,44,books/fiction/mystery,mystery thriller detective,Mystery and thriller novels
Non-Fiction,Books,Non-fiction and educational books,1,44,books/nonfiction,nonfiction educational factual,Non-fiction and educational materials`;

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'edocman_category_import_sample.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Form validation before submit
function validateForm() {
    const fileInput = document.getElementById('csv_file');
    if (!fileInput.files.length) {
        alert('Please select a CSV file to import.');
        return false;
    }
    return true;
}

// Override Joomla submit function
Joomla.submitbutton = function(task) {
    if (task == 'save') {
        if (validateForm()) {
            Joomla.submitform(task, document.getElementById('adminForm'));
        }
    } else {
        Joomla.submitform(task, document.getElementById('adminForm'));
    }
}
</script>
