<?php

namespace App\Livewire\Admin\Navigation\Link;

use Livewire\Component;
use Livewire\Attributes\On;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;
use App\Models\Admin\NavigationLink;
use App\Models\Admin\NavigationMenu;

class Index extends Component
{
    use WithPagination;

    public NavigationMenu $navigationMenu;

    #[Computed()]
    public function links()
    {
        return $this->navigationMenu->links()->orderBy('ordernum')->paginate(25);
    }

    public function updateOrder($list)
    {
        foreach ($list as $item) {
            NavigationLink::find($item['value'])->update(['ordernum' => $item['order']]);
        }

        activity()->causedBy(auth()->id())->log('Navigasyon link sıralaması güncellendi');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Navigasyon link sıralaması başarıyla güncellendi.', 'icon' => 'success'
        ]);
    }

    public function deleteConfirm($id)
    {
        $this->dispatch('deleteTriggered', id: $id);
    }

    #[On('delete')]
    public function delete($id)
    {
        $navigationLink = NavigationLink::find($id);
        $navigationLink->children()->delete();
        $navigationLink->delete();

        activity()->performedOn($navigationLink)->causedBy(auth()->id())->log('Link silindi');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Link başarıyla silindi.', 'icon' => 'success'
        ]);
    }

    public function render()
    {
        return view('livewire.admin.navigation.link.index');
    }
}
