<?php

namespace App\Services\ClassProgress;

class ClassProgressRuleService
{
    public function defaultStatus(): string
    {
        return 'on_track';
    }

    public function normalizeFlags($flags): ?array
    {
        $values = array_values(array_filter((array) $flags, static fn ($item) => $item !== '' && $item !== null));
        return $values === [] ? null : $values;
    }

    public function buildUnitChapterSummary(array $unitValues, array $chapterValues): ?string
    {
        $parts = [];
        $count = max(count($unitValues), count($chapterValues));
        for ($i = 0; $i < $count; $i++) {
            $unit = trim((string) ($unitValues[$i] ?? ''));
            $chapter = trim((string) ($chapterValues[$i] ?? ''));
            if ($unit === '' && $chapter === '') {
                continue;
            }
            $segment = $unit;
            if ($chapter !== '') {
                $segment = $segment !== '' ? $segment . ' / ' . $chapter : $chapter;
            }
            if ($segment === '') {
                continue;
            }
            $parts[] = $segment;
        }

        if ($parts === []) {
            return null;
        }

        $summary = implode(' ; ', $parts);
        return mb_strlen($summary) > 120 ? mb_substr($summary, 0, 120) : $summary;
    }

    public function ensureWeekEnd(string $weekStart, ?string $weekEnd): string
    {
        if ($weekEnd) {
            return $weekEnd;
        }

        try {
            $dt = new \DateTime($weekStart);
            $dt->modify('+6 days');
            return $dt->format('Y-m-d');
        } catch (\Exception $e) {
            return $weekStart;
        }
    }

    public function isWeekEndValid(string $weekStart, string $weekEnd): bool
    {
        return strtotime($weekEnd) >= strtotime($weekStart);
    }
}
