<?php
require_once __DIR__ . '/../../../bootstrap/auth.php';
requireLogin();
require_once __DIR__ . '/../../../app/Models/UserType.php';
ob_start();

// Determine edit capability: admin role OR specific permission if user types with permissions are used
$canEdit = false;
if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin') {
    $canEdit = true;
} elseif (isset($_SESSION['user_type_id'])) {
    $userTypeModel = new UserType();
    $canEdit = $userTypeModel->hasPermission($_SESSION['user_type_id'], 'translations.edit') ||
               $userTypeModel->hasPermission($_SESSION['user_type_id'], 'translations_edit'); // legacy key
}

$title = 'Translation Manager - ' . htmlspecialchars($language['name'] ?? '');
?>

<div class="content">
    <?php if (!isset($grouped) || empty($grouped)): ?>
        <div class="alert alert-info">No translation keys found.</div>
    <?php else: ?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>
            <i class="fas fa-edit me-2"></i>
            <?php _e('languages.manage_translations'); ?>
            <small class="text-muted">
                <?php echo $language['flag']; ?> <?php echo htmlspecialchars($language['name']); ?>
            </small>
        </h2>
        <div>
            <a href="/samanta_crm/languages/<?php echo $language['id']; ?>/export" class="btn btn-success me-2" title="Export translations to JSON">
                <i class="fas fa-download me-1"></i><?php _e('common.export'); ?>
            </a>
            <button type="button" class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#importModal" title="Import translations from JSON">
                <i class="fas fa-upload me-1"></i><?php _e('common.import'); ?>
            </button>
            <a href="/samanta_crm/languages" class="btn btn-secondary">
                <i class="fas fa-arrow-left me-1"></i>Back to <?php _e('languages.list'); ?>
            </a>
        </div>
    </div>

    <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-<?php echo $_SESSION['message_type']; ?> alert-dismissible fade show" role="alert">
            <?php 
            echo $_SESSION['message']; 
            unset($_SESSION['message'], $_SESSION['message_type']);
            ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        Translation Keys
                        <?php
                        // Count total keys across categories
                        $totalKeys = 0; foreach ($grouped as $catArr) { $totalKeys += count($catArr); }
                        ?>
                        <span class="badge bg-primary"><?php echo $totalKeys; ?> keys</span>
                    </h5>
                    
                    <?php if ($canEdit): ?>
                    <div>
                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="copyFromEnglish()">
                            <i class="fas fa-copy me-1"></i>Copy from English
                        </button>
                        <button type="button" class="btn btn-sm btn-success" onclick="saveAll()">
                            <i class="fas fa-save me-1"></i><?php _e('common.save'); ?> All
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="mt-3 row g-2">
                    <div class="col-12 col-md-6">
                        <div class="input-group input-group-sm">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" id="translationSearch" class="form-control" placeholder="Quick search (key / English / current)..." oninput="filterTranslations()" />
                            <button type="button" class="btn btn-outline-secondary" onclick="clearSearch()">&times;</button>
                        </div>
                    </div>
                    <div class="col-12 col-md-3 small text-muted d-flex align-items-center" id="searchStats" style="display:none;"></div>
                </div>
            </div>
            
            <div class="card-body">
                <?php if ($canEdit): ?>
                <form id="translationsForm" method="POST" action="">
                <?php endif; ?>
                
                <!-- Category tabs -->
                <ul class="nav nav-tabs mb-3" id="categoryTabs">
                    <?php $first = true; foreach ($grouped as $category => $categoryTranslations): ?>
                    <li class="nav-item">
                        <button class="nav-link <?php echo $first ? 'active' : ''; ?>" 
                                type="button" 
                                data-bs-toggle="tab" 
                                data-bs-target="#tab-<?php echo htmlspecialchars($category); ?>">
                            <?php echo ucfirst($category); ?>
                            <span class="badge bg-secondary ms-1"><?php echo count($categoryTranslations); ?></span>
                        </button>
                    </li>
                    <?php $first = false; endforeach; ?>
                </ul>
                
                <!-- Category content -->
                <div class="tab-content">
                    <?php $first = true; foreach ($grouped as $category => $categoryTranslations): ?>
                    <div class="tab-pane fade <?php echo $first ? 'show active' : ''; ?>" 
                         id="tab-<?php echo htmlspecialchars($category); ?>">
                         
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th width="30%"><?php _e('translations.key'); ?></th>
                                        <th width="35%">English<?php if (empty($englishExists)): ?> (—)<?php endif; ?></th>
                                        <th width="35%"><?php echo htmlspecialchars($language['name']); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($categoryTranslations as $key => $row): ?>
                                    <tr>
                                        <td>
                                            <code><?php echo htmlspecialchars($key); ?></code>
                                        </td>
                                        <td>
                                            <div class="english-text" data-key="<?php echo htmlspecialchars($key); ?>">
                                                <?php echo htmlspecialchars($row['english'] ?? ''); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if ($canEdit): ?>
                                            <textarea class="form-control form-control-sm translation-input" 
                                                      name="translations[<?php echo htmlspecialchars($key); ?>]"
                                                      rows="2"
                                                      placeholder="Enter translation..."><?php echo htmlspecialchars($row['current'] ?? ''); ?></textarea>
                                            <?php else: ?>
                                            <div class="form-control-plaintext">
                                                <?php echo htmlspecialchars($row['current'] ?? ''); ?>
                                            </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php $first = false; endforeach; ?>
                </div>
                
                <?php if ($canEdit): ?>
                </form>
                <?php endif; ?>
            </div>
    </div>
    <?php endif; ?>
</div>

<!-- Import Modal -->
<div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importModalLabel">
                    <i class="fas fa-upload me-2"></i><?php _e('common.import'); ?> Translations
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="/samanta_crm/languages/<?php echo $language['id']; ?>/import" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Import Format:</strong> JSON file exported from this system.
                        Existing translations will be updated, new ones will be added.
                    </div>
                    
                    <div class="mb-3">
                        <label for="import_file" class="form-label">
                            <i class="fas fa-file-code me-1"></i>Select JSON File
                        </label>
                        <input type="file" 
                               class="form-control" 
                               id="import_file" 
                               name="import_file" 
                               accept=".json,application/json" 
                               required>
                        <div class="form-text">
                            Upload a JSON file previously exported from this system.
                        </div>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Warning:</strong> This will overwrite existing translations with matching keys.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-upload me-1"></i><?php _e('common.import'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Filtering logic
function filterTranslations() {
    const q = document.getElementById('translationSearch').value.toLowerCase().trim();
    const panes = document.querySelectorAll('.tab-pane');
    let totalVisible = 0;

    panes.forEach(pane => {
        const rows = pane.querySelectorAll('tbody tr');
        let paneVisible = 0;
        rows.forEach(r => {
            const keyEl = r.querySelector('code');
            const englishEl = r.querySelector('.english-text');
            const inputEl = r.querySelector('.translation-input');
            const plainEl = r.querySelector('.form-control-plaintext');
            const key = keyEl?.textContent.toLowerCase() || '';
            const english = englishEl?.textContent.toLowerCase() || '';
            const current = inputEl ? inputEl.value.toLowerCase() : (plainEl?.textContent.toLowerCase() || '');
            const match = !q || key.includes(q) || english.includes(q) || current.includes(q);
            if (match) {
                r.style.display = '';
                paneVisible++;
                totalVisible++;
            } else {
                r.style.display = 'none';
            }

            // Highlight key & english
            [keyEl, englishEl].forEach(el => {
                if (!el) return;
                const original = el.getAttribute('data-original') || el.textContent;
                if (!el.getAttribute('data-original')) {
                    el.setAttribute('data-original', original);
                }
                if (q && original.toLowerCase().includes(q)) {
                    const regex = new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')','ig');
                    el.innerHTML = original.replace(regex,'<mark>$1</mark>');
                } else {
                    el.innerHTML = original;
                }
            });
        });

        // Update badge counts (show matches/total when searching)
        const tabBtn = document.querySelector(`[data-bs-target='#${pane.id}']`);
        if (tabBtn) {
            const badge = tabBtn.querySelector('.badge');
            if (badge) {
                if (!badge.getAttribute('data-original')) {
                    badge.setAttribute('data-original', badge.textContent.trim());
                    badge.setAttribute('data-original-class', badge.className);
                }
                if (q) {
                    const totalRows = rows.length;
                    badge.textContent = `${paneVisible}/${totalRows}`;
                    // Reset color classes first
                    badge.className = badge.getAttribute('data-original-class');
                    // Apply dynamic color based on matches
                    if (paneVisible === 0) {
                        badge.classList.remove('bg-secondary','bg-primary','bg-success');
                        badge.classList.add('bg-danger');
                    } else if (paneVisible === totalRows) {
                        badge.classList.remove('bg-secondary','bg-primary','bg-danger');
                        badge.classList.add('bg-success');
                    } else {
                        badge.classList.remove('bg-secondary','bg-success','bg-danger');
                        badge.classList.add('bg-primary');
                    }
                } else {
                    badge.textContent = badge.getAttribute('data-original');
                    badge.className = badge.getAttribute('data-original-class');
                }
            }
        }
    });

    const stats = document.getElementById('searchStats');
    if (q) {
        stats.style.display = 'flex';
        stats.textContent = totalVisible + ' match' + (totalVisible!==1?'es':'');
    } else {
        stats.style.display = 'none';
    }
}

function clearSearch(){
    const input = document.getElementById('translationSearch');
    input.value='';
    filterTranslations();
    input.focus();
}

// Re-run filter when changing tabs
document.querySelectorAll('#categoryTabs button[data-bs-toggle="tab"]').forEach(btn => {
    btn.addEventListener('shown.bs.tab', () => filterTranslations());
});

function copyFromEnglish() {
    if (confirm('This will copy all English translations to empty fields. Continue?')) {
        document.querySelectorAll('.english-text').forEach(function(englishDiv) {
            const key = englishDiv.dataset.key;
            const englishText = englishDiv.textContent.trim();
            const textarea = document.querySelector(`textarea[name="translations[${key}]"]`);
            
            if (textarea && !textarea.value.trim()) {
                textarea.value = englishText;
            }
        });
        
        // Show success message
        const alert = document.createElement('div');
        alert.className = 'alert alert-info alert-dismissible fade show';
        alert.innerHTML = `
            <i class="fas fa-info-circle me-2"></i>
            English translations copied to empty fields. Don't forget to save!
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.querySelector('.content').insertBefore(alert, document.querySelector('.card'));
        
        // Auto-hide after 3 seconds
        setTimeout(function() {
            new bootstrap.Alert(alert).close();
        }, 3000);
    }
}

function saveAll() {
    document.getElementById('translationsForm').submit();
}

// Auto-resize textareas
document.querySelectorAll('.translation-input').forEach(function(textarea) {
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    });
    
    // Initial resize
    textarea.style.height = (textarea.scrollHeight) + 'px';
});

// Auto-hide alerts
setTimeout(function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        var bsAlert = new bootstrap.Alert(alert);
        bsAlert.close();
    });
}, 5000);
</script>

<?php
// Finalize buffered content and include layout
$content = ob_get_clean();
include __DIR__ . '/../layout.php';
?>


