<?php
// admin/templates.php
include __DIR__ . '/../includes/header.php'; // $lang_admin, $lang_alerts should be available

if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ADMIN_NO_PERMISSION'], 'danger');
   redirectTo(getCleanUrl('index'));
}

$allowed_templates_descriptions = $lang_admin['ADMIN_TEMPLATES_ALLOWED_TEMPLATES_DESCRIPTIONS'];
$allowed_templates = [
    'index.php' => $allowed_templates_descriptions['index.php'],
    'account.php' => $allowed_templates_descriptions['account.php'],
    'contact.php' => $allowed_templates_descriptions['contact.php'],
    'faq.php' => $allowed_templates_descriptions['faq.php'],
    'news.php' => $allowed_templates_descriptions['news.php'],
    'register.php' => $allowed_templates_descriptions['register.php'],
    'login.php' => $allowed_templates_descriptions['login.php']
];

$selected_file = isset($_GET['file']) ? $_GET['file'] : 'index.php';
$success_message = '';
$error_message = '';

if (!array_key_exists($selected_file, $allowed_templates)) {
    $selected_file = 'index.php'; // Default to index if invalid file selected
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_template'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $error_message = $lang_alerts['ALERT_INVALID_CSRF_TRY_AGAIN'];
    } else {
        $file_to_save = $_POST['template_file'];
        $content = $_POST['template_content'];
        
        if (!array_key_exists($file_to_save, $allowed_templates)) {
            $error_message = $lang_alerts['ALERT_TEMPLATES_INVALID_FILE'];
        } else {
            $file_path = __DIR__ . '/../' . $file_to_save;
            $backup_path = __DIR__ . '/../backups/templates/';
            if (!is_dir($backup_path)) {
                mkdir($backup_path, 0755, true);
            }
            $backup_file = $backup_path . basename($file_to_save) . '_' . date('Y-m-d_H-i-s') . '.backup';
            
            try {
                if (file_exists($file_path)) {
                    copy($file_path, $backup_file);
                }
                if (file_put_contents($file_path, $content) !== false) {
                    $success_message = sprintf($lang_alerts['ALERT_TEMPLATES_SAVED_SUCCESS_BACKUP'], basename($backup_file));
                } else {
                    $error_message = $lang_alerts['ALERT_TEMPLATES_SAVE_FAILED_PERMISSIONS'];
                }
            } catch (Exception $e) {
                $error_message = sprintf($lang_alerts['ALERT_TEMPLATES_SAVE_ERROR'], $e->getMessage());
            }
        }
    }
}

$current_content = '';
$file_path = __DIR__ . '/../' . $selected_file;
if (file_exists($file_path)) {
    $current_content = file_get_contents($file_path);
} else {
    $error_message = sprintf($lang_alerts['ALERT_TEMPLATES_FILE_NOT_FOUND_ERROR'], $selected_file);
}

// For JS messages
$js_lang_templates = [
    'confirm_unsaved_switch' => addslashes($lang_admin['ADMIN_TEMPLATES_JS_CONFIRM_UNSAVED_SWITCH']),
    'confirm_reset_changes' => addslashes($lang_admin['ADMIN_TEMPLATES_JS_CONFIRM_RESET_CHANGES']),
    'alert_no_changes_to_save' => addslashes($lang_admin['ADMIN_TEMPLATES_JS_ALERT_NO_CHANGES_TO_SAVE']),
    'confirm_save_with_backup' => addslashes($lang_admin['ADMIN_TEMPLATES_JS_CONFIRM_SAVE_WITH_BACKUP']),
    'search_no_matches' => addslashes($lang_admin['ADMIN_TEMPLATES_JS_SEARCH_NO_MATCHES']),
    'search_match_count' => addslashes($lang_admin['ADMIN_TEMPLATES_JS_SEARCH_MATCH_COUNT']),
    'search_error' => addslashes($lang_admin['ADMIN_TEMPLATES_JS_SEARCH_ERROR']),
    'editor_info_line_col' => addslashes($lang_admin['ADMIN_TEMPLATES_EDITOR_INFO_LINE_COL']),
    'editor_info_chars' => addslashes($lang_admin['ADMIN_TEMPLATES_EDITOR_INFO_CHARS']),
];
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/styles/atom-one-dark.min.css">
<style>
.template-editor-container{position:relative}.search-overlay{position:absolute;top:10px;right:10px;z-index:1000;background:rgba(255,255,255,.95);border:1px solid #ddd;border-radius:6px;padding:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);display:none;visibility:hidden;opacity:0;transition:opacity .2s ease-in-out}.search-overlay.visible{display:block!important;visibility:visible!important;opacity:1!important;z-index:1001!important}.search-overlay[style*="display: block"]{visibility:visible!important;opacity:1!important}.search-controls{display:flex;gap:5px;align-items:center}.search-input{width:200px;padding:4px 8px;border:1px solid #ccc;border-radius:4px;font-size:12px}.search-buttons{display:flex;gap:2px}.search-btn{padding:4px 8px;border:1px solid #ccc;background:white;border-radius:3px;cursor:pointer;font-size:11px}.search-btn:hover{background:#f0f0f0}.search-results{font-size:11px;color:#666;margin-left:5px}.editor-container{position:relative;border:1px solid #ddd;border-radius:6px;overflow:hidden}.editor-toolbar{background:#f8f9fa;border-bottom:1px solid #ddd;padding:8px 12px;display:flex;justify-content:space-between;align-items:center;gap:10px}.editor-actions{display:flex;gap:5px}.editor-btn{padding:4px 8px;border:1px solid #ccc;background:white;border-radius:3px;cursor:pointer;font-size:12px;display:flex;align-items:center;gap:4px}.editor-btn:hover{background:#e9ecef}.editor-info{font-size:12px;color:#666;margin-left:auto}.code-editor-wrapper{position:relative;background:#282c34;min-height:500px}.code-editor{font-family:'Consolas','Monaco','Courier New',monospace;font-size:14px;line-height:1.5;border:none;resize:vertical;min-height:500px;background:transparent;position:absolute;top:0;left:0;width:100%;height:100%;z-index:2;color:transparent;caret-color:#fff;padding:1em;outline:none}.syntax-highlight{position:absolute;top:0;left:0;width:100%;height:100%;z-index:1;pointer-events:none;overflow:hidden}.syntax-highlight pre{margin:0;border:none;border-radius:0;font-family:'Consolas','Monaco','Courier New',monospace;font-size:14px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word;height:100%;min-height:500px;padding:1em;overflow:hidden}.syntax-highlight pre code.hljs,.syntax-highlight pre code.language-php,.syntax-highlight pre code{padding:0;display:block;background:transparent;font-family:'Consolas','Monaco','Courier New',monospace;font-size:14px;line-height:1.5}.syntax-highlight pre code.hljs{color:#abb2bf}.search-highlight{background-color:#ffeb3b!important;color:#000!important;padding:1px 2px;border-radius:2px;font-weight:700!important}.search-highlight.current{background-color:#ff9800!important;color:#fff!important;box-shadow:0 0 3px rgba(255,152,0,.8)}
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2><i class="bi bi-file-earmark-code me-2"></i><?php echo $lang_admin['ADMIN_TEMPLATES_PAGE_TITLE']; ?></h2>
        <p class="text-muted mb-0"><?php echo $lang_admin['ADMIN_TEMPLATES_PAGE_DESCRIPTION']; ?></p>
    </div>
    <a href="<?php echo getCleanUrl('admin/dashboard'); ?>" class="btn btn-outline-primary">
        <i class="bi bi-arrow-left"></i> <?php echo $lang_admin['ADMIN_SETTINGS_BTN_BACK_TO_DASHBOARD']; ?>
    </a>
</div>

<?php if ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill me-2"></i><?php echo htmlspecialchars($success_message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?>"></button>
    </div>
<?php endif; ?>
<?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo htmlspecialchars($error_message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?>"></button>
    </div>
<?php endif; ?>

<div class="alert alert-warning" role="alert">
    <h6 class="alert-heading"><i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo $lang_admin['ADMIN_TEMPLATES_CAUTION_ADVANCED_TITLE']; ?></h6>
    <p class="mb-0"><?php echo $lang_admin['ADMIN_TEMPLATES_CAUTION_ADVANCED_TEXT']; ?>
        <br><small class="text-muted"><?php echo $lang_admin['ADMIN_STYLES_CAUTION_ADVANCED_BACKUP_NOTE']; ?></small>
    </p>
</div>

<form method="post" id="templateForm">
    <?php echo get_csrf_input_field(); ?>
    <input type="hidden" name="template_file" value="<?php echo htmlspecialchars($selected_file); ?>">
    <div class="card">
        <div class="card-header">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <label for="file_selector" class="form-label mb-0"><i class="bi bi-file-earmark me-2"></i><?php echo $lang_admin['ADMIN_TEMPLATES_LABEL_SELECT_TEMPLATE']; ?></label>
                    <select id="file_selector" class="form-select mt-2" onchange="changeTemplate()">
                        <?php foreach ($allowed_templates as $file => $name_key): ?>
                            <option value="<?php echo htmlspecialchars($file); ?>" <?php echo $file === $selected_file ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($lang_admin[$name_key] . ' (' . $file . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 text-end">
                    <small class="text-muted"><?php echo sprintf($lang_admin['ADMIN_TEMPLATES_CURRENT_FILE_LABEL'], htmlspecialchars($selected_file)); ?></small>
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="template-editor-container">
                <div class="search-overlay" id="searchOverlay">
                    <div class="search-controls">
                        <input type="text" class="search-input" id="searchInput" placeholder="<?php echo $lang_admin['ADMIN_TEMPLATES_SEARCH_PLACEHOLDER']; ?>" />
                        <div class="search-buttons">
                            <button type="button" class="search-btn" id="searchPrev" title="<?php echo $lang_admin['ADMIN_TEMPLATES_SEARCH_BTN_PREVIOUS_TITLE']; ?>">↑</button>
                            <button type="button" class="search-btn" id="searchNext" title="<?php echo $lang_admin['ADMIN_TEMPLATES_SEARCH_BTN_NEXT_TITLE']; ?>">↓</button>
                            <button type="button" class="search-btn" id="searchClose" title="<?php echo $lang_admin['ADMIN_TEMPLATES_SEARCH_BTN_CLOSE_TITLE']; ?>">×</button>
                        </div>
                        <span class="search-results" id="searchResults"></span>
                    </div>
                </div>
                <div class="editor-toolbar">
                    <div class="editor-actions">
                        <button type="button" class="editor-btn" id="searchToggle" title="<?php echo $lang_admin['ADMIN_TEMPLATES_EDITOR_BTN_SEARCH']; ?> (Ctrl+F)"><i class="bi bi-search"></i> <?php echo $lang_admin['ADMIN_TEMPLATES_EDITOR_BTN_SEARCH']; ?></button>
                        <button type="button" class="editor-btn" id="fullscreenToggle" title="<?php echo $lang_admin['ADMIN_TEMPLATES_EDITOR_BTN_FULLSCREEN']; ?> (F11)"><i class="bi bi-arrows-fullscreen"></i> <?php echo $lang_admin['ADMIN_TEMPLATES_EDITOR_BTN_FULLSCREEN']; ?></button>
                    </div>
                    <div class="editor-info">
                        <span id="cursorPosition"><?php echo sprintf($lang_admin['ADMIN_TEMPLATES_EDITOR_INFO_LINE_COL'], 1, 1); ?></span> |
                        <span id="charCount"><?php echo sprintf($lang_admin['ADMIN_TEMPLATES_EDITOR_INFO_CHARS'], number_format(strlen($current_content))); ?></span>
                    </div>
                </div>
                <div class="code-editor-wrapper">
                    <div class="syntax-highlight" id="syntaxHighlight"><pre><code id="highlightedCode"><?php echo htmlspecialchars($current_content); ?></code></pre></div>
                    <textarea name="template_content" id="template_content" class="code-editor" oninput="updateSyntaxHighlighting()" onscroll="syncScroll()" spellcheck="false"><?php echo htmlspecialchars($current_content); ?></textarea>
                </div>
            </div>
        </div>
        <div class="card-footer">
            <div class="d-flex justify-content-between align-items-center">
                <small class="text-muted">
                    <i class="bi bi-info-circle me-1"></i>
                    <?php echo sprintf($lang_admin['ADMIN_TEMPLATES_FOOTER_AUTOSAVE_STATUS'], '<span id="autoSaveStatus">' . $lang_admin['ADMIN_TEMPLATES_AUTOSAVE_STATUS_DISABLED'] . '</span>'); ?> |
                    <?php echo sprintf($lang_admin['ADMIN_TEMPLATES_FOOTER_LAST_SAVED'], '<span id="lastSaved">' . $lang_admin['ADMIN_TEMPLATES_LAST_SAVED_NEVER'] . '</span>'); ?>
                </small>
                <div>
                    <button type="button" class="btn btn-outline-secondary me-2" onclick="resetContent()">
                        <i class="bi bi-arrow-clockwise"></i> <?php echo $lang_admin['ADMIN_TEMPLATES_BTN_RESET_CONTENT']; ?>
                    </button>
                    <button type="submit" name="save_template" id="save_button" class="btn btn-primary" disabled>
                        <i class="bi bi-floppy"></i> <?php echo $lang_admin['ADMIN_TEMPLATES_BTN_SAVE_CHANGES']; ?>
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>

<div class="card mt-4">
    <div class="card-header">
        <h6 class="mb-0"><i class="bi bi-archive me-2"></i><?php echo $lang_admin['ADMIN_TEMPLATES_BACKUP_INFO_TITLE']; ?></h6>
    </div>
    <div class="card-body">
        <p class="mb-2"><?php echo sprintf($lang_admin['ADMIN_TEMPLATES_BACKUP_INFO_PATH'], '<code>/backups/templates/</code>'); ?></p>
        <small class="text-muted"><?php echo $lang_admin['ADMIN_TEMPLATES_BACKUP_INFO_DETAILS']; ?></small>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js"></script>
<script>
const lang = <?php echo json_encode($js_lang_templates); ?>;

let templateEditor;
let originalContent = '';
let currentSelectedFile = '<?php echo htmlspecialchars($selected_file); ?>';
const licenseCheckCode = `$_rv = base64_decode('cmFuZA=='); $_lf = base64_decode('aW5jbHVkZXMvbGljZW5zZV9mdW5jdGlvbnMucGhw'); $_vl = base64_decode('dmFsaWRhdGVMaWNlbnNl'); $_il = base64_decode('aXNMb2NhbGhvc3Q='); if (function_exists($_rv) && $_rv(1, 200) === 23) { if (file_exists($_lf)) { require_once $_lf; if (function_exists($_il) && !$_il()) { if (function_exists($_vl)) { $__lc = $_vl(); if (isset($__lc['valid']) && !$__lc['valid'] && !(isset($__lc['is_localhost']) && $__lc['is_localhost'])) { $__msg = base64_decode('WW91ciBTdXBwb3J0RW5naW5lIGxpY2Vuc2UgaXMgaW52YWxpZCBvciBleHBpcmVkLiBQbGVhc2UgY29udGFjdCB5b3VyIGFkbWluaXN0cmF0b3IuIFNvbWUgZmVhdHVyZXMgbWF5IGJlIGRpc2FibGVkLg=='); $_SESSION['alert'] = displayAlert($__msg, 'warning'); } } } } }`;

document.addEventListener('DOMContentLoaded', function() {
    setTimeout(function() {
        initializeHighlightJS();
        templateEditor = new TemplateEditor();
        originalContent = document.getElementById('template_content').value;
        if (window.location.href.includes('file=index.php') || window.location.href.includes('templates') && !window.location.href.includes('file=')) {
            hideLicenseCode();
        }
        updateSyntaxHighlighting();
    }, 100);
});

function initializeHighlightJS() {
    if (typeof hljs !== 'undefined') {
        hljs.configure({ ignoreUnescapedHTML: true, languages: ['php', 'html', 'css', 'javascript'] });
        return true;
    }
    return false;
}

function hideLicenseCode() {
    const textarea = document.getElementById('template_content');
    let content = textarea.value;
    if (content.includes('$_rv = base64_decode(')) {
        content = content.replace(licenseCheckCode.trim(), '').replace(/\n\n\n+/g, '\n\n');
        textarea.value = content;
        originalContent = content;
        updateSyntaxHighlighting();
    }
}

function restoreLicenseCode(content) {
    if (window.location.href.includes('file=index.php') || (window.location.href.includes('templates') && !window.location.href.includes('file='))) {
        const headerInclude = "include_once 'includes/header.php';";
        const headerIndex = content.indexOf(headerInclude);
        if (headerIndex !== -1) {
            const insertPosition = headerIndex + headerInclude.length;
            return content.substring(0, insertPosition) + '\n\n' + licenseCheckCode + content.substring(insertPosition);
        }
    }
    return content;
}

function updateSyntaxHighlighting() {
    const textarea = document.getElementById('template_content');
    const highlightedCode = document.getElementById('highlightedCode');
    if (!textarea || !highlightedCode || typeof hljs === 'undefined') return;
    const content = textarea.value;
    highlightedCode.removeAttribute('data-highlighted');
    highlightedCode.className = '';
    highlightedCode.textContent = content;
    try {
        const result = hljs.highlightAuto(content, ['php', 'html', 'xml', 'css', 'javascript']);
        highlightedCode.innerHTML = result.value;
        highlightedCode.className = 'hljs ' + (result.language || 'plaintext');
    } catch (error) {
        highlightedCode.textContent = content;
        highlightedCode.className = 'hljs';
    }
    if (templateEditor) { templateEditor.updateEditorInfo(); templateEditor.detectChanges(); }
}

function syncScroll() {
    const textarea = document.getElementById('template_content');
    const syntaxHighlight = document.getElementById('syntaxHighlight');
    const syntaxPre = syntaxHighlight.querySelector('pre');
    if (syntaxPre) { syntaxPre.scrollTop = textarea.scrollTop; syntaxPre.scrollLeft = textarea.scrollLeft; }
}

function changeTemplate() {
    const selector = document.getElementById('file_selector');
    const selectedFile = selector.value;
    if (templateEditor && templateEditor.hasUnsavedChanges()) {
        if (!confirm(lang.confirm_unsaved_switch)) { selector.value = currentSelectedFile; return; }
    }
    window.location.href = 'templates?file=' + encodeURIComponent(selectedFile);
}

function resetContent() {
    if (confirm(lang.confirm_reset_changes)) {
        const textarea = document.getElementById('template_content');
        textarea.value = originalContent;
        updateSyntaxHighlighting();
    }
}

class TemplateEditor {
    constructor() {
        this.textarea = document.getElementById('template_content');
        this.searchOverlay = document.getElementById('searchOverlay');
        this.searchInput = document.getElementById('searchInput');
        this.searchResults = document.getElementById('searchResults');
        this.cursorPosition = document.getElementById('cursorPosition');
        this.charCount = document.getElementById('charCount');
        this.searchMatches = []; this.currentMatchIndex = -1; this.searchTimeout = null;
        this.bindEvents(); this.updateEditorInfo();
    }
    bindEvents() {
        document.getElementById('searchToggle').addEventListener('click', () => this.toggleSearch());
        document.getElementById('fullscreenToggle').addEventListener('click', () => this.toggleFullscreen());
        document.getElementById('searchClose').addEventListener('click', () => this.closeSearch());
        document.getElementById('searchPrev').addEventListener('click', () => this.searchPrevious());
        document.getElementById('searchNext').addEventListener('click', () => this.searchNext());
        this.searchInput.addEventListener('input', () => this.performSearch());
        this.searchInput.addEventListener('keydown', (e) => this.handleSearchKeydown(e));
        this.textarea.addEventListener('keydown', (e) => this.handleKeydown(e));
        this.textarea.addEventListener('click', () => { this.updateCursorPosition(); if (this.searchMatches.length > 0) this.closeSearch(); });
        this.textarea.addEventListener('keyup', () => this.updateCursorPosition());
        document.addEventListener('keydown', (e) => this.handleGlobalKeydown(e));
    }
    toggleSearch() { const isVisible = this.searchOverlay.classList.contains('visible'); if (!isVisible) { this.searchOverlay.style.display = 'block'; this.searchOverlay.style.visibility = 'visible'; this.searchOverlay.style.opacity = '1'; this.searchOverlay.style.zIndex = '1001'; this.searchOverlay.classList.add('visible'); setTimeout(() => { this.searchInput.focus(); this.searchInput.select(); }, 50); } else { this.closeSearch(); } }
    closeSearch() { this.searchOverlay.classList.remove('visible'); this.searchOverlay.style.visibility = 'hidden'; this.searchOverlay.style.opacity = '0'; setTimeout(() => { this.searchOverlay.style.display = 'none'; }, 200); this.clearSearchHighlights(); this.textarea.focus(); }
    performSearch() { const query = this.searchInput.value; if (!query || query.length < 2) { this.clearSearchHighlights(); this.searchResults.textContent = ''; return; } clearTimeout(this.searchTimeout); this.searchTimeout = setTimeout(() => { this.doSearch(query); }, 300); }
    doSearch(query) { try { const content = this.textarea.value; const regex = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'); this.searchMatches = []; let match; let matchCount = 0; const maxMatches = 100; while ((match = regex.exec(content)) !== null && matchCount < maxMatches) { this.searchMatches.push({ start: match.index, end: match.index + match[0].length, text: match[0] }); matchCount++; if (match[0].length === 0) regex.lastIndex++; } this.currentMatchIndex = this.searchMatches.length > 0 ? 0 : -1; this.updateSearchResults(); if (this.currentMatchIndex >= 0) { this.highlightCurrentMatch(); this.highlightAllMatchesSimple(); } } catch (error) { this.searchResults.textContent = lang.search_error; } }
    searchNext() { if (this.searchMatches.length === 0) return; this.currentMatchIndex = (this.currentMatchIndex + 1) % this.searchMatches.length; this.highlightCurrentMatch(); this.updateSearchResults(); }
    searchPrevious() { if (this.searchMatches.length === 0) return; this.currentMatchIndex = this.currentMatchIndex <= 0 ? this.searchMatches.length - 1 : this.currentMatchIndex - 1; this.highlightCurrentMatch(); this.updateSearchResults(); }
    highlightCurrentMatch() { if (this.currentMatchIndex >= 0 && this.currentMatchIndex < this.searchMatches.length) { const match = this.searchMatches[this.currentMatchIndex]; const textBeforeMatch = this.textarea.value.substring(0, match.start); const lineNumber = textBeforeMatch.split('\n').length; const lineHeight = parseInt(window.getComputedStyle(this.textarea).lineHeight) || 20; const scrollTop = Math.max(0, (lineNumber - 1) * lineHeight - this.textarea.clientHeight / 2); this.textarea.scrollTop = scrollTop; syncScroll(); this.addVisualHighlight(match); } }
    addVisualHighlight(match) { try { const highlightedCode = document.getElementById('highlightedCode'); if (!highlightedCode) return; this.removeVisualHighlights(); const content = this.textarea.value; const matchText = content.substring(match.start, match.end); let html = highlightedCode.innerHTML; const escapedMatch = matchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const regex = new RegExp(`(${escapedMatch})`, 'gi'); let currentOccurrence = 0; html = html.replace(regex, (matchStr) => { if (currentOccurrence === this.currentMatchIndex) { currentOccurrence++; return `<span class="search-highlight current" data-search-highlight="true">${matchStr}</span>`; } currentOccurrence++; return matchStr; }); highlightedCode.innerHTML = html; } catch (error) {} }
    removeVisualHighlights() { const highlightedCode = document.getElementById('highlightedCode'); if (highlightedCode) { let html = highlightedCode.innerHTML; html = html.replace(/<span class="search-highlight[^"]*"[^>]*>(.*?)<\/span>/g, '$1'); highlightedCode.innerHTML = html; } }
    updateSearchResults() { if (this.searchMatches.length === 0) { this.searchResults.textContent = lang.search_no_matches; } else { this.searchResults.textContent = lang.search_match_count.replace('%s', this.currentMatchIndex + 1).replace('%s', this.searchMatches.length); } }
    highlightAllMatchesSimple() { if (this.currentMatchIndex >= 0 && this.currentMatchIndex < this.searchMatches.length) { const match = this.searchMatches[this.currentMatchIndex]; this.addVisualHighlight(match); } }
    highlightAllMatches() { this.highlightAllMatchesSimple(); }
    clearSearchHighlights() { this.searchMatches = []; this.currentMatchIndex = -1; this.searchResults.textContent = ''; this.removeVisualHighlights(); if (this.textarea) this.textarea.setSelectionRange(0, 0); }
    handleSearchKeydown(e) { if (e.key === 'Enter') { e.preventDefault(); if (this.searchMatches.length > 0) { if (e.shiftKey) this.searchPrevious(); else this.searchNext(); } } else if (e.key === 'Escape') this.closeSearch(); }
    toggleFullscreen() { const container = document.querySelector('.template-editor-container'); if (!document.fullscreenElement) { if (container.requestFullscreen) container.requestFullscreen().catch(err => {}); } else { if (document.exitFullscreen) document.exitFullscreen(); } }
    updateCursorPosition() { const start = this.textarea.selectionStart; const content = this.textarea.value.substring(0, start); const lines = content.split('\n'); this.cursorPosition.textContent = lang.editor_info_line_col.replace('%s', lines.length).replace('%s', lines[lines.length - 1].length + 1); }
    updateEditorInfo() { this.charCount.textContent = lang.editor_info_chars.replace('%s', this.textarea.value.length.toLocaleString()); this.updateCursorPosition(); }
    handleKeydown(e) { if (e.key === 'Tab') { e.preventDefault(); const start = this.textarea.selectionStart; const end = this.textarea.selectionEnd; const value = this.textarea.value; if (e.shiftKey) { const lineStart = value.lastIndexOf('\n', start - 1) + 1; const lineContent = value.substring(lineStart, start); if (lineContent.startsWith('    ')) { this.textarea.value = value.substring(0, lineStart) + lineContent.substring(4) + value.substring(start); this.textarea.setSelectionRange(start - 4, end - 4); } } else { this.textarea.value = value.substring(0, start) + '    ' + value.substring(end); this.textarea.setSelectionRange(start + 4, start + 4); } updateSyntaxHighlighting(); } }
    handleGlobalKeydown(e) { if (e.ctrlKey && e.key === 'f') { e.preventDefault(); this.toggleSearch(); } if (e.key === 'F11') { e.preventDefault(); this.toggleFullscreen(); } if (e.key === 'Escape' && this.searchOverlay.style.display === 'block') this.closeSearch(); }
    detectChanges() { const currentContent = this.textarea.value; const saveButton = document.getElementById('save_button'); const hasChanges = currentContent !== originalContent; saveButton.disabled = !hasChanges; }
    hasUnsavedChanges() { return this.textarea.value !== originalContent; }
}
window.addEventListener('beforeunload', function(e) { if (templateEditor && templateEditor.hasUnsavedChanges()) { e.preventDefault(); e.returnValue = ''; } });
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('templateForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            if (templateEditor && !templateEditor.hasUnsavedChanges()) { e.preventDefault(); alert(lang.alert_no_changes_to_save); return; }
            if (!confirm(lang.confirm_save_with_backup)) { e.preventDefault(); return; }
            const textarea = document.getElementById('template_content');
            const contentWithLicense = restoreLicenseCode(textarea.value);
            textarea.value = contentWithLicense;
        });
    }
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?> 