<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Simulatore contabilità
 *
 * @package    mod_mtcontabilita
 * @copyright  2026 Mediatouch 2000 Srl <https://www.mediatouch.it>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @author     Marco Cappuccio <m.cappuccio@mediatouch.it>
 */

namespace mod_mtcontabilita;

/**
 * currency class.
 */
final class currency {

    /**
     * normalize
     */
    public static function normalize(string $str, ?string $lang = null): string {
        $str = trim($str);
        if ($str === '') {
            return '';
        }

        if ($lang === null) {
            $lang = current_language();
        }
        $isitalian = (substr($lang, 0, 2) === 'it');

        // Rimuovo spazi (anche NBSP).
        $str = preg_replace('/[[:space:]\x{00A0}]+/u', '', $str);

        if ($isitalian) {
            if (strpos($str, ',') !== false) {
                // IT: 1.234,56 -> 1234.56 .
                $str = str_replace('.', '', $str);
                $str = str_replace(',', '.', $str);
            } else {
                // Niente virgola:
                // Se i punti sono migliaia (es: 1.111 / 12.345 / 1.234.567) li tolgo
                // Regex: un punto seguito da esattamente 3 cifre, ripetibile fino a fine stringa.
                if (preg_match('/^\d{1,3}(\.\d{3})+$/', $str)) {
                    $str = str_replace('.', '', $str);
                }
                // Altrimenti lascio il punto (caso EN-friendly: 1234.56).
            }
        } else {
            $str = str_replace(',', '', $str);
        }

        return $str;
    }

    /**
     * has fraction
     */
    public static function has_fraction(string $normalized): bool {
        if ($normalized === '') {
            return false;
        }
        $n = (float)$normalized;
        $frac = abs($n - floor($n));
        return $frac > 0.0000001;
    }
}
