<?php

namespace App\Livewire\SchoolClass;

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

class SchoolClassTable extends Component
{
    use WithPagination, HasNotifications;

    protected $paginationTheme = 'bootstrap';
    public $search = '';

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function deleteClass($id)
    {
        $schoolClass = SchoolClass::findOrFail($id);
        $schoolClass->delete();

        session()->flash('toast', ['type' => 'success', 'message' => 'Class deleted successfully!']);
        return redirect()->route('school-classes.index');
    }

    public function toggleStatus($id)
    {
        $schoolClass = SchoolClass::findOrFail($id);
        $schoolClass->update(['is_active' => !$schoolClass->is_active]);

        session()->flash('toast', ['type' => 'success', 'message' => 'Class status updated successfully!']);
        return redirect()->route('school-classes.index');
    }

    public function render()
    {
        $classes = SchoolClass::when($this->search, function ($query) {
            $query->where('name', 'like', '%' . $this->search . '%')
                ->orWhere('description', 'like', '%' . $this->search . '%');
        })->orderBy('order')->paginate(10);

        return view('livewire.school-class.school-class-table', compact('classes'));
    }
}
