<?php

/**
 * escape_javascript() — JavaScript String Escaping Helper
 *
 * Safely escapes a PHP string for embedding inside a JavaScript string literal.
 * Prevents XSS when injecting server data into inline onclick handlers or JS vars.
 *
 * Usage (in view files):
 *   onclick='fn("<?= escape_javascript($value) ?>")'
 *
 * Output:
 *   String with quotes, backslashes, newlines, and special characters escaped
 *   so the result is safe to embed inside a single or double-quoted JS string.
 *
 * This is NOT a substitute for json_encode() when building JS objects or arrays.
 * Use json_encode() with JSON_HEX_* flags for full JSON embedding.
 *
 * @package Inveetaire
 * @ref     PILOT-006, BETA-001
 */

if (!function_exists('escape_javascript')) {

    /**
     * Escape a string for safe embedding inside a JavaScript string literal.
     *
     * Escapes:
     *   - Backslashes (\)
     *   - Single quotes (')
     *   - Double quotes (")
     *   - Newlines (\n, \r)
     *   - Null bytes
     *   - Unicode line/paragraph separators (U+2028, U+2029)
     *
     * @param  string $value The raw PHP string to escape.
     * @return string        The escaped string, safe for JS string embedding.
     */
    function escape_javascript(string $value): string
    {
        $replacements = [
            "\\"   => '\\\\',
            "\r\n" => '\\n',
            "\r"   => '\\n',
            "\n"   => '\\n',
            "'"    => "\\'",
            '"'    => '\\"',
            "\0"   => '',
            "\u{2028}" => '\\u2028',
            "\u{2029}" => '\\u2029',
        ];

        return strtr($value, $replacements);
    }

}
