<?php

namespace App\Livewire;

use App\Models\Subject;
use App\Services\SubjectService;
use App\Traits\HasNotifications;
use Livewire\Component;

class DeletedSubjectsList extends Component
{
    use HasNotifications;

    protected $subjectService;
    protected $listeners = ['action-confirmed' => 'handleConfirmedAction', 'subjectDeleted' => '$refresh'];
    public $pendingAction = null;
    public $pendingSubjectId = null;

    public function boot(SubjectService $subjectService)
    {
        $this->subjectService = $subjectService;
    }

    public function confirmRestore($subjectId)
    {
        $this->pendingAction = 'restore';
        $this->pendingSubjectId = $subjectId;
        $this->confirmAction('Restore Subject?', 'This will restore the subject and make it available again.');
    }

    public function handleConfirmedAction()
    {
        if ($this->pendingAction === 'restore') {
            $this->restoreSubject($this->pendingSubjectId);
        }
        
        $this->pendingAction = null;
        $this->pendingSubjectId = null;
    }

    public function restoreSubject($subjectId)
    {
        $subject = Subject::withTrashed()->find($subjectId);
        $subject->restore();
        
        $this->showToast('success', 'Subject restored successfully!');
        $this->dispatch('subjectRestored');
    }

    public function render()
    {
        $deletedSubjects = Subject::onlyTrashed()->orderBy('deleted_at', 'desc')->get();
        
        return view('livewire.deleted-subjects-list', compact('deletedSubjects'));
    }
}
