<?php

namespace App\Services\ExtraCharges;

use Illuminate\Support\Facades\DB;

class ExtraChargesMetaService
{
    public function getSchoolYears(string $fallbackYear = ''): array
    {
        $schoolYears = [];

        try {
            $rows = DB::table('additional_charges')
                ->selectRaw('DISTINCT school_year')
                ->whereNotNull('school_year')
                ->orderByDesc('school_year')
                ->get()
                ->map(fn ($row) => (array) $row)
                ->all();

            foreach ($rows as $row) {
                $val = (string) ($row['school_year'] ?? '');
                if ($val !== '' && !in_array($val, $schoolYears, true)) {
                    $schoolYears[] = $val;
                }
            }
        } catch (\Throwable $e) {
        }

        try {
            $rows = DB::table('invoices')
                ->selectRaw('DISTINCT school_year')
                ->whereNotNull('school_year')
                ->orderByDesc('school_year')
                ->get()
                ->map(fn ($row) => (array) $row)
                ->all();

            foreach ($rows as $row) {
                $val = (string) ($row['school_year'] ?? '');
                if ($val !== '' && !in_array($val, $schoolYears, true)) {
                    $schoolYears[] = $val;
                }
            }
        } catch (\Throwable $e) {
        }

        if (empty($schoolYears) && $fallbackYear !== '') {
            $schoolYears[] = $fallbackYear;
            if (str_contains($fallbackYear, '-')) {
                [$start] = explode('-', $fallbackYear) + [0 => ''];
                $start = (int) $start;
                if ($start > 0) {
                    for ($i = 1; $i <= 3; $i++) {
                        $schoolYears[] = ($start - $i) . '-' . (($start - $i) + 1);
                    }
                }
            }
        }

        rsort($schoolYears);

        return array_values(array_unique($schoolYears));
    }
}
