<div class="container-fluid">
<div class="row">
        <div class="col-12">
            <!-- Page Header -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h2 class="h4 mb-1">
                        <i class="fas fa-<?= isset($lang) ? 'edit' : 'plus' ?> text-primary me-2"></i>
                        <?= isset($lang) ? __("admin.edit_language") : __("admin.add_language") ?>
                    </h2>
                    <p class="text-muted mb-0">
                        <?= isset($lang) ? __("admin.modify_language_settings") : __("admin.create_new_language") ?>
                    </p>
                </div>
                <div>
                    <a href="<?= base_url("admincontrol/language") ?>" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i><?= __("admin.back_to_languages") ?>
                    </a>
                </div>
            </div>

            <!-- Main Card -->
            <div class="card shadow-sm border-0">
                <div class="card-header bg-light border-bottom">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-cog text-primary me-2"></i>
                        <?= __("admin.language_settings") ?>
                    </h5>
                </div>

            <div class="card-body">
                <form id="language-form" enctype="multipart/form-data" action="<?= base_url("admincontrol/update_language") ?>" method="POST">
                    <input type="hidden" name="id" value="<?= isset($lang) ? $lang['id'] : '0' ?>">
                        
                        <div class="row">
                            <div class="col-md-6">
                    <div class="mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-language me-2 text-primary"></i><?= __("admin.language_name") ?>
                                        <span class="text-danger">*</span>
                                    </label>
                        <?php if(isset($lang) && isset($lang['name'])) { ?>
                                        <input name="name" value="<?= $lang['name'] ?>" class="form-control bg-light" readonly/>
                                        <div class="form-text text-muted">
                                            <i class="fas fa-info-circle me-1"></i><?= __("admin.language_name_cannot_be_changed") ?>
                                        </div>
                        <?php } else { ?>
                                            <select name="name" class="d-none" id="realLanguageSelect" required>
                                            <option value="" disabled selected><?= __('admin.select') ?> <?= __("admin.language_name") ?></option>
                                            <?php 
                                            $existing_languages = $this->db->query("SELECT name FROM language")->result_array();
                                            $existing_names = array_column($existing_languages, 'name');
                                            
                                            foreach ($languages as $key => $value) { 
                                                $is_existing = in_array($value, $existing_names);
                                                $is_current = (isset($lang) && $lang['name'] == $value);
                                                
                                                if($is_existing && !$is_current) {
                                            ?>
                                                <option value="<?= $value ?>" disabled><?= $value ?> (<?= __('admin.already_added') ?>)</option>
                                            <?php } else { ?>
                                                <option value="<?= $value ?>"><?= $value ?></option>
                                            <?php 
                                                }
                                            } 
                                            ?>
                                        </select>
                                        <div class="dropdown position-relative">
                                                <button class="btn btn-outline-primary dropdown-toggle w-100 text-start d-flex align-items-center justify-content-between shadow-sm" type="button" id="languageDropdownBtn" data-bs-toggle="dropdown">
                                                    <span id="selectedLanguageText" class="d-flex align-items-center">
                                                        <i class="fas fa-globe me-2 text-muted"></i>
                                                        <?= __('admin.select') ?> <?= __("admin.language_name") ?>
                                                    </span>
                                                </button>
                                                <ul class="dropdown-menu w-100 shadow border-0" style="max-height: 250px; overflow-y: auto; overflow-x: hidden; position: absolute;">
                                                    <li class="px-3 py-2 bg-light border-bottom">
                                                        <div class="input-group input-group-sm">
                                                            <span class="input-group-text bg-white border-end-0">
                                                                <i class="fas fa-search text-muted"></i>
                                                            </span>
                                                            <input type="text" class="form-control border-start-0" id="languageSearchInput" placeholder="<?= __('admin.search') ?> <?= __("admin.language_name") ?>..." autocomplete="off">
                                                        </div>
                                                    </li>
                                                    <?php 
                                                    foreach ($languages as $key => $value) { 
                                                        $is_existing = in_array($value, $existing_names);
                                                        $is_current = (isset($lang) && $lang['name'] == $value);
                                                        $is_disabled = $is_existing && !$is_current;
                                                        
                                                        $language_flag = '';
                                                        $lang_lower = strtolower($value);
                                                        
                                                        foreach ($flags_code as $flag_key => $flag_value) {
                                                            $flag_lower = strtolower($flag_key);
                                                            if (
                                                                strpos($lang_lower, $flag_lower) !== false || 
                                                                strpos($flag_lower, $lang_lower) !== false ||
                                                                ($lang_lower == 'english' && in_array($flag_lower, ['united-states', 'united-kingdom'])) ||
                                                                ($lang_lower == 'spanish' && $flag_lower == 'spain') ||
                                                                ($lang_lower == 'french' && $flag_lower == 'france') ||
                                                                ($lang_lower == 'german' && $flag_lower == 'germany') ||
                                                                ($lang_lower == 'portuguese' && $flag_lower == 'portugal') ||
                                                                ($lang_lower == 'chinese' && $flag_lower == 'china') ||
                                                                ($lang_lower == 'arabic' && $flag_lower == 'saudi-arabia') ||
                                                                ($lang_lower == 'dutch' && $flag_lower == 'netherlands') ||
                                                                ($lang_lower == 'russian' && $flag_lower == 'russia') ||
                                                                ($lang_lower == 'bulgarian' && $flag_lower == 'bulgaria')
                                                            ) {
                                                                $language_flag = base_url($flag_value);
                                                                break;
                                                            }
                                                        }
                                                    ?>
                                                    <li>
                                                        <a class="dropdown-item d-flex align-items-center py-2 px-3 border-0 <?= $is_disabled ? 'disabled text-muted' : '' ?>" 
                                                           href="#" 
                                                           data-value="<?= $value ?>" 
                                                           data-flag="<?= $language_flag ?>"
                                                           data-disabled="<?= $is_disabled ? 'true' : 'false' ?>"
                                                           <?= $is_disabled ? 'style="pointer-events: none; cursor: not-allowed;"' : '' ?>>
                                                            <div class="flag-container me-3 d-flex align-items-center justify-content-center">
                                                                <?php if($language_flag): ?>
                                                                    <img src="<?= $language_flag ?>" width="28" height="20" class="rounded shadow-sm <?= $is_disabled ? 'opacity-50' : '' ?>" alt="flag" style="object-fit: cover;">
                                                                <?php else: ?>
                                                                    <div class="bg-light rounded d-flex align-items-center justify-content-center <?= $is_disabled ? 'opacity-50' : '' ?>" style="width: 28px; height: 20px;">
                                                                        <i class="fas fa-globe text-muted" style="font-size: 12px;"></i>
                                                                    </div>
                                                                <?php endif; ?>
                                                            </div>
                                                            <span class="fw-medium <?= $is_disabled ? 'text-decoration-line-through' : '' ?>">
                                                                <?= $value ?>
                                                                <?php if($is_disabled): ?>
                                                                    <small class="badge bg-secondary ms-2"><?= __('admin.already_added') ?></small>
                                                                <?php endif; ?>
                                                            </span>
                                                        </a>
                                                    </li>
                                                    <?php } ?>
                                                </ul>
                                        </div>
                                        <div class="form-text text-muted">
                                            <?php 
                                            $available_count = 0;
                                            $total_count = count($languages);
                                            foreach ($languages as $lang_name) {
                                                if(!in_array($lang_name, $existing_names)) {
                                                    $available_count++;
                                                }
                                            }
                                            $existing_count = $total_count - $available_count;
                                            ?>
                                            <i class="fas fa-lightbulb me-1"></i><?= __("admin.select_language_from_list") ?>
                                            <span class="badge bg-success ms-2"><?= $available_count ?> <?= __("admin.available") ?></span>
                                            <span class="badge bg-secondary ms-1"><?= $existing_count ?> <?= __("admin.already_added") ?></span>
                                        </div>
                        <?php } ?>
                                </div>
                    </div>

                            <div class="col-md-6">
                                <label class="form-label fw-semibold">
                                    <i class="fas fa-flag me-2 text-success"></i><?= __("admin.language_flag") ?>
                                </label>
                                <div class="border rounded p-3 bg-light" id="flagSelector">
                                    <div class="row g-2">
                            <?php
                                $selected = isset($lang['flag']) ? $lang['flag'] : null;
                                            $__flag_index = 0;
                            ?>
                            <?php foreach ($flags_code as $key => $value) { ?>
                                            <div class="col-auto flag-option">
                                                <input data-flag_code="<?= $key ?>" 
                                                       <?= $selected == $value ? 'checked' : '' ?> 
                                                       type="radio" 
                                                       name="flag" 
                                                       value="<?= $value ?>" 
                                                       id="flag_<?= $key ?>"
                                                       class="btn-check flag-radio">
                                                <label class="btn btn-outline-secondary btn-sm lang_edit_flag_btn" for="flag_<?= $key ?>" title="<?= ucfirst($key) ?>">
                                                    <img src="<?= base_url($value) ?>" alt="<?= $key ?>" class="rounded">
                                    </label>
                                            </div>
                            <?php } ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <hr class="my-4">

                        <div class="row">
                            <div class="col-md-4">
                            <div class="mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-toggle-on me-2 text-info"></i><?= __("admin.status") ?>
                                    </label>
                                <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="statusSwitch" name="status" value="1" 
                                               <?= (isset($lang) && $lang['status'] == '1') ? "checked" :  '' ?>>
                                        <label class="form-check-label" for="statusSwitch">
                                            <?= __("admin.active") ?>
                                        </label>
                                    </div>
                                    <div class="form-text text-muted"><?= __("admin.enable_disable_language") ?></div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-star me-2 text-warning"></i><?= __("admin.set_default") ?>
                                    </label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="defaultSwitch" name="is_default" value="1" 
                                               <?= (isset($lang) && $lang['is_default'] == '1') ? "checked" :  '' ?>>
                                        <label class="form-check-label" for="defaultSwitch">
                                            <?= __("admin.default_language") ?>
                                        </label>
                                    </div>
                                    <div class="form-text text-muted"><?= __("admin.default_language_description") ?></div>
                            </div>
                        </div>

                            <div class="col-md-4">
                            <div class="mb-3">
                                    <label class="form-label fw-semibold">
                                        <i class="fas fa-text-width me-2 text-danger"></i><?= __("admin.is_rtl") ?>
                                    </label>
                                <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="rtlSwitch" name="is_rtl" value="1" 
                                               <?= (isset($lang) && $lang['is_rtl'] == '1') ? "checked" :  '' ?>>
                                        <label class="form-check-label" for="rtlSwitch">
                                            <?= __("admin.right_to_left") ?>
                                        </label>
                                    </div>
                                    <div class="form-text text-muted"><?= __("admin.rtl_language_description") ?></div>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex gap-3 pt-3">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i><?= __("admin.save_changes") ?>
                            </button>
                            <a href="<?= base_url("admincontrol/language") ?>" class="btn btn-outline-secondary">
                                <i class="fas fa-times me-2"></i><?= __("admin.cancel") ?>
                            </a>
                    </div>
                </form>
                </div>
            </div>
        </div> 
    </div>
</div>



<script type="text/javascript">
document.addEventListener('DOMContentLoaded', (event) => {
    let languages = null;
    let countries_with_languages = null;

    fetch("<?= base_url('assets/data/countries_with_languages.json'); ?>")
    .then(response => response.json())
    .then(data => { countries_with_languages = data; });

    fetch("<?= base_url('assets/data/languages.json'); ?>")
    .then(response => response.json())
    .then(data => { languages = data; });

    // Handle custom dropdown with flag images
    const customDropdownItems = document.querySelectorAll('.dropdown .dropdown-item');
    const realSelect = document.getElementById('realLanguageSelect');
    const selectedText = document.getElementById('selectedLanguageText');
    const searchInput = document.getElementById('languageSearchInput');
    
    // Language search functionality
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const dropdownItems = document.querySelectorAll('.dropdown .dropdown-item');
            
            dropdownItems.forEach(item => {
                const languageName = item.textContent.toLowerCase();
                const listItem = item.closest('li');
                
                if (listItem) {
                    if (languageName.includes(searchTerm)) {
                        listItem.style.display = '';
                    } else {
                        listItem.style.display = 'none';
                    }
                }
            });
        });
        
        searchInput.addEventListener('click', function(e) {
            e.stopPropagation();
        });
        document.getElementById('languageDropdownBtn').addEventListener('show.bs.dropdown', function() {
            setTimeout(() => {
                searchInput.value = '';
                searchInput.focus();
                document.querySelectorAll('.dropdown .dropdown-item').forEach(item => {
                    const listItem = item.closest('li');
                    if (listItem) {
                        listItem.style.display = '';
                    }
                });
            }, 100);
        });
    }
    
    if (customDropdownItems.length > 0) {
        customDropdownItems.forEach(item => {
            item.addEventListener('click', function(e) {
                e.preventDefault();
                
                const isDisabled = this.getAttribute('data-disabled') === 'true';
                if (isDisabled) return;
                
                const value = this.getAttribute('data-value');
                const flagUrl = this.getAttribute('data-flag');
                
                realSelect.value = value;
                let displayText = '';
                if (flagUrl) {
                    displayText = '<img src="' + flagUrl + '" width="24" height="18" class="rounded shadow-sm me-2" alt="flag" style="object-fit: cover;"><span class="fw-medium">' + value + '</span>';
                } else {
                    displayText = '<div class="bg-light rounded d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 18px;"><i class="fas fa-globe text-muted" style="font-size: 10px;"></i></div><span class="fw-medium">' + value + '</span>';
                }
                selectedText.innerHTML = displayText;
                filterFlagsByLanguage(value);
                const dropdown = bootstrap.Dropdown.getInstance(document.getElementById('languageDropdownBtn'));
                if (dropdown) dropdown.hide();
            });
        });
    }

    const languageDropdown = document.querySelector('select[name="name"]:not(.d-none)');
    const languageInput = document.querySelector('input[name="name"]');
    
    function findFlagForLanguage(languageName) {
        if (!languageName) return '';
        
        const lang_lower = languageName.toLowerCase();
        
        // Check all flag options to find matching flag
        const flagOptions = <?= json_encode($flags_code) ?>;
        
        for (const [flag_key, flag_value] of Object.entries(flagOptions)) {
            const flag_lower = flag_key.toLowerCase();
            if (
                lang_lower.includes(flag_lower) || 
                flag_lower.includes(lang_lower) ||
                (lang_lower === 'english' && ['united-states', 'united-kingdom'].includes(flag_lower)) ||
                (lang_lower === 'spanish' && flag_lower === 'spain') ||
                (lang_lower === 'french' && flag_lower === 'france') ||
                (lang_lower === 'german' && flag_lower === 'germany') ||
                (lang_lower === 'portuguese' && flag_lower === 'portugal') ||
                (lang_lower === 'chinese' && flag_lower === 'china') ||
                (lang_lower === 'arabic' && flag_lower === 'saudi-arabia') ||
                (lang_lower === 'dutch' && flag_lower === 'netherlands') ||
                (lang_lower === 'russian' && flag_lower === 'russia') ||
                (lang_lower === 'bulgarian' && flag_lower === 'bulgaria')
            ) {
                return '<?= base_url() ?>' + flag_value;
            }
        }
        return '';
    }
    
    function displayLanguageFlag(languageName, container) {
        // Remove existing flag
        const existingFlag = container.querySelector('.language-flag-display');
        if (existingFlag) existingFlag.remove();
        
        const flagUrl = findFlagForLanguage(languageName);
        
        if (flagUrl) {
            const flagDisplay = document.createElement('span');
            flagDisplay.className = 'language-flag-display ms-2';
            flagDisplay.innerHTML = '<img src="' + flagUrl + '" width="24" height="24" class="rounded border" alt="flag">';
            container.appendChild(flagDisplay);
            console.log('Flag displayed for ' + languageName + ':', flagUrl);
        } else {
            console.log('No flag found for language:', languageName);
        }
    }
    
    // Handle NEW language creation (dropdown)
    if (languageDropdown) {
        function updateDropdownFlag() {
            const selectedValue = languageDropdown.value;
            if (selectedValue) {
                displayLanguageFlag(selectedValue, languageDropdown.parentNode);
            }
        }
        
        languageDropdown.addEventListener('change', updateDropdownFlag);
        setTimeout(updateDropdownFlag, 200);
    }
    
    // Handle EXISTING language editing (readonly input)
    if (languageInput) {
        function updateInputFlag() {
            const languageName = languageInput.value;
            if (languageName) {
                displayLanguageFlag(languageName, languageInput.parentNode);
            }
        }
        
        setTimeout(updateInputFlag, 200);
    }

    // Function to filter flags based on selected language
    function filterFlagsByLanguage(langName) {
        if (!langName || !languages || !countries_with_languages) return;
        
            let langCode = Object.keys(languages).find(key => languages[key] === langName);
            let country = countries_with_languages.filter(function (e) {
                let languages = e.languages.split(",");
                return languages.indexOf(langCode) != -1;
            });

            if(country.length > 0) {
            document.querySelectorAll('.flag-option').forEach(function(el) {
                el.style.display = 'none';
                });
                for (let index = 0; index < country.length; index++) {
                    const iso_code = country[index].iso_code.toLowerCase();
                const el = document.querySelector('.flag-option input[data-flag_code="'+iso_code+'"]');
                if (el && el.closest('.flag-option')) {
                    const container = el.closest('.flag-option');
                    container.style.display = 'block';
                    container.classList.remove('d-none');
                    if(index == 0 && !document.querySelector('.flag-radio:checked')) { 
                        el.click();
                    }
                    }
                }
            } else {
            document.querySelectorAll('.flag-option').forEach(function(el) {
                el.style.display = 'block';
            });
        }
    }

    let selectElem = document.querySelector('select[name="name"]');
    let inputElem = document.querySelector('input[name="name"]');
    
    if (selectElem) {
        // NEW language creation - dropdown exists
        selectElem.addEventListener('change', function() {
            filterFlagsByLanguage(this.value);
        });
    }
    
    if (inputElem) {
        // EXISTING language editing - readonly input exists
        setTimeout(function() {
            if (inputElem.value && inputElem.value !== '') {
                filterFlagsByLanguage(inputElem.value);
            }
        }, 500); // Wait for data to load
    }

    // Function to scroll to selected flag and highlight it
    function scrollToSelectedFlag(radioElement) {
        const flagSelector = document.getElementById('flagSelector');
        const flagContainer = radioElement.closest('.flag-option');
        
        if (flagSelector && flagContainer) {
            // Calculate position to scroll to center the selected flag
            const containerRect = flagSelector.getBoundingClientRect();
            const flagRect = flagContainer.getBoundingClientRect();
            
            // Calculate scroll position to center the flag
            const scrollTop = flagSelector.scrollTop + (flagRect.top - containerRect.top) - (containerRect.height / 2) + (flagRect.height / 2);
            
            // Smooth scroll to the selected flag
            flagSelector.scrollTo({
                top: scrollTop,
                behavior: 'smooth'
            });
            
            // Add visual highlight effect
            highlightSelectedFlag(flagContainer);
        }
    }

    // Function to add visual highlight to selected flag
    function highlightSelectedFlag(flagContainer) {
        // Remove previous highlights
        document.querySelectorAll('.flag-option').forEach(function(el) {
            el.classList.remove('lang_flag_selected');
        });
        
        // Add highlight to selected flag
        flagContainer.classList.add('lang_flag_selected');
        
        // Brief flash effect
        flagContainer.style.animation = 'none';
        setTimeout(() => {
            flagContainer.style.animation = 'lang_flag_highlight 0.6s ease-in-out';
        }, 10);
    }



    // Listen for flag radio button changes to update highlighting
    document.querySelectorAll('.flag-radio').forEach(function(radio) {
        radio.addEventListener('change', function() {
            if (this.checked) {
                const flagContainer = this.closest('.flag-option');
                highlightSelectedFlag(flagContainer);
            }
        });
    });

    // Initialize highlighting for already selected flag on page load
    const alreadySelectedFlag = document.querySelector('.flag-radio:checked');
    if (alreadySelectedFlag) {
        const flagContainer = alreadySelectedFlag.closest('.flag-option');
        if (flagContainer) {
            flagContainer.classList.add('lang_flag_selected');
        }
    }
    
    // Form submission handling
    document.getElementById('language-form').addEventListener('submit', function(e) {
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i><?= __("admin.saving") ?>';
        
        // Form will submit normally, button will be reset on page reload
    });
});
</script>

