<?php

namespace App\Livewire\SchoolClass;

use App\Models\SchoolClass;
use App\Services\SchoolClassService;
use App\Traits\HasNotifications;
use Livewire\Component;

class SchoolClassForm extends Component
{
    use HasNotifications;

    public $schoolClass;
    public $name = '';
    public $alias = '';
    public $description = '';
    public $is_active = true;
    public $isEdit = false;

    public function mount($schoolClass = null)
    {
        if ($schoolClass) {
            $this->schoolClass = $schoolClass;
            $this->name = $schoolClass->name;
            $this->alias = $schoolClass->alias;
            $this->description = $schoolClass->description;
            $this->is_active = $schoolClass->is_active;
            $this->isEdit = true;
        }
    }

    protected function rules()
    {
        return [
            'name' => 'required|string|max:255|unique:school_classes,name' . ($this->isEdit ? ',' . $this->schoolClass->id : ''),
            'alias' => 'nullable|string|max:50',
            'description' => 'nullable|string|max:500',
            'is_active' => 'boolean'
        ];
    }

    public function save()
    {
        $this->validate();

        $data = [
            'name' => $this->name,
            'alias' => $this->alias,
            'description' => $this->description,
            'is_active' => $this->is_active
        ];

        $service = new SchoolClassService();

        if ($this->isEdit) {
            $service->update($this->schoolClass, $data);
            session()->flash('toast', ['type' => 'success', 'message' => 'Class updated successfully!']);
        } else {
            $service->create($data);
            session()->flash('toast', ['type' => 'success', 'message' => 'Class created successfully!']);
        }

        return redirect()->route('school-classes.index');
    }

    public function render()
    {
        return view('livewire.school-class.school-class-form');
    }
}
