<?php
/**
 * NROI Match Point System
 * Points per match = (Level points) × (number of disciplines)
 *
 * Level I   = 1 point
 * Level II  = 2 points
 * Level III = 3 points
 * Level IV  = 8 points
 * Level V   = 12 points
 *
 * Example: Level IV match with 3 disciplines (e.g. HG, PCC, MR) = 8 × 3 = 24 points
 */

if (!function_exists('nroi_get_level_points')) {
    /**
     * Get base points for a match level (single discipline).
     * @param string $matchLevel e.g. "Level 1", "Level 2", "Level I", "Level II"
     * @return int points for that level, or 0 if unknown
     */
    function nroi_get_level_points($matchLevel) {
        $level = trim((string) $matchLevel);
        $map = [
            '1' => 1, '2' => 2, '3' => 3, '4' => 8, '5' => 12,
            'i' => 1, 'ii' => 2, 'iii' => 3, 'iv' => 8, 'v' => 12,
        ];
        // Match "Level 1", "Level 2", "Level I", "Level II", etc.
        if (preg_match('/Level\s*(\d+|I{1,3}|IV|V)/i', $level, $m)) {
            $key = strtolower($m[1]);
            if (isset($map[$key])) {
                return $map[$key];
            }
        }
        // Fallback: last character as number
        $num = (int) preg_replace('/\D/', '', $level);
        if ($num >= 1 && $num <= 5) {
            return [1 => 1, 2 => 2, 3 => 3, 4 => 8, 5 => 12][$num];
        }
        return 0;
    }
}

if (!function_exists('nroi_count_disciplines')) {
    /**
     * Count disciplines from range_master string (comma-separated).
     * @param string $rangeMaster e.g. "HG, PCC, MR" or single "IPSC"
     * @return int at least 1 if any non-empty value
     */
    function nroi_count_disciplines($rangeMaster) {
        if (trim((string) $rangeMaster) === '') {
            return 1; // backward compat: treat as one discipline
        }
        $parts = array_map('trim', explode(',', $rangeMaster));
        $parts = array_filter($parts, function ($v) { return $v !== ''; });
        $n = count($parts);
        return $n >= 1 ? $n : 1;
    }
}

if (!function_exists('nroi_compute_match_points')) {
    /**
     * Compute total points for a match: level_points × discipline_count.
     * @param string $matchLevel
     * @param string $rangeMaster disciplines string (comma-separated)
     * @return int total points for that match
     */
    function nroi_compute_match_points($matchLevel, $rangeMaster) {
        $levelPts = nroi_get_level_points($matchLevel);
        $discCount = nroi_count_disciplines($rangeMaster);
        return $levelPts * $discCount;
    }
}
