<?php

use App\Models\AttendanceCommentTemplateModel;

if (!function_exists('attendance_comment_from_score')) {
    function attendance_comment_from_score($score, string $firstName = ''): ?string
    {
        if ($score === null || $score === '') {
            return null;
        }

        $score = (float) $score;
        $template = attendance_comment_template_for_score($score);
        if ($template === null) {
            return null;
        }

        $text = trim((string) ($template['template_text'] ?? ''));
        if ($text === '') {
            return null;
        }

        $name = trim($firstName) !== '' ? trim($firstName) : 'This student';
        $lastChar = $name !== '' ? substr($name, -1) : '';
        $namePossessive = ($name === 'This student')
            ? "This student's"
            : ($lastChar === 's' || $lastChar === 'S' ? ($name . "'") : ($name . "'s"));
        if (strpos($text, '{name}') !== false) {
            return str_replace('{name}', $namePossessive, $text);
        }

        return $namePossessive . ' ' . $text;
    }
}

if (!function_exists('attendance_comment_template_for_score')) {
    function attendance_comment_template_for_score(float $score): ?array
    {
        static $templates = null;

        if ($templates === null) {
            try {
                $model = new AttendanceCommentTemplateModel();
                $templates = $model->getActiveTemplates();
            } catch (\Throwable $e) {
                $templates = [];
            }
        }

        foreach ($templates as $template) {
            $min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0;
            $max = isset($template['max_score']) ? (float) $template['max_score'] : 100.0;
            if ($score >= $min && $score <= $max) {
                return $template;
            }
        }

        return null;
    }
}
