<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Discipline;

class Disciplines extends Component
{
    use WithPagination;

    protected $paginationTheme = 'tailwind';

    public $search = '';
    public $showModal = false;
    public $editMode = false;

    public $disciplineId;
    public $name;
    public $description;
    public $is_active = true;

    protected function rules()
    {
        return [
            'name' => 'required|string|min:3',
            'description' => 'nullable|string',
        ];
    }

    public function render()
    {
        return view('livewire.admin.disciplines', [
            'disciplines' => Discipline::where('name', 'like', "%{$this->search}%")
                ->orderBy('name')
                ->paginate(10),
        ]);
    }

    public function create()
    {
        $this->resetFields();
        $this->editMode = false;
        $this->showModal = true;
    }

    public function edit(Discipline $discipline)
    {
        $this->disciplineId = $discipline->id;
        $this->name = $discipline->name;
        $this->description = $discipline->description;
        $this->is_active = $discipline->is_active;

        $this->editMode = true;
        $this->showModal = true;
    }

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

        if ($this->editMode) {
            Discipline::findOrFail($this->disciplineId)->update([
                'name' => $this->name,
                'description' => $this->description,
                'is_active' => $this->is_active,
            ]);
        } else {
            Discipline::create([
                'name' => $this->name,
                'description' => $this->description,
                'is_active' => true,
            ]);
        }

        $this->showModal = false;
        $this->resetFields();
    }

    public function toggleStatus(Discipline $discipline)
    {
        $discipline->update([
            'is_active' => ! $discipline->is_active
        ]);
    }

    private function resetFields()
    {
        $this->reset([
            'disciplineId',
            'name',
            'description',
            'is_active',
        ]);
    }
}
