<?php

namespace App\Livewire\Admin\Banner;

use Livewire\Component;
use Livewire\Attributes\On;
use App\Models\Admin\Banner;
use Livewire\Attributes\Url;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;

class Index extends Component
{
    use WithPagination;

    #[Url(as: 'q')]
    public $search = '';

    public $paginate = 25;

    public function mount()
    {
        $storedPaginate = session('paginate', $this->paginate);
        $this->paginate = $storedPaginate;
    }

    public function updatedPaginate($value)
    {
        session(['paginate' => $value]);
    }

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

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

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

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

    #[Computed()]
    public function banners()
    {
        return Banner::orderByRaw('CASE WHEN ordernum = 0 THEN 99999 ELSE ordernum END')
        ->orderBy('title')
        ->paginate($this->paginate);
    }

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

    #[On('delete')]
    public function delete($id)
    {
        $banner = Banner::find($id);
        $banner->delete();

        activity()->performedOn($banner)->causedBy(auth()->id())->log('Banner silindi');

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

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