<?php
/**
 * Guest UI string registry (CSV) and per-site overrides (wp_options).
 *
 * @package Maca_Menu_List
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Option key for restaurant-specific guest string overrides.
 */
function maca_menulist_guest_string_overrides_option_key() {
    return 'maca_menulist_guest_string_overrides';
}

/**
 * @return array<int, array{string_id: string, msgid: string, group: string}>
 */
function maca_menulist_get_guest_string_registry() {
    static $registry = null;

    if ($registry !== null) {
        return $registry;
    }

    $registry = array();
    $path     = MACA_MENULIST_PLUGIN_DIR . 'docs/GUEST-UI-STRINGS.csv';

    if (!is_readable($path)) {
        return $registry;
    }

    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Bundled guest CSV registry read.
    $handle = fopen($path, 'rb');

    if ($handle === false) {
        return $registry;
    }

    $header = fgetcsv($handle, 0, ',', '"', '\\');

    if ($header === false) {
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Bundled guest CSV registry read.
        fclose($handle);

        return $registry;
    }

    while (($row = fgetcsv($handle, 0, ',', '"', '\\')) !== false) {
        if (count($row) < 2) {
            continue;
        }

        $string_id = sanitize_key($row[0]);
        $msgid     = isset($row[1]) ? (string) $row[1] : '';

        if ($string_id === '' || $msgid === '') {
            continue;
        }

        $group = isset($row[2]) ? (string) $row[2] : '';

        $registry[] = array(
            'string_id' => $string_id,
            'msgid'     => $msgid,
            'group'     => $group,
        );
    }

    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Bundled guest CSV registry read.
    fclose($handle);

    return $registry;
}

/**
 * @return array<string, array{local?: string, en?: string}>
 */
function maca_menulist_get_guest_string_overrides() {
    $stored = get_option(maca_menulist_guest_string_overrides_option_key(), array());

    if (!is_array($stored)) {
        return array();
    }

    $out = array();

    foreach ($stored as $msgid => $row) {
        if (!is_string($msgid) || $msgid === '' || !is_array($row)) {
            continue;
        }

        $entry = array();

        if (isset($row['local']) && is_string($row['local']) && $row['local'] !== '') {
            $entry['local'] = $row['local'];
        }

        if (isset($row['en']) && is_string($row['en']) && $row['en'] !== '') {
            $entry['en'] = $row['en'];
        }

        if ($entry !== array()) {
            $out[ $msgid ] = $entry;
        }
    }

    return $out;
}

/**
 * Bundled default for the site local language.
 *
 * @param string $msgid English message id.
 * @return string
 */
function maca_menulist_get_guest_string_bundled_local($msgid) {
    $from_catalog = maca_menulist_lookup_guest_catalog_string($msgid);

    if ($from_catalog !== null) {
        return $from_catalog;
    }

    return $msgid;
}

/**
 * @param string $msgid English message id.
 * @param bool   $for_local True = local column, false = English for guests.
 * @return string|null Null = no override, use bundled/default chain.
 */
function maca_menulist_lookup_guest_string_override($msgid, $for_local) {
    $overrides = maca_menulist_get_guest_string_overrides();

    if (!isset($overrides[ $msgid ])) {
        return null;
    }

    $key = $for_local ? 'local' : 'en';

    if (!isset($overrides[ $msgid ][ $key ])) {
        return null;
    }

    return $overrides[ $msgid ][ $key ];
}

/**
 * Effective guest-facing string (overrides → bundle → gettext).
 *
 * @param string $msgid English message id.
 * @param bool   $for_local Whether guest chose local language.
 * @return string
 */
function maca_menulist_resolve_guest_string($msgid, $for_local) {
    if (!$for_local) {
        $override = maca_menulist_lookup_guest_string_override($msgid, false);

        return $override !== null ? $override : $msgid;
    }

    $override = maca_menulist_lookup_guest_string_override($msgid, true);

    if ($override !== null) {
        return $override;
    }

    $from_catalog = maca_menulist_lookup_guest_catalog_string($msgid);

    if ($from_catalog !== null) {
        return $from_catalog;
    }

    return maca_menulist_translate_without_guest_filter($msgid);
}

/**
 * Persist overrides from settings POST.
 */
function maca_menulist_save_guest_string_overrides_from_post() {
    if (!function_exists('maca_menulist_guest_ui_strings_available') || !maca_menulist_guest_ui_strings_available()) {
        return;
    }

    if (!isset($_POST['maca_guest_text']) || !is_array($_POST['maca_guest_text'])) {
        return;
    }

    $by_slug = array();

    foreach (maca_menulist_get_guest_string_registry() as $row) {
        $by_slug[ $row['string_id'] ] = $row['msgid'];
    }

    $raw     = wp_unslash($_POST['maca_guest_text']);
    $saved   = array();
    $code   = maca_menulist_guest_translation_file_code();
    $bundle = maca_menulist_get_guest_translation_catalog($code);

    foreach ($raw as $slug => $fields) {
        $slug = sanitize_key((string) $slug);

        if ($slug === '' || !isset($by_slug[ $slug ]) || !is_array($fields)) {
            continue;
        }

        $msgid = $by_slug[ $slug ];
        $local = isset($fields['local']) ? sanitize_textarea_field((string) $fields['local']) : '';
        $en    = isset($fields['en']) ? sanitize_textarea_field((string) $fields['en']) : '';

        $default_local = isset($bundle[ $msgid ]) && is_string($bundle[ $msgid ]) ? $bundle[ $msgid ] : $msgid;
        $default_en    = $msgid;

        $entry = array();

        if ($local !== '' && $local !== $default_local) {
            $entry['local'] = $local;
        }

        if ($en !== '' && $en !== $default_en) {
            $entry['en'] = $en;
        }

        if ($entry !== array()) {
            $saved[ $msgid ] = $entry;
        }
    }

    update_option(maca_menulist_guest_string_overrides_option_key(), $saved, false);
}
