<?php
session_start();
$settings = get_settings();
$id_user = $_SESSION['id_user'];
$id_map_sel = $_SESSION['id_map_sel'];
$map = get_map($id_map_sel,$id_user);

$tmp_languages = get_languages_map();
$array_languages = $tmp_languages[0];
$default_language = $tmp_languages[1];

if($user_info['role']=='editor') {
    $editor_permissions = get_editor_permissions($id_user,$id_map_sel);
    if($editor_permissions['edit_map']==0) {
        $map=false;
    }
}

$deepl_api_key = $settings['deepl_api_key'];
$enable_deepl = $settings['enable_deepl'];
$deepl = ($enable_deepl && !empty($deepl_api_key)) ? 1 : 0;

$counts = [
        'map' => 1,
        'categories' => 0,
        'markers' => 0,
        'connections' => 0,
        'story' => 0,
        'geodata' => 0
];

if($map) {
    $c_c = $mysqli->query("SELECT COUNT(*) as num FROM sml_categories WHERE id_map=$id_map_sel AND name!=''");
    if($c_c) $counts['categories'] = $c_c->fetch_assoc()['num'];

    $c_m = $mysqli->query("SELECT COUNT(*) as num FROM sml_markers WHERE id_map=$id_map_sel AND (name!='' OR description!='' OR hours!='' OR icon_label!='' OR box_warning!='' OR extra_field_name_1!='')");
    if($c_m) $counts['markers'] = $c_m->fetch_assoc()['num'];

    $c_mc = $mysqli->query("SELECT COUNT(*) as num FROM sml_markers_connects WHERE (id_marker_source IN (SELECT id FROM sml_markers WHERE id_map=$id_map_sel) OR id_marker_dest IN (SELECT id FROM sml_markers WHERE id_map=$id_map_sel)) AND (title!='' OR description!='')");
    if($c_mc) $counts['connections'] = $c_mc->fetch_assoc()['num'];

    $c_s = $mysqli->query("SELECT COUNT(*) as num FROM sml_story WHERE id_map=$id_map_sel AND description!=''");
    if($c_s) $counts['story'] = $c_s->fetch_assoc()['num'];

    $c_g = $mysqli->query("SELECT COUNT(*) as num FROM sml_geodata WHERE id_map=$id_map_sel AND content!=''");
    if($c_g) $counts['geodata'] = $c_g->fetch_assoc()['num'];
}
?>

<?php if(!$map): ?>
    <div class="text-center">
        <div class="error mx-auto" data-text="401">401</div>
        <p class="lead text-gray-800 mb-5"><?php echo _("Permission denied"); ?></p>
        <p class="text-gray-500 mb-0"><?php echo _("It looks like that you do not have permission to access this page"); ?></p>
        <a href="index.php?p=dashboard">← <?php echo _("Back to Dashboard"); ?></a>
    </div>
    <?php die(); endif; ?>

<?php if(count($array_languages) < 2): ?>
    <div class="card bg-warning text-white shadow mb-4">
        <div class="card-body">
            <?php echo _("The map is not multi-language! To enable other languages go to the settings."); ?>
        </div>
    </div>
    <?php die(); endif; ?>

    <style>
        <?php if($demo): ?>
        .block_translate { pointer-events: none !important; }
        <?php endif; ?>
        .field_translate[data-type="editor"],
        .translate_original_field[data-type="editor"] {
            min-height: 50px;
        }
        .field_translate[data-type="editor"]:not(.ql-container),
        .translate_original_field[data-type="editor"]:not(.ql-container) {
            cursor: text;
            border: 1px solid #d1d3e2;
            border-radius: 0.35rem;
            padding: 12px 15px;
            overflow-y: auto;
            max-height: 300px;
        }
        .field_translate[data-type="editor"]:not(.ql-container) p,
        .translate_original_field[data-type="editor"]:not(.ql-container) p {
            padding: 0;
            margin: 0;
        }
        .translate_original_field[data-type="editor"]:not(.ql-container) {
            cursor: default;
        }
        .loader-sentinel {
            padding: 0;
            margin: 0;
            height: 10px;
            visibility: hidden;
        }
        .filter-active .row_translate.translated {
            display: none !important;
        }
    </style>

    <ul class="nav bg-white nav-pills nav-fill mb-2" id="translate_tabs">
        <li class="nav-item">
            <a class="nav-link active" data-toggle="pill" href="#map_tab"><i class="fas fa-map"></i> <?php echo strtoupper(_("Map")); ?></a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo ($counts['categories']==0) ? 'disabled' : ''; ?>" data-toggle="pill" href="#categories_tab"><i class="fas fa-list"></i> <?php echo strtoupper(_("Categories")); ?></a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo ($counts['markers']==0) ? 'disabled' : ''; ?>" data-toggle="pill" href="#markers_tab"><i class="fas fa-map-marker-alt"></i> <?php echo strtoupper(_("Markers")); ?></a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo ($counts['connections']==0) ? 'disabled' : ''; ?>" data-toggle="pill" href="#connections_tab"><i class="fas fa-project-diagram"></i> <?php echo strtoupper(_("Connections")); ?></a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo ($counts['story']==0) ? 'disabled' : ''; ?>" data-toggle="pill" href="#story_tab"><i class="fas fa-book-open"></i> <?php echo strtoupper(_("Story")); ?></a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo ($counts['geodata']==0) ? 'disabled' : ''; ?>" data-toggle="pill" href="#geodata_tab"><i class="fas fa-draw-polygon"></i> <?php echo strtoupper(_("Geodata")); ?></a>
        </li>
    </ul>

    <div class="tab-content">

        <?php
        function render_lazy_tab($tab_id, $table, $counts, $mysqli, $id_map_sel, $deepl, $demo, $callback) {
            $count = $counts[str_replace('_tab','',$tab_id)] ?? 0;
            global $lazy_counter;
            $lazy_counter = 0;
            ?>
            <div class="tab-pane <?php echo ($tab_id=='map_tab') ? 'active' : ''; ?>" id="<?php echo $tab_id; ?>">
                <div class="row">
                    <div class="col-md-12">
                        <div data-table="<?php echo $table; ?>" class="card block_translate shadow mb-4">
                            <div class="card-header py-3">
                                <i class="fas fa-circle icon_check_translate"></i>&nbsp;&nbsp;<h6 class="m-0 font-weight-bold d-inline-block text-primary"><?php echo sprintf(_("%s of %s translated"),'<span class="count_translated">--</span>','<span class="count_total_translate">--</span>') ?></h6>
                                <?php if($deepl==1) : ?>
                                    <button class="btn_bulk_translate btn btn-sm btn-primary ml-3 <?php echo ($demo) ? 'disabled_d' : ''; ?>"><?php echo _("translate missing values"); ?>&nbsp;&nbsp;<i style="vertical-align:middle" class="fas fa-globe"></i></button>
                                <?php endif; ?>
                                <label class="ml-3"><input class="checkbox_only_translated" type="checkbox" /> <?php echo _("view only not translated"); ?></label>
                                <div class="float-right d-inline-block grid_list_switcher">
                                    <i onclick="change_translate_view('list');" class="fas fa-table-list"></i>&nbsp;&nbsp;<i onclick="change_translate_view('grid');" class="fas fa-table-cells text-primary active"></i>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="infinite-container">
                                    <?php $callback($mysqli, $id_map_sel); ?>
                                </div>
                                <div class="loader-sentinel" style="display:none;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }

        render_lazy_tab('map_tab', 'sml_maps_lang', $counts, $mysqli, $id_map_sel, $deepl, $demo, function($mysqli, $id_m) {
            global $map;
            $array_input_lang = array();
            $query_lang = "SELECT * FROM sml_maps_lang WHERE id_map=$id_m;";
            $result_lang = $mysqli->query($query_lang);
            if($result_lang) {
                if ($result_lang->num_rows > 0) {
                    while($row_lang = $result_lang->fetch_array(MYSQLI_ASSOC)) {
                        $language = $row_lang['language'];
                        unset($row_lang['id_map']);
                        unset($row_lang['language']);
                        $array_input_lang[$language]=$row_lang;
                    }
                }
            }
            echo print_value_input('name',$map,$array_input_lang,'sml_maps_lang','text');
            echo print_value_input('meta_title',$map,$array_input_lang,'sml_maps_lang','text');
            echo print_value_input('meta_description',$map,$array_input_lang,'sml_maps_lang','textarea');
            echo print_value_input('info_content',$map,$array_input_lang,'sml_maps_lang','editor');

            echo print_value_input_json_params('intro_params','title',$map,$array_input_lang,'sml_maps_lang','text');
            echo print_value_input_json_params('intro_params','description',$map,$array_input_lang,'sml_maps_lang','textarea');
            echo print_value_input_json_params('intro_params','button',$map,$array_input_lang,'sml_maps_lang','text');

            for ($i = 1; $i <= 20; $i++) {
                echo print_value_input_json_params('default_am_placeholders',(string)$i,$map,$array_input_lang,'sml_maps_lang','text');
            }
        });

        render_lazy_tab('categories_tab', 'sml_categories_lang', $counts, $mysqli, $id_map_sel, $deepl, $demo, function($mysqli, $id_m) {
            $query = "SELECT * FROM sml_categories WHERE id_map=$id_m;";
            $result = $mysqli->query($query);
            if($result && $result->num_rows > 0) {
                while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                    $id_category = $row['id'];
                    $array_input_lang = get_lang_data($mysqli, 'sml_categories_lang', 'id_category', $id_category);
                    echo print_value_input('name',$row,$array_input_lang,'sml_categories_lang','text');
                }
            }
        });

        render_lazy_tab('markers_tab', 'sml_markers_lang', $counts, $mysqli, $id_map_sel, $deepl, $demo, function($mysqli, $id_m) {
            $query = "SELECT * FROM sml_markers WHERE id_map=$id_m;";
            $result = $mysqli->query($query);
            if($result && $result->num_rows > 0) {
                while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                    $id_marker = $row['id'];
                    $array_input_lang = get_lang_data($mysqli, 'sml_markers_lang', 'id_marker', $id_marker);

                    echo print_value_input('name',$row,$array_input_lang,'sml_markers_lang','text');
                    echo print_value_input('icon_label',$row,$array_input_lang,'sml_markers_lang','text');
                    echo print_value_input('hours',$row,$array_input_lang,'sml_markers_lang','textarea');
                    echo print_value_input('description',$row,$array_input_lang,'sml_markers_lang','editor');
                    echo print_value_input('box_warning',$row,$array_input_lang,'sml_markers_lang','editor');

                    for($i=1; $i<=20; $i++) {
                        echo print_value_input('extra_field_name_'.$i, $row, $array_input_lang, 'sml_markers_lang', 'text');
                        echo print_value_input('extra_field_value_'.$i, $row, $array_input_lang, 'sml_markers_lang', 'textarea');
                    }
                    echo print_value_input('extra_button_title_1', $row, $array_input_lang, 'sml_markers_lang', 'text');
                    echo print_value_input('extra_button_value_1', $row, $array_input_lang, 'sml_markers_lang', 'text');
                }
            }
        });

        render_lazy_tab('connections_tab', 'sml_markers_connects_lang', $counts, $mysqli, $id_map_sel, $deepl, $demo, function($mysqli, $id_m) {
            $query = "SELECT * FROM sml_markers_connects WHERE id_marker_source IN (SELECT id FROM sml_markers WHERE id_map=$id_m);";
            $result = $mysqli->query($query);
            if($result && $result->num_rows > 0) {
                while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                    $id_connect = $row['id'];
                    $array_input_lang = get_lang_data($mysqli, 'sml_markers_connects_lang', 'id_marker_connect', $id_connect);
                    echo print_value_input('title',$row,$array_input_lang,'sml_markers_connects_lang','text');
                    echo print_value_input('description',$row,$array_input_lang,'sml_markers_connects_lang','editor');
                }
            }
        });

        render_lazy_tab('story_tab', 'sml_story_lang', $counts, $mysqli, $id_map_sel, $deepl, $demo, function($mysqli, $id_m) {
            $query = "SELECT * FROM sml_story WHERE id_map=$id_m;";
            $result = $mysqli->query($query);
            if($result && $result->num_rows > 0) {
                while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                    $id_story = $row['id'];
                    $array_input_lang = get_lang_data($mysqli, 'sml_story_lang', 'id_story', $id_story);
                    echo print_value_input('description',$row,$array_input_lang,'sml_story_lang','editor');
                }
            }
        });

        render_lazy_tab('geodata_tab', 'sml_geodata_lang', $counts, $mysqli, $id_map_sel, $deepl, $demo, function($mysqli, $id_m) {
            $query = "SELECT * FROM sml_geodata WHERE id_map=$id_m;";
            $result = $mysqli->query($query);
            if($result && $result->num_rows > 0) {
                while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                    $id_geodata = $row['id'];
                    $array_input_lang = get_lang_data($mysqli, 'sml_geodata_lang', 'id_geodata', $id_geodata);
                    echo print_value_input('content',$row,$array_input_lang,'sml_geodata_lang','editor');
                }
            }
        });
        ?>

    </div>

    <script>
        (function($) {
            "use strict";
            window.id_map = <?php echo $id_map_sel; ?>;
            var timeout_input = null;
            var BATCH_SIZE = 50;
            var DirectionAttribute = Quill.import('attributors/attribute/direction');
            Quill.register(DirectionAttribute,true);
            var AlignClass = Quill.import('attributors/class/align');
            Quill.register(AlignClass,true);
            var BackgroundClass = Quill.import('attributors/class/background');
            Quill.register(BackgroundClass,true);
            var ColorClass = Quill.import('attributors/class/color');
            Quill.register(ColorClass,true);
            var DirectionClass = Quill.import('attributors/class/direction');
            Quill.register(DirectionClass,true);
            var FontClass = Quill.import('attributors/class/font');
            Quill.register(FontClass,true);
            var SizeClass = Quill.import('attributors/class/size');
            Quill.register(SizeClass,true);
            var AlignStyle = Quill.import('attributors/style/align');
            Quill.register(AlignStyle,true);
            var BackgroundStyle = Quill.import('attributors/style/background');
            Quill.register(BackgroundStyle,true);
            var ColorStyle = Quill.import('attributors/style/color');
            Quill.register(ColorStyle,true);
            var DirectionStyle = Quill.import('attributors/style/direction');
            Quill.register(DirectionStyle,true);
            var FontStyle = Quill.import('attributors/style/font');
            Quill.register(FontStyle,true);
            var SizeStyle = Quill.import('attributors/style/size');
            Quill.register(SizeStyle,true);
            var LinkFormats = Quill.import("formats/link");
            Quill.register(LinkFormats,true);
            SizeStyle.whitelist = ['12px','14px','16px','18px','24px','28px','32px','40px','48px','56px','64px','72px'];
            Quill.register(SizeStyle,true);
            window.lang_editors = [];
            window.bulk_translate = false;
            var toolbarOptions = [
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'size': ['12px','14px','16px','18px','24px','28px','32px','40px','48px','56px','64px','72px'] }],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'align': [] }],
                ['clean']
            ];

            $(document).on('click', '.field_translate[data-type="editor"], .translate_original_field[data-type="editor"]', function() {
                var elem = this;
                var $elem = $(elem);
                if ($elem.hasClass('ql-container')) return;
                var table = $elem.closest('.block_translate').attr('data-table');
                var field = $elem.attr('data-field');
                var lang = $elem.attr('data-lang') || "orig";
                var id = $elem.attr('data-id');
                if (!table) return;
                if(!window.lang_editors[table]) window.lang_editors[table] = [];
                if(!window.lang_editors[table][field]) window.lang_editors[table][field] = [];
                if(!window.lang_editors[table][field][lang+'-'+id]) {
                    var modulesConfig = { toolbar: toolbarOptions };
                    window.lang_editors[table][field][lang+'-'+id] = new Quill(elem, {
                        modules: modulesConfig,
                        readOnly: (lang!=='orig') ? false : true,
                        theme: 'snow',
                        bounds: document.getElementsByClassName('container-fluid')[0]
                    });
                    if(lang!=='orig') {
                        var q = window.lang_editors[table][field][lang+'-'+id];
                        q.on('text-change', function (delta, oldDelta, source) {
                            $elem.trigger('input');
                        });
                        q.focus();
                    }
                }
            });

            function renderNextBatch(tabId) {
                var $hiddenItems = $(tabId).find('.lazy-hidden');
                var $toShow = $hiddenItems.slice(0, BATCH_SIZE);
                $toShow.removeClass('d-none lazy-hidden');
                check_count_translated_tab(tabId);
                var sentinel = $(tabId).find('.loader-sentinel');
                if ($(tabId).find('.lazy-hidden').length > 0) {
                    sentinel.show();
                } else {
                    sentinel.hide();
                }
            }

            var tabObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        var tabPane = $(entry.target).closest('.tab-pane');
                        var tabId = '#' + tabPane.attr('id');
                        renderNextBatch(tabId);
                    }
                });
            }, { rootMargin: '200px' });

            $(document).ready(function () {
                check_count_translated_tab('#map_tab');
            });

            $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
                var targetTabSelector = $(e.target).attr("href");
                var $targetPane = $(targetTabSelector);
                if ($targetPane.find('.lazy-hidden').length > 0) {
                    var sentinel = $targetPane.find('.loader-sentinel')[0];
                    if(sentinel) {
                        tabObserver.observe(sentinel);
                        renderNextBatch(targetTabSelector);
                    }
                }
                check_count_translated_tab(targetTabSelector);
            });

            $(document).on('click', '.btn_bulk_translate', function() {
                var button = $(this);
                var html_btn = button.html();
                button.css('pointer-events','none');
                button.html(window.backend_labels.translating+'&nbsp;&nbsp;<i class="fas fa-spin fa-circle-notch"></i>')
                var parent = $(this).closest('.card');
                var tabId = '#' + parent.closest('.tab-pane').attr('id');
                var table = parent.attr('data-table');
                var elems_to_translate = [];
                parent.find('.infinite-container .field_translate').each(function () {
                    processField($(this));
                });

                function processField($elem) {
                    var id = $elem.attr('data-id');
                    var type = $elem.attr('data-type');
                    var field = $elem.attr('data-field');
                    var lang = $elem.attr('data-lang');
                    var val_original = '';
                    var val_current = '';
                    if(type=='editor') {
                        if(window.lang_editors[table] && window.lang_editors[table][field] && window.lang_editors[table][field][lang+'-'+id]) {
                            val_current = window.lang_editors[table][field][lang+'-'+id].root.innerHTML;
                        } else {
                            val_current = $elem.html();
                        }
                    } else {
                        val_current = $elem.val();
                    }
                    if (isEmptyHtml(val_current)) {
                        var $row = $elem.closest('.row_translate');
                        var $orig = $row.find('[data-lang="orig"][data-field="'+field+'"]');
                        if($orig.length) {
                            if(type=='editor') {
                                if(window.lang_editors[table] && window.lang_editors[table][field] && window.lang_editors[table][field]['orig-'+id]) {
                                    val_original = window.lang_editors[table][field]['orig-'+id].root.innerHTML;
                                } else {
                                    val_original = $orig.html();
                                }
                            } else {
                                val_original = $orig.val();
                            }
                        } else if (type != 'editor') {
                            if(field.endsWith('_custom')) {
                                var json_field = $elem.attr('data-json_field');
                                val_original = $row.find('.translate_original_field[data-field="'+field+'"][data-json_field="'+json_field+'"]').val();
                            } else {
                                val_original = $row.find('.translate_original_field[data-field="'+field+'"]').val();
                            }
                        }
                        if(val_original && val_original != '') {
                            elems_to_translate.push([$elem, val_original, lang, type, field, id, table]);
                        }
                    }
                }
                window.bulk_translate = true;
                translate(elems_to_translate, function() {
                    window.bulk_translate = false;
                    button.html(html_btn);
                    button.css('pointer-events','initial');
                });
            });

            $(document).on('change', '.checkbox_only_translated', function () {
                var tabPane = $(this).closest('.tab-pane');
                var tabId = '#' + tabPane.attr('id');
                var container = tabPane.find('.infinite-container');
                if($(this).is(':checked')) {
                    container.addClass('filter-active');
                } else {
                    container.removeClass('filter-active');
                }
                var sentinel = tabPane.find('.loader-sentinel');
                if (sentinel.is(':visible')) {
                    renderNextBatch(tabId);
                }
            });

            $(document).on('input', '.field_translate', function() {
                if(!window.bulk_translate) {
                    clearTimeout(timeout_input);
                }
                var elem = $(this);
                elem.closest('.input-group').find('.check_translate i').removeClass('fa-circle').addClass('fa-circle-notch').addClass('fa-spin');
                var id = elem.attr('data-id');
                var type = elem.attr('data-type');
                var field = elem.attr('data-field');
                var table = elem.closest('.block_translate').attr('data-table');
                var lang = elem.attr('data-lang');
                var value;
                if(type=='editor') {
                    if(window.lang_editors[table] && window.lang_editors[table][field] && window.lang_editors[table][field][lang+'-'+id]) {
                        value = window.lang_editors[table][field][lang+'-'+id].root.innerHTML;
                        if(isEmptyHtml(value)) value='';
                    } else {
                        value = elem.html();
                    }
                } else {
                    value = elem.val();
                }
                if(!isEmptyHtml(value)) {
                    elem.closest('.row_translate').addClass('translated');
                    elem.closest('.input-group').find('.check_translate i').css('color','green');
                } else {
                    elem.closest('.row_translate').removeClass('translated');
                    elem.closest('.input-group').find('.check_translate i').css('color','orange');
                }

                var finalValue = value;
                var finalField = field;
                var $parent_block = elem.closest('.block_translate');

                if(field.endsWith('_custom')) {
                    var real_field = elem.attr('data-real_field');
                    var json_str = $parent_block.find('.field_translate[data-table="'+table+'"][data-id="'+id+'"][data-field="'+field+'"][data-lang="'+lang+'"]').first().attr('data-param');
                    var json_params = {};
                    if(json_str) {
                        json_params = JSON.parse(json_str);
                    }
                    $parent_block.find('.field_translate[data-table="'+table+'"][data-id="'+id+'"][data-field="'+field+'"][data-lang="'+lang+'"]').each(function() {
                        var elem_s = $(this);
                        var s_value = elem_s.val();
                        var json_field = elem_s.attr('data-json_field');
                        json_params[json_field] = s_value;
                    });
                    finalValue = JSON.stringify(json_params);
                    finalField = real_field;
                }

                timeout_input = setTimeout(function() {
                    check_count_translated_tab('#'+elem.closest('.tab-pane').attr('id'));
                    saveTranslation(id, finalField, finalValue, table, lang);
                    elem.closest('.input-group').find('.check_translate i').addClass('fa-circle').removeClass('fa-circle-notch').removeClass('fa-spin');
                },(window.bulk_translate) ? 0 : 500);
            });

            function saveTranslation(id, field, value, table, lang) {
                $.ajax({
                    url: "ajax/save_bulk_translate.php",
                    type: "POST",
                    data: { id: id, field: field, value: value, table: table, lang: lang },
                    async: true
                });
            }

            function translate(elems_to_translate, callback) {
                if (elems_to_translate.length === 0) {
                    callback();
                    return;
                }
                var item = elems_to_translate.shift();
                var target = item[0];
                var originalText = item[1];
                var lang = item[2];
                var type = item[3];
                var field = item[4];
                var id = item[5];
                var table = item[6];
                $.ajax({
                    url: 'ajax/translate_deepl.php',
                    async: true,
                    type: 'POST',
                    data: { language: lang, text: originalText },
                    success: function(rsp) {
                        if(window.lang_editors[table] && window.lang_editors[table][field] && window.lang_editors[table][field][lang+'-'+id]) {
                            var quill = window.lang_editors[table][field][lang+'-'+id];
                            quill.root.innerHTML = rsp;
                            quill.update();
                        } else {
                            if(type=='editor') { target.html(rsp); } else { target.val(rsp); }
                            target.trigger('input');
                        }

                        setTimeout(function() {
                            translate(elems_to_translate, callback);
                        },500);
                    },
                    error: function() {
                        setTimeout(function() {
                            translate(elems_to_translate, callback);
                        },250);
                    }
                });
            }

            function isEmptyHtml(value) {
                if (!value) return true;
                const text = value.replace(/<[^>]*>/g, '').trim();
                return text === '';
            }

            window.check_count_translated_tab = function(tabSelector) {
                var $scope = $(tabSelector);
                var count_translated = 0;
                var count_total = 0;
                $scope.find('.field_translate').each(function() {
                    count_total++;
                    var val = ($(this).attr('data-type')=='editor') ? $(this).text().trim() : $(this).val();
                    if(val!='') count_translated++;
                });
                $scope.find('.count_translated').html(count_translated);
                $scope.find('.count_total_translate').html(count_total);
                if(count_translated == count_total && count_total > 0) {
                    $scope.find('.icon_check_translate').css('color','green');
                    $scope.find('.btn_bulk_translate').addClass('disabled');
                } else {
                    $scope.find('.icon_check_translate').css('color','orange');
                    $scope.find('.btn_bulk_translate').removeClass('disabled');
                }
            }

            window.change_translate_view = function(type) {
                switch(type) {
                    case 'list':
                        $('.grid_list_switcher .fa-table-list').addClass('active').addClass('text-primary');
                        $('.grid_list_switcher .fa-table-cells').removeClass('active').removeClass('text-primary');
                        $('.column_field_translate').removeClass('col-md-4').addClass('col-md-12');
                        break;
                    case 'grid':
                        $('.grid_list_switcher .fa-table-list').removeClass('active').removeClass('text-primary');
                        $('.grid_list_switcher .fa-table-cells').addClass('active').addClass('text-primary');
                        $('.column_field_translate').removeClass('col-md-12').addClass('col-md-4');
                        break;
                }
            }
        })(jQuery);
    </script>

<?php
function get_lang_data($mysqli, $table, $id_col, $id_val) {
    $array_input_lang = array();
    $query_lang = "SELECT * FROM $table WHERE $id_col=$id_val;";
    $result_lang = $mysqli->query($query_lang);
    if($result_lang && $result_lang->num_rows > 0) {
        while($row_lang = $result_lang->fetch_array(MYSQLI_ASSOC)) {
            $language = $row_lang['language'];
            unset($row_lang[$id_col]);
            unset($row_lang['language']);
            $array_input_lang[$language]=$row_lang;
        }
    }
    return $array_input_lang;
}

function print_value_input($field,$array,$array_lang,$table,$input_type) {
    global $default_language,$array_languages, $lazy_counter;

    if(empty($array[$field]) || trim(strip_tags($array[$field]))=='') {
        return '';
    }

    $lazy_counter++;
    $visibility_class = ($lazy_counter > 50) ? 'd-none lazy-hidden' : '';

    $is_translated = true;
    foreach ($array_languages as $language) {
        if ($language != $default_language) {
            $val = isset($array_lang[$language][$field]) ? $array_lang[$language][$field] : '';
            if(empty(trim(strip_tags($val)))) {
                $is_translated = false;
                break;
            }
        }
    }

    $status_class = $is_translated ? 'translated' : '';
    $html = '<div class="row row_translate '.$visibility_class.' '.$status_class.'">';
    $disabled = "";

    switch($input_type) {
        case 'text':
            $input = '<input readonly data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$field.'" data-lang="orig" type="text" class="form-control translate_original_field" value="'.htmlspecialchars($array[$field]).'" />';
            break;
        case 'textarea':
            $input = '<textarea readonly data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$field.'" data-lang="orig" class="form-control translate_original_field">'.htmlspecialchars($array[$field]).'</textarea>';
            break;
        case 'editor':
            $input = '<div data-type="editor" data-lang="orig" readonly class="translate_original_field" data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$field.'">'.($array[$field]).'</div>';
            $disabled = "disabled_editor";
            break;
    }

    $html .= '<div class="col-md-4 column_field_translate">
        <div class="input-group input-group-sm '.$disabled.'">
            <div class="input-group-prepend">
                <span class="input-group-text bg-white"><img style="height:14px;width:22px;" src="img/flags_lang/'.$default_language.'.png?v=3" /></span>
            </div>
            '.$input.'
        </div>
    </div>';

    foreach ($array_languages as $language) {
        if ($language != $default_language) {
            switch($input_type) {
                case 'text':
                    $input = '<input data-type="text" data-lang="'.$language.'" data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$field.'" type="text" class="form-control field_translate" value="'.htmlspecialchars($array_lang[$language][$field] ?? '').'">';
                    break;
                case 'textarea':
                    $input = '<textarea data-type="textarea" data-lang="'.$language.'" data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$field.'" class="form-control field_translate">'.htmlspecialchars($array_lang[$language][$field] ?? '').'</textarea>';
                    break;
                case 'editor':
                    $input = '<div data-type="editor" data-lang="'.$language.'" data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$field.'" class="field_translate">'.($array_lang[$language][$field] ?? '').'</div>';
                    break;
            }

            $icon_color = (empty(trim(strip_tags($array_lang[$language][$field] ?? '')))) ? 'orange' : 'green';
            if($input_type == 'editor') {
                $html .= '<div class="col-md-4 column_field_translate">
                    <div class="input-group input-group-sm">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-white"><img style="height:14px;width:22px;" src="img/flags_lang/'.$language.'.png?v=3" /></span>
                        </div>
                        <div style="position:absolute;top:0;right:0;" class="input-group-prepend">
                            <span class="input-group-text bg-white check_translate"><i style="color:'.$icon_color.'" class="status_translate_icon fas fa-circle"></i></span>
                        </div>
                        '.$input.'
                    </div>
                </div>';
            } else {
                $html .= '<div class="col-md-4 column_field_translate">
                    <div class="input-group input-group-sm">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-white"><img style="height:14px;width:22px;" src="img/flags_lang/'.$language.'.png?v=3" /></span>
                        </div>
                        '.$input.'
                        <div class="input-group-append">
                            <span class="input-group-text bg-white check_translate"><i style="color:'.$icon_color.'" class="status_translate_icon fas fa-circle"></i></span>
                        </div>
                    </div>
                </div>';
            }
        }
    }

    $html .= '<hr class="mt-0 mb-3"></div>';
    return $html;
}

function print_value_input_json_params($field,$json_field,$array,$array_lang,$table,$input_type) {
    global $default_language,$array_languages, $lazy_counter;

    if(empty($array[$field])) {
        return '';
    }
    $json_orig = json_decode($array[$field], true);
    if(json_last_error() !== JSON_ERROR_NONE || !isset($json_orig[$json_field]) || empty(trim(strip_tags($json_orig[$json_field])))) {
        return '';
    }

    $lazy_counter++;
    $visibility_class = ($lazy_counter > 50) ? 'd-none lazy-hidden' : '';

    $is_translated = true;
    foreach ($array_languages as $language) {
        if ($language != $default_language) {
            $val = '';
            if(isset($array_lang[$language][$field])) {
                $json_lang = json_decode($array_lang[$language][$field], true);
                if(is_array($json_lang) && isset($json_lang[$json_field])) {
                    $val = $json_lang[$json_field];
                }
            }
            if(empty(trim(strip_tags($val)))) {
                $is_translated = false;
                break;
            }
        }
    }

    $status_class = $is_translated ? 'translated' : '';
    $html = '<div class="row row_translate '.$visibility_class.' '.$status_class.'">';
    $custom_field = $field . '_custom';

    if($input_type=='textarea') {
        $input = '<textarea readonly data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$custom_field.'" data-real_field="'.$field.'" data-json_field="'.$json_field.'" data-lang="orig" class="form-control translate_original_field">'.htmlspecialchars($json_orig[$json_field]).'</textarea>';
    } else {
        $input = '<input readonly data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$custom_field.'" data-real_field="'.$field.'" data-json_field="'.$json_field.'" data-lang="orig" type="text" class="form-control translate_original_field" value="'.htmlspecialchars($json_orig[$json_field]).'">';
    }

    $html .= '<div class="col-md-4 column_field_translate">
        <div class="input-group input-group-sm">
            <div class="input-group-prepend">
                <span class="input-group-text bg-white"><img style="height:14px;width:22px;" src="img/flags_lang/'.$default_language.'.png?v=3" /></span>
            </div>
            '.$input.'
        </div>
    </div>';

    foreach ($array_languages as $language) {
        if ($language != $default_language) {
            $json_content = $json_orig;
            $val = '';

            if(!empty($array_lang[$language][$field])) {
                $json_lang = json_decode($array_lang[$language][$field], true);
                if(is_array($json_lang)) {
                    $json_content = $json_lang;
                    if(isset($json_lang[$json_field]) && $json_lang[$json_field] != $json_orig[$json_field]) {
                        $val = $json_lang[$json_field];
                    }
                }
            }

            $icon_color = (empty(trim(strip_tags($val)))) ? 'orange' : 'green';

            if($input_type=='textarea') {
                $input_lang = '<textarea data-type="textarea" data-lang="'.$language.'" data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$custom_field.'" data-real_field="'.$field.'" data-json_field="'.$json_field.'" data-param=\''.htmlspecialchars(json_encode($json_content, JSON_HEX_APOS | JSON_HEX_QUOT)).'\' class="form-control field_translate">'.htmlspecialchars($val).'</textarea>';
            } else {
                $input_lang = '<input data-type="text" data-lang="'.$language.'" data-id="'.$array['id'].'" data-table="'.$table.'" data-field="'.$custom_field.'" data-real_field="'.$field.'" data-json_field="'.$json_field.'" data-param=\''.htmlspecialchars(json_encode($json_content, JSON_HEX_APOS | JSON_HEX_QUOT)).'\' type="text" class="form-control field_translate" value="'.htmlspecialchars($val).'">';
            }

            $html .= '<div class="col-md-4 column_field_translate">
                    <div class="input-group input-group-sm">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-white"><img style="height:14px;width:22px;" src="img/flags_lang/'.$language.'.png?v=3" /></span>
                        </div>
                        '.$input_lang.'
                        <div class="input-group-append">
                            <span class="input-group-text bg-white check_translate"><i style="color:'.$icon_color.'" class="status_translate_icon fas fa-circle"></i></span>
                        </div>
                    </div>
                </div>';
        }
    }

    $html .= '<hr class="mt-0 mb-3"></div>';
    return $html;
}
?>