<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center py-3">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-globe me-3 fs-4"></i>
                        <h4 class="card-title mb-0 text-white"><?= __("admin.language") ?></h4>
                    </div>
                    <div class="d-flex gap-2">
                        <a href="<?= base_url('admincontrol/update_user_langauges/all') ?>" class="btn btn-warning text-dark">
                            <i class="fas fa-sync-alt me-2"></i><?= __("admin.update_languages") ?>
                        </a>
                        <a href="<?= base_url('admincontrol/translation_edit/'.$lang['id']) ?>" class="btn btn-light text-primary add-new" id="<?= $lang['id'] ?>">
                            <i class="fas fa-plus me-2"></i><?= __("admin.add_new") ?>
                        </a>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th class="border-0 ps-4 text-nowrap w-auto">
                                        <i class="fas fa-flag text-muted"></i>
                                    </th>
                                    <th class="border-0 text-nowrap"><?= __("admin.name") ?></th>
                                    <th class="border-0 text-center text-nowrap w-auto">
                                        <i class="fas fa-exclamation-triangle text-warning me-1"></i><?= __("admin.translation_missing_all") ?>
                                    </th>
                                    <th class="border-0 text-center text-nowrap w-auto">
                                        <i class="fas fa-align-right me-2 text-info"></i><?= __("admin.direction") ?>
                                    </th>
                                    <th class="border-0 text-center text-nowrap w-auto"><?= __("admin.is_default") ?></th>
                                    <th class="border-0 text-center text-nowrap w-auto"><?= __("admin.status") ?></th>
                                    <th class="border-0 text-end pe-4 text-nowrap w-auto"><?= __("admin.actions") ?></th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php
                            // Build code lookup: name => code, from the same languages.json used for merging
                            $_all_lang_map = [];
                            $_lj = FCPATH.'assets/data/languages.json';
                            if (file_exists($_lj)) {
                                $_all_lang_map = json_decode(file_get_contents($_lj), true) ?: [];
                            }
                            ?>
                            <?php foreach($language as $lang){ ?>
                            <?php $_lang_code = strtoupper(array_search($lang['name'], $_all_lang_map) ?: $lang['id']); ?>
                                <tr class="align-middle">
                                    <td class="ps-4">
                                        <img src="<?= base_url($lang['flag']) ?>" class="rounded" alt="<?= $lang['name'] ?>" onerror="this.onerror=null;this.style.display='none'">
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="fw-semibold"><?= $lang['name'] ?></span>
                                            <span class="badge bg-secondary bg-opacity-75 text-white font-monospace" style="font-size:.7rem;letter-spacing:.5px"><?= htmlspecialchars($_lang_code) ?></span>
                                            <?php if($lang['is_default']){ ?>
                                                <span class="badge bg-success">
                                                    <i class="fas fa-star me-1"></i><?= __('admin.default') ?>
                                                </span>
                                            <?php } ?>
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <div class="d-flex align-items-center justify-content-center">
                                            <span class="badge bg-<?= $lang['count']['missing'] > 0 ? 'warning' : 'success' ?> rounded-pill">
                                                <?= $lang['count']['missing'] ?> / <?= $language_count['all'] ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <?php if(isset($lang['rtl']) && $lang['rtl'] == '1'){ ?>
                                            <span class="badge bg-info text-white">
                                                <i class="fas fa-align-right me-1"></i><?= __('admin.rtl') ?>
                                            </span>
                                        <?php } else { ?>
                                            <span class="badge bg-light text-muted">
                                                <i class="fas fa-align-left me-1"></i><?= __('admin.ltr') ?>
                                            </span>
                                        <?php } ?>
                                    </td>
                                    <td class="text-center">
                                        <div class="form-check form-switch d-flex justify-content-center">
                                            <input class="form-check-input btn_default_lang btn_lang_toggle" type="checkbox" 
                                                   id="switchDefaultLang<?= $lang['id'] ?>" 
                                                   <?= ($lang['is_default'] == 1) ? "checked" : ""?> 
                                                   data-lang_id="<?= $lang['id'] ?>" 
                                                   data-column="is_default">
                                            <label class="form-check-label" for="switchDefaultLang<?= $lang['id'] ?>"></label>
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <div class="form-check form-switch d-flex justify-content-center">
                                            <input class="form-check-input btn_lang_toggle" type="checkbox" 
                                                   id="switchStatusLang<?= $lang['id'] ?>" 
                                                   <?= ($lang['status'] == 1) ? "checked" : ""?> 
                                                   data-lang_id="<?= $lang['id'] ?>" 
                                                   data-column="status">
                                            <label class="form-check-label" for="switchStatusLang<?= $lang['id'] ?>"></label>
                                        </div>
                                    </td>
                                    <td class="text-end pe-4">
                                        <div class="btn-group" role="group">
                                            <button class="btn btn-outline-info btn-sm open-details" title="<?= __('admin.import_export') ?>">
                                                <i class="fas fa-upload"></i>
                                            </button>
                                            <a href="<?= base_url('admincontrol/translation_edit/'.$lang['id']) ?>" 
                                               class="btn btn-outline-primary btn-sm edit-button" 
                                               id="<?= $lang['id'] ?>" 
                                               title="<?= __("admin.edit") ?>">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <?php if($lang['id'] != 1){ ?>
                                                <a class="btn btn-outline-secondary btn-sm" 
                                                   href="<?= base_url('admincontrol/translation/'.$lang['id']) ?>" 
                                                   title="<?= __("admin.translation") ?>">
                                                    <i class="fas fa-language"></i>
                                                </a>
                                            <?php } ?>
                                            <?php if (ENVIRONMENT !== 'demo'): ?>
                                                <?php if($lang['is_default'] == '0' && $lang['id'] != 1){ ?>
                                                    <button class="btn btn-outline-danger btn-sm detele-button" 
                                                            id="<?= $lang['id'] ?>" 
                                                            title="<?= __("admin.delete") ?>">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php } ?>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>

                                <tr class="details-tr d-none">
                                    <td colspan="6" class="p-0">
                                        <div class="bg-light border-top">
                                            <div class="p-4">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="card border-0 bg-white shadow-sm">
                                                            <div class="card-body text-center">
                                                                <h6 class="card-title text-primary mb-3">
                                                    <i class="fas fa-download me-2"></i><?= __('admin.export_language') ?>
                                                </h6>
                                                <p class="text-muted mb-3"><?= __('admin.want_to_export_language_file') ?></p>
                                                <a href="<?= base_url("admincontrol/language_export/".$lang['id']) ?>" 
                                                   target="_blank" 
                                                   class="btn btn-primary">
                                                    <i class="fas fa-file-export me-2"></i><?= __('admin.export_language') ?>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                    <?php if($lang['id'] != 1){ ?>
                                        <div class="col-md-6">
                                            <div class="card border-0 bg-white shadow-sm">
                                                <div class="card-body">
                                                    <h6 class="card-title text-success mb-3">
                                                        <i class="fas fa-upload me-2"></i><?= __('admin.import_language') ?>
                                                    </h6>
                                                    <form class="form-language">
                                                        <div class="lang-message mb-3"></div>
                                                        <input class="d-none" data-lang_file="<?= $lang['id'] ?>" type="file" name="file">
                                                        <input type="hidden" name="id" value="<?= $lang['id'] ?>">
                                                    </form>
                                                    <div class="d-grid gap-2">
                                                        <button type="button" 
                                                                data-lang_id="<?= $lang['id'] ?>" 
                                                                id="language_xls_upload_btn" 
                                                                class="btn btn-success">
                                                            <i class="fas fa-file-excel me-2"></i><?= __('admin.import_excel_file') ?>
                                                        </button>
                                                        <button type="button" 
                                                                id="language_zip_upload_btn" 
                                                                class="btn btn-info">
                                                            <i class="fas fa-file-archive me-2"></i><?= __('admin.import_language_package') ?>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php } else { ?>
                                        <div class="col-md-6">
                                            <div class="alert alert-warning border-0 shadow-sm">
                                                <i class="fas fa-exclamation-triangle me-2"></i>
                                                <?= __('admin.you_can_not_import_main_language') ?>
                                            </div>
                                        </div>
                                    <?php } ?>
                                </div>
                            </div>
                        </td>
                    </tr>
                            <?php } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="d-none">
    <form id="language_zip_upload_form" action="<?= base_url("admincontrol/language_zip_upload") ?>" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="language_zip_upload_input">
    </form>
</div>



<script type="text/javascript">
    $(document).on('click', '#language_xls_upload_btn', function(){
        $('input[data-lang_file="'+$(this).data('lang_id')+'"]').click();
    });

    $(document).on('change', 'input[type="file"][data-lang_file]', function(){
        $(this).closest('form').submit();
    });

    $(document).on('click', '#language_zip_upload_btn', function(){
        $('#language_zip_upload_input').click();
    });

    $(document).on('change', '#language_zip_upload_input', function(){
        $('#language_zip_upload_form').submit();
    });

    $(document).on('change', ".btn_lang_toggle", function(){
        let skip_change = false;
        let id = $(this).data('lang_id');
        let column = $(this).data('column');
        let status = this.checked ? 1 : 0;

        if (column == 'is_default' && !status) {
            Swal.fire('Warning', '<?= __('admin.please_select_another_language_as_default') ?>', 'warning');
            this.checked = !this.checked;
            skip_change = true;
        } else if (column == 'is_default') {
            if(!$('.btn_lang_toggle[data-lang_id="'+id+'"][data-column="status"]').prop('checked')) {
                Swal.fire('Warning', '<?= __('admin.inactive_language_can_not_be_set_as_default') ?>', 'warning');
                this.checked = !this.checked;
                skip_change = true;
            } else {
                $('.btn_default_lang').prop('checked', false);
            }
        } else {
            if($('.btn_lang_toggle[data-lang_id="'+id+'"][data-column="is_default"]').prop('checked')) {
                Swal.fire('Warning', '<?= __('admin.default_language_can_not_be_set_as_inactive') ?>', 'warning');
                this.checked = !this.checked;
                skip_change = true;
            }
        }

        if(!skip_change) {
            if (status && column == 'is_default') { 
                $('.default-badge').remove();
                $(this).closest('tr').find('td:nth-child(2) .badge').remove();
                $(this).closest('tr').find('td:nth-child(2)').append('<span class="badge bg-success ms-2"><i class="fas fa-star me-1"></i><?= __('admin.default') ?></span>');
            }

            $.ajax({
                url: "<?= base_url('admincontrol/lang_status_toggle')?>",
                type: "POST",
                dataType: "json",
                data: {
                    id:id,
                    status:status,
                    column:column
                },
                success: function (response) {    
                    if(response.reload) {
                        window.location.reload();
                    }
                    if(response.status) {
                        $('.notification-list.language').html(response.languages);
                    }
                }
            });
        }
    });

    $(".open-details").on('click', function(){
        $tr = $(this).parents("tr").next(".details-tr");
        if($tr.hasClass('d-none')){
            $tr.removeClass('d-none').hide().fadeIn(300);
        } else {
            $tr.fadeOut(300, function(){
                $(this).addClass('d-none');
            });
        }
    });

    $(".detele-button").on('click', function(){
        if(!confirm('<?= __('admin.are_you_sure') ?>')) return false;

        $this = $(this);
        $.ajax({
            url: '<?= base_url("admincontrol/delete_update_language") ?>',
            type: 'POST',
            dataType: 'json',
            data: {id: $this.attr("id")},
            beforeSend: function(){
                $this.prop("disabled", true);
            },
            complete: function(){
                $this.prop("disabled", false);
            },
            success: function(json){
                showToast('<?= __('admin.success') ?>', '<?= __('admin.language_deleted_successfully') ?>', 'success', 3000);
                $this.closest('tr').fadeOut(300, function() {
                    $(this).remove();
                    reindexTable();
                });
            },
        });
    });

    function reindexTable() {
        $('table tbody tr:not(.details-tr)').each(function(index) {
            $(this).find('.btn_lang_toggle').each(function() {
                let oldId = $(this).attr('id');
                let newId = oldId.replace(/\d+$/, index + 1);
                $(this).attr('id', newId);
                $(this).next('label').attr('for', newId);
            });
        });
    }

    $(".form-language").submit(function(evt){
        evt.preventDefault();
        var formData = new FormData($(this)[0]);
        formData = formDataFilter(formData);
        $this = $(this);

        $this.find('.btn-submit').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Loading...');
        $.ajax({
            url: '<?= base_url('admincontrol/language_import') ?>',
            type: 'POST',
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,
            data: formData,
            error: function(){
                $this.find('.btn-submit').prop('disabled', false).html($this.find('.btn-submit').data('original-text') || 'Submit');
            },
            success: function(json){
                $this.find('.btn-submit').prop('disabled', false).html($this.find('.btn-submit').data('original-text') || 'Submit');
                $this.find(".lang-message").html('');

                if(json['success']){
                    showToast('<?= __('admin.success') ?>', json['success'], 'success', 4000);
                    $this[0].reset();
                }
                if(json['warning']){
                    showToast('<?= __('admin.warning') ?>', json['warning'], 'warning', 4000);
                }
            },
        });
        return false;
    });
</script>
