<?php

namespace App\Services\Attendance;

use App\Models\AttendanceCommentTemplate;

class AttendanceCommentService
{
    private ?array $templates = null;

    public function commentFromScore($score, string $firstName = ''): ?string
    {
        if ($score === null || $score === '') {
            return null;
        }

        $score = (float) $score;
        $template = $this->templateForScore($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;
    }

    public function templateForScore(float $score): ?array
    {
        $templates = $this->loadTemplates();

        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;
    }

    public function clearCache(): void
    {
        $this->templates = null;
    }

    private function loadTemplates(): array
    {
        if ($this->templates !== null) {
            return $this->templates;
        }

        try {
            $this->templates = AttendanceCommentTemplate::query()
                ->where('is_active', 1)
                ->orderByDesc('min_score')
                ->get()
                ->map(fn ($row) => $row->toArray())
                ->all();
        } catch (\Throwable $e) {
            $this->templates = [];
        }

        return $this->templates;
    }
}
