<?php

namespace App\Observers;

use App\Models\Absenta;
use App\Notifications\AbsentaAdaugata;
use App\Notifications\AbsentaMotivata;

class AbsentaObserver
{
    public function created(Absenta $absenta): void
    {
        $this->notifyParinte($absenta, new AbsentaAdaugata($absenta));
    }

    public function updated(Absenta $absenta): void
    {
        if ($absenta->isDirty('motivata')) {
            $this->notifyParinte($absenta, new AbsentaMotivata($absenta));
        }
    }

    private function notifyParinte(Absenta $absenta, $notification): void
    {
        $absenta->loadMissing('elev.clasa.scoala', 'materie');

        $elev = $absenta->elev;
        if (!$elev) {
            return;
        }

        $parinte = $elev->parinte;
        if ($parinte) {
            $parinte->notify($notification);
        } elseif ($elev->email_parinte) {
            $elev->notify($notification);
        }
    }
}
