<?php

namespace App\Filament\Pages;

use App\Models\Clasa;
use App\Models\Materie;
use App\Models\OrarSlot;
use Filament\Pages\Page;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

class GeneratorOrar extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-calendar-days';
    protected static ?string $navigationLabel = 'Generator Orar';
    protected static ?string $title = 'Generator Orar';
    protected static ?string $navigationGroup = 'Administrare';
    protected static ?int $navigationSort = 10;

    protected static string $view = 'filament.pages.generator-orar';

    public static function canAccess(): bool
    {
        return Auth::user()?->hasAnyRole(['admin', 'director', 'secretariat']) ?? false;
    }

    public function getClaseData(): array
    {
        return Clasa::with(['materii.user', 'elevi'])->get()->map(fn($c) => [
            'id' => $c->id,
            'name' => $c->nume,
            'elevi' => $c->elevi->count(),
            'materii' => $c->materii->map(fn($m) => [
                'id' => $m->id,
                'materie' => $m->nume,
                'prof' => $m->user?->name ?? $m->profesor,
                'ore' => $m->ore_pe_saptamana ?? 2,
            ])->values()->toArray(),
        ])->values()->toArray();
    }

    public function getProfesoriData(): array
    {
        $materii = Materie::with('user')->get();
        $profesori = [];

        foreach ($materii as $m) {
            $name = $m->user?->name ?? $m->profesor;
            if (!$name || isset($profesori[$name])) continue;
            $profesori[$name] = [
                'name' => $name,
                'materie' => $m->nume,
            ];
        }

        return array_values($profesori);
    }

    public function salveazaOrar(array $slots): void
    {
        $clasaMap = Clasa::pluck('id', 'nume')->toArray();
        $materieMap = [];
        foreach (Materie::all() as $m) {
            $materieMap[$m->clasa_id . '|' . $m->nume] = $m->id;
        }

        $finalizate = Clasa::where('orar_finalizat', true)->pluck('nume', 'id')->toArray();
        $toInsert = [];
        $clasaIds = [];
        $skippedClase = [];

        foreach ($slots as $slot) {
            $clasaId = $clasaMap[$slot['clasa']] ?? null;
            if (!$clasaId) continue;

            if (isset($finalizate[$clasaId])) {
                $skippedClase[$clasaId] = $finalizate[$clasaId];
                continue;
            }

            $materieId = $materieMap[$clasaId . '|' . $slot['materie']] ?? null;
            if (!$materieId) continue;

            $clasaIds[$clasaId] = true;
            $toInsert[] = [
                'clasa_id' => $clasaId,
                'materie_id' => $materieId,
                'zi' => $slot['zi'],
                'ora_index' => $slot['ora_index'],
                'ora_inceput' => $slot['ora_inceput'],
                'ora_sfarsit' => $slot['ora_sfarsit'],
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        OrarSlot::withoutGlobalScopes()->whereIn('clasa_id', array_keys($clasaIds))->delete();
        OrarSlot::insert($toInsert);

        $notification = Notification::make()
            ->title('Orarul a fost salvat')
            ->body(count($toInsert) . ' sloturi salvate pentru ' . count($clasaIds) . ' clase.'
                . (count($skippedClase) ? ' Clase omise (finalizate): ' . implode(', ', $skippedClase) . '.' : ''))
            ->success();

        if (count($skippedClase)) {
            $notification->color('warning');
        }

        $notification->send();
    }
}
