<?php
ob_start();
include 'db.php';
include 'handlers/language_handler.php';
include 'layout.php';

$language_handler = new LanguageHandler($conn);

// Handle language switching
if (isset($_POST['switch_language'])) {
    $language_handler->setLanguage($_POST['language_code']);
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle translation updates
if (isset($_POST['update_translation'])) {
    $key = $_POST['key'];
    $value = $_POST['value'];
    $language_code = $_POST['language_code'];
    
    $stmt = $conn->prepare("INSERT INTO translations (language_code, `key`, `value`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `value` = ?");
    $stmt->bind_param("ssss", $language_code, $key, $value, $value);
    $stmt->execute();
    
    $_SESSION['success'] = __('translation_updated', 'Translation updated successfully');
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle adding new translation (removed - all translations are pre-populated)

$current_language = $language_handler->getCurrentLanguage();
$available_languages = $language_handler->getAvailableLanguages();
$is_rtl = $language_handler->isRTL();
$current_language_info = $language_handler->getCurrentLanguageInfo();

// Get all translations for current language
$stmt = $conn->prepare("SELECT * FROM translations WHERE language_code = ? ORDER BY `key`");
$stmt->bind_param("s", $current_language);
$stmt->execute();
$result = $stmt->get_result();
$translations = [];
while ($row = $result->fetch_assoc()) {
    $translations[] = $row;
}
?>

<body>
<div class="main-wrapper">
	<div class="page-wrapper">
		<div class="content">
			<div class="page-header">
				<div class="page-title">
					<h4><?= __('language_management', 'Language Management') ?></h4>
					<h6><?= __('manage_system_languages', 'Manage system languages and translations') ?></h6>
				</div>
			</div>

			<div class="card">
				<div class="card-body">
                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert">&times;</button>
                            <?= $_SESSION['success'] ?>
                        </div>
                        <?php unset($_SESSION['success']); ?>
                    <?php endif; ?>

                    <!-- Language Switcher -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <form method="POST" class="d-inline">
                                <div class="input-group">
                                    <select name="language_code" class="form-control" onchange="this.form.submit()">
                                        <?php foreach ($available_languages as $lang): ?>
                                            <option value="<?= $lang['code'] ?>" <?= $lang['code'] == $current_language ? 'selected' : '' ?>>
                                                <?= $lang['native_name'] ?> (<?= $lang['name'] ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <input type="hidden" name="switch_language" value="1">
                                </div>
                            </form>
                        </div>
                        <div class="col-md-6 text-right">
                            <span class="badge badge-info">
                                <?= __('current_language', 'Current') ?>: <?= $current_language ?>
                                <?php if ($is_rtl): ?>
                                    <span class="badge badge-warning">RTL</span>
                                <?php endif; ?>
                            </span>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><?= __('search', 'Search') ?>:</label>
                                <input type="text" id="searchTranslations" class="form-control" placeholder="<?= __('search_product', 'Search translations...') ?>">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label><?= __('context', 'Context') ?>:</label>
                                <select id="filterContext" class="form-control">
                                    <option value=""><?= __('all', 'All Contexts') ?></option>
                                    <option value="navigation"><?= __('navigation', 'Navigation') ?></option>
                                    <option value="buttons"><?= __('buttons', 'Buttons') ?></option>
                                    <option value="labels"><?= __('labels', 'Labels') ?></option>
                                    <option value="messages"><?= __('messages', 'Messages') ?></option>
                                    <option value="placeholders"><?= __('placeholders', 'Placeholders') ?></option>
                                    <option value="page_titles"><?= __('page_titles', 'Page Titles') ?></option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <button type="button" id="clearFilters" class="btn btn-secondary btn-block">
                                    <?= __('clear', 'Clear Filters') ?>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- All translations are pre-populated - no need to add new ones -->

                    <!-- Translations List -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title">
                                        <?= __('available_languages', 'Translations') ?> - <?= $current_language_info['native_name'] ?>
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead>
                                                <tr>
                                                    <th><?= __('translation_key', 'Key') ?></th>
                                                    <th><?= __('translation_value', 'Value') ?></th>
                                                    <th><?= __('context', 'Context') ?></th>
                                                    <th><?= __('actions', 'Actions') ?></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($translations as $translation): ?>
                                                    <tr>
                                                        <td><?= htmlspecialchars($translation['key']) ?></td>
                                                        <td>
                                                            <form method="POST" class="d-inline">
                                                                <input type="text" name="value" value="<?= htmlspecialchars($translation['value']) ?>" 
                                                                       class="form-control form-control-sm" style="min-width: 200px;">
                                                                <input type="hidden" name="key" value="<?= $translation['key'] ?>">
                                                                <input type="hidden" name="language_code" value="<?= $current_language ?>">
                                                                <button type="submit" name="update_translation" class="btn btn-sm btn-success mt-1">
                                                                    <?= __('save', 'Save') ?>
                                                                </button>
                                                            </form>
                                                        </td>
                                                        <td><?= htmlspecialchars($translation['context']) ?></td>
                                                        <td>
                                                            <button class="btn btn-sm btn-danger" onclick="deleteTranslation('<?= $translation['key'] ?>')">
                                                                <?= __('delete', 'Delete') ?>
                                                            </button>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
function deleteTranslation(key) {
    if (confirm('Are you sure you want to delete this translation?')) {
        // You can implement AJAX deletion here
        console.log('Delete translation:', key);
    }
}

// Search and filter functionality
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchTranslations');
    const contextFilter = document.getElementById('filterContext');
    const clearFilters = document.getElementById('clearFilters');
    const tableRows = document.querySelectorAll('tbody tr');

    function filterTranslations() {
        const searchTerm = searchInput.value.toLowerCase();
        const selectedContext = contextFilter.value;

        tableRows.forEach(row => {
            const key = row.cells[0].textContent.toLowerCase();
            const value = row.cells[1].textContent.toLowerCase();
            const context = row.cells[2].textContent.toLowerCase();

            const matchesSearch = key.includes(searchTerm) || value.includes(searchTerm);
            const matchesContext = !selectedContext || context === selectedContext;

            if (matchesSearch && matchesContext) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }

    searchInput.addEventListener('input', filterTranslations);
    contextFilter.addEventListener('change', filterTranslations);
    
    clearFilters.addEventListener('click', function() {
        searchInput.value = '';
        contextFilter.value = '';
        filterTranslations();
    });
});
</script>

</body>
</html>
