<?php

namespace App\Components;

use App\Interface\NoteOwner;
use App\Models\Note;
use App\Services\NoteService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\WithPagination;

class NoteManager extends Component {
    use AuthorizesRequests, WithPagination;

    public NoteOwner $owner;
    public bool $show = false;
    public string $note = '';
    public $perPage = 10;
    public bool $primary = false;

    protected $paginationTheme = 'bootstrap';

    public function mount(NoteOwner $owner) {
        $this->owner = $owner;
        $this->show = false;
    }

    public function showAddNote() {
        $this->show = true;
    }

    public function addNote(NoteService $noteService) {
        $this->authorize('notes.create');
        $data = $this->validate([
            'note' => 'required|string|min:1'
        ]);

        $noteService->addNote($this->owner, $data['note'], $this->primary);

        $this->resetPage();
        $this->hideAddNote();
    }

    public function hideAddNote() {
        $this->show = false;
        $this->reset('note');
    }

    public function deleteNote(NoteService $noteService, int $id) {
        $this->authorize('notes.delete');
        $note = Note::findOrFail($id);

        $noteService->deleteNote($note);

        $this->resetPage();
    }

    public function render() {
        $builder = $this->primary ? $this->owner->keyInfo() : $this->owner->notes()->where('is_primary', false);
        return view('components.note-manager', [
            'notes' => $builder
                ->paginate($this->perPage),
        ]);
    }
}
