<?php

namespace App\Livewire\Admin\Popup;

use Livewire\Component;
use App\Models\Admin\Popup;
use Livewire\Attributes\On;
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 updateOrder($list)
    {
        foreach ($list as $item) {
            Popup::find($item['value'])->update(['ordernum' => $item['order']]);
        }

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

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

    #[Computed()]
    public function popups()
    {
        return Popup::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)
    {
        $popup = Popup::find($id);
        $popup->delete();

        activity()->performedOn($popup)->causedBy(auth()->id())->log('Popup silindi');

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

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