<?php

namespace BitApps\PiPro\src\MixInputFunctions;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

final class MathFunctions
{
    public static function average($numbers)
    {
        $numbers = \is_string($numbers) ? explode(',', $numbers) : $numbers;

        return array_sum($numbers) / \count($numbers);
    }

    public static function floor($number)
    {
        if (!is_numeric($number)) {
            return;
        }

        return floor($number);
    }

    public static function min($numbers)
    {
        $numbers = \is_string($numbers) ? explode(',', $numbers) : $numbers;

        return min($numbers);
    }

    public static function max($numbers)
    {
        $numbers = \is_string($numbers) ? explode(',', $numbers) : $numbers;

        return max($numbers);
    }

    public static function absolute($params)
    {
        $number = $params[0] ?? null;
        if (!is_numeric($number)) {
            return;
        }

        return abs($number);
    }

    public static function round($number)
    {
        if (!is_numeric($number)) {
            return;
        }

        return round($number);
    }

    public static function celi($params)
    {
        $number = $params[0] ?? null;
        if (!is_numeric($number)) {
            return;
        }

        return ceil((float) $number);
    }

    public static function parseNumber($numbers)
    {
        return \floatval($numbers);
    }

    public static function formatNumber($numbers)
    {
        return number_format($numbers);
    }

    /**
     * Math expression with arithmetic operations.
     *
     * Supported Operations:
     * + - Addition
     * - - Subtraction
     * * - Multiplication
     * / - Division
     * % - Modulo (remainder) - when used between numbers (e.g., 10 % 3 = 1)
     * ** - Exponentiation (power)
     * ^ - Exponentiation (converted to **)
     * () - Parentheses for grouping
     * % - Percentage - when used after a number (e.g., 50% = 0.5)
     *
     * @param mixed $params
     *
     * @return float|string
     */
    public static function math($params)
    {
        $expression = $params[0] ?? '';

        if (!\is_string($expression) || empty($expression)) {
            return '';
        }

        return MathParser::evaluate($expression);
    }
}
