<?php

include __DIR__ . '/../includes/header.php';



if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ADMIN_NO_PERMISSION'] ?? 'You do not have permission to access this page', 'danger');
    redirectTo(getCleanUrl('index'));
}

// Detect available languages
$lang_dir = __DIR__ . '/../languages/';
$languages = array_filter(glob($lang_dir . '*'), 'is_dir');
$lang_options = [];
foreach ($languages as $dir) {
    $code = basename($dir);
    $lang_options[$code] = $code;
}

// Detect subcategories (Virtual categories for consolidated lang.php)
$subcategories = ['all', 'admin', 'alerts', 'email', 'frontend', 'navigation'];

// Get selected language and subcategory
$selected_lang = $_GET['lang'] ?? array_key_first($lang_options);
$selected_subcat = $_GET['subcat'] ?? 'all';
$search = $_GET['search'] ?? '';

// --- Helper: Parse only top-level string key-value pairs ---
function parse_top_level_strings($file_contents)
{
    $matches = [];
    // Updated pattern to handle both single and double quoted values
    $pattern = "/^\s*'([A-Z0-9_]+)'\s*=>\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\"),\s*$/m";
    preg_match_all($pattern, $file_contents, $matches, PREG_SET_ORDER);
    $result = [];
    foreach ($matches as $m) {
        $key = $m[1];
        // Handle both single and double quoted values
        $value = !empty($m[2]) ? stripcslashes($m[2]) : stripcslashes($m[3]);
        $result[$key] = $value;
    }
    return $result;
}

function replace_top_level_strings($file_contents, $new_strings)
{
    $lines = explode("\n", $file_contents);
    // Updated pattern to handle both single and double quoted values
    $pattern = "/^\s*'([A-Z0-9_]+)'\s*=>\s*(?:'((?:[^'\\\\]|\\\\.)*)'|\"((?:[^\"\\\\]|\\\\.)*)\"),\s*$/";
    foreach ($lines as $i => $line) {
        if (preg_match($pattern, $line, $m)) {
            $key = $m[1];
            if (isset($new_strings[$key])) {
                // Use var_export for consistent, safe escaping
                $val = var_export($new_strings[$key], true);
                $lines[$i] = "    '" . $key . "' => $val,";
            }
        }
    }
    return implode("\n", $lines);
}

// Load strings
$strings = [];
$lang_file = $lang_dir . $selected_lang . '/lang.php';
if (file_exists($lang_file)) {
    $file_contents = file_get_contents($lang_file);
    $strings = parse_top_level_strings($file_contents);
}

// Filter by virtual subcategory
$base_strings = [];
foreach ($strings as $key => $value) {
    $match = false;
    switch ($selected_subcat) {
        case 'admin':
            if (preg_match('/^(ADMIN_|QUOTE_|INVOICE_|PRODUCT_|SNIPPET_|COUPON_|STAT_)/', $key))
                $match = true;
            break;
        case 'alerts':
            if (preg_match('/^(ALERT_)/', $key))
                $match = true;
            break;
        case 'email':
            if (preg_match('/^(EMAIL_)/', $key))
                $match = true;
            break;
        case 'navigation':
            if (preg_match('/^(NAV_|MENU_|HEADER_|FOOTER_)/', $key))
                $match = true;
            break;
        case 'frontend':
            // Logic for frontend: not admin, alerts, email, or navigation
            if (!preg_match('/^(ADMIN_|QUOTE_|INVOICE_|PRODUCT_|SNIPPET_|COUPON_|STAT_|ALERT_|EMAIL_|NAV_|MENU_|HEADER_|FOOTER_)/', $key))
                $match = true;
            break;
        case 'all':
        default:
            $match = true;
            break;
    }

    if ($match) {
        $base_strings[$key] = $value;
    }
}

// Filter by search
if ($search) {
    $base_strings = array_filter($base_strings, function ($v, $k) use ($search) {
        return stripos($k, $search) !== false || stripos($v, $search) !== false;
    }, ARRAY_FILTER_USE_BOTH);
}

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_texts'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_REQUEST_TRY_AGAIN'] ?? 'Invalid request. Please try again.', 'danger');
        redirectTo('admin/texts.php?lang=' . urlencode($selected_lang) . '&subcat=' . urlencode($selected_subcat));
        exit;
    }
    $updated = $strings;
    foreach ($base_strings as $key => $old_value) {
        if (isset($_POST['strings'][$key])) {
            // Sanitize input to prevent injection
            $new_value = $_POST['strings'][$key];
            // Remove any null bytes for security
            $new_value = str_replace("\0", '', $new_value);
            $updated[$key] = $new_value;
        }
    }
    $file_contents = file_get_contents($lang_file);
    $new_contents = replace_top_level_strings($file_contents, $updated);
    if (is_writable($lang_file) && file_put_contents($lang_file, $new_contents)) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_TEXTS_SAVED'] ?? 'Texts saved successfully.', 'success');
    } else {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_FAILED_SAVE_FILE_PERMISSIONS'] ?? 'Failed to save file. Check permissions.', 'danger');
    }
    redirectTo('admin/texts.php?lang=' . urlencode($selected_lang) . '&subcat=' . urlencode($selected_subcat));
    exit;
}

// Handle add new string
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_new'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_REQUEST_TRY_AGAIN'] ?? 'Invalid request. Please try again.', 'danger');
        redirectTo('admin/texts.php?lang=' . urlencode($selected_lang) . '&subcat=' . urlencode($selected_subcat));
        exit;
    }
    $new_key = trim($_POST['new_key'] ?? '');
    $new_value = trim($_POST['new_value'] ?? '');

    // Additional security: remove null bytes
    $new_key = str_replace("\0", '', $new_key);
    $new_value = str_replace("\0", '', $new_value);

    if ($new_key === '' || $new_value === '') {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_BOTH_KEY_VALUE_REQUIRED'] ?? 'Both key and value are required.', 'danger');
        redirectTo('admin/texts.php?lang=' . urlencode($selected_lang) . '&subcat=' . urlencode($selected_subcat));
        exit;
    }
    if (!preg_match('/^[A-Z0-9_]+$/', $new_key)) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_KEY_INVALID_FORMAT'] ?? 'Key must be uppercase letters, numbers, and underscores only.', 'danger');
        redirectTo('admin/texts.php?lang=' . urlencode($selected_lang) . '&subcat=' . urlencode($selected_subcat));
        exit;
    }
    $file_contents = file_get_contents($lang_file);
    $existing = parse_top_level_strings($file_contents);
    if (isset($existing[$new_key])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_KEY_ALREADY_EXISTS'] ?? 'This key already exists. Please choose a unique key.', 'danger');
        redirectTo('admin/texts.php?lang=' . urlencode($selected_lang) . '&subcat=' . urlencode($selected_subcat));
        exit;
    }
    // Insert new key just before the final ];
    $insert_pos = strrpos($file_contents, '];');
    if ($insert_pos === false) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_LANGUAGE_FILE_FORMAT'] ?? 'Invalid language file format.', 'danger');
        redirectTo('admin/texts.php?lang=' . urlencode($selected_lang) . '&subcat=' . urlencode($selected_subcat));
        exit;
    }
    $new_line = "    '" . $new_key . "' => " . var_export($new_value, true) . ",\n";
    $new_contents = substr($file_contents, 0, $insert_pos) . $new_line . substr($file_contents, $insert_pos);
    if (is_writable($lang_file) && file_put_contents($lang_file, $new_contents)) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_NEW_STRING_ADDED'] ?? 'New string added successfully.', 'success');
    } else {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_FAILED_SAVE_FILE_PERMISSIONS'] ?? 'Failed to save file. Check permissions.', 'danger');
    }
    redirectTo('admin/texts.php?lang=' . urlencode($selected_lang) . '&subcat=' . urlencode($selected_subcat));
    exit;
}
?>
<div class="container py-4">
    <h2 class="mb-4"><i class="bi bi-translate me-2"></i><?php echo $lang_admin['ADMIN_TEXTS_PAGE_TITLE'] ?? 'Edit Language Texts'; ?></h2>
    <?php if (isset($_SESSION['alert'])):
        echo $_SESSION['alert'];
        unset($_SESSION['alert']); endif; ?>
    <form method="get" class="row g-2 mb-3">
        <div class="col-md-3">
            <label for="lang" class="form-label"><?php echo $lang_admin['ADMIN_TEXTS_LBL_LANGUAGE'] ?? 'Language'; ?></label>
            <select name="lang" id="lang" class="form-select" onchange="this.form.submit()">
                <?php foreach ($lang_options as $code => $label): ?>
                    <option value="<?php echo htmlspecialchars($code); ?>" <?php if ($selected_lang === $code)
                           echo 'selected'; ?>><?php echo htmlspecialchars($label); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label for="subcat" class="form-label"><?php echo $lang_admin['ADMIN_TEXTS_LBL_CATEGORY'] ?? 'Category'; ?></label>
            <select name="subcat" id="subcat" class="form-select" onchange="this.form.submit()">
                <?php foreach ($subcategories as $cat): ?>
                    <option value="<?php echo $cat; ?>" <?php if ($selected_subcat === $cat)
                           echo 'selected'; ?>>
                        <?php echo ucfirst($cat); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-4">
            <label for="search" class="form-label"><?php echo $lang_admin['ADMIN_TEXTS_LBL_SEARCH'] ?? 'Search'; ?></label>
                value="<?php echo htmlspecialchars($search); ?>" placeholder="<?php echo $lang_admin['ADMIN_TEXTS_PLACEHOLDER_SEARCH'] ?? 'Search key or value...'; ?>"
                oninput="filterTable()">
        </div>
        <div class="col-md-2 d-flex align-items-end">
            <button type="submit" class="btn btn-outline-primary w-100"><?php echo $lang_admin['ADMIN_TEXTS_BTN_FILTER'] ?? 'Filter'; ?></button>
        </div>
    </form>
    <form method="post" class="mb-4 d-flex flex-wrap gap-2 align-items-end">
        <?php echo get_csrf_input_field(); ?>
        <div>
            <label for="new_key" class="form-label mb-0"><?php echo $lang_admin['ADMIN_TEXTS_LBL_NEW_KEY'] ?? 'New Key'; ?></label>
            <input type="text" name="new_key" id="new_key" class="form-control" required>
        </div>
        <div>
            <label for="new_value" class="form-label mb-0"><?php echo $lang_admin['ADMIN_TEXTS_LBL_NEW_VALUE'] ?? 'New Value'; ?></label>
            <input type="text" name="new_value" id="new_value" class="form-control" required>
        </div>
        <button type="submit" name="add_new" class="btn btn-primary"><i class="bi bi-plus-circle me-1"></i><?php echo $lang_admin['ADMIN_TEXTS_BTN_ADD_NEW'] ?? 'Add New'; ?></button>
    </form>
    <form method="post">
        <?php echo get_csrf_input_field(); ?>
        <table class="table table-bordered align-middle" id="textsTable">
            <thead>
                <tr>
                    <th style="width: 30%"><?php echo $lang_admin['ADMIN_TEXTS_TH_KEY'] ?? 'Key'; ?></th>
                    <th><?php echo $lang_admin['ADMIN_TEXTS_TH_VALUE'] ?? 'Value'; ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($base_strings as $key => $value): ?>
                    <tr>
                        <td><code><?php echo htmlspecialchars($key); ?></code></td>
                        <td><input type="text" class="form-control" name="strings[<?php echo htmlspecialchars($key); ?>]"
                                value="<?php echo htmlspecialchars($value); ?>"></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <button type="submit" name="save_texts" class="btn btn-success mt-3"><i class="bi bi-save me-1"></i><?php echo $lang['BUTTON_SAVE_ALL'] ?? 'Save All'; ?></button>
    </form>
</div>
<script>
    function filterTable() {
        var input = document.getElementById('search');
        var filter = input.value.toLowerCase();
        var table = document.getElementById('textsTable');
        var trs = table.getElementsByTagName('tr');
        for (var i = 1; i < trs.length; i++) {
            var tds = trs[i].getElementsByTagName('td');
            if (!tds.length) continue;
            var key = tds[0].textContent.toLowerCase();
            var val = tds[1].getElementsByTagName('input')[0].value.toLowerCase();
            trs[i].style.display = (key.indexOf(filter) > -1 || val.indexOf(filter) > -1) ? '' : 'none';
        }
    }
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>