<?php

namespace App\Livewire\Admin\Products;

use Livewire\Component;
use Livewire\Attributes\On;
use Livewire\Attributes\Url;
use Livewire\WithPagination;
use App\Models\Admin\Product;
use Livewire\Attributes\Computed;
use App\Enums\ProductCategories;

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();
    }

    #[Computed()]
    public function products()
    {
        return Product::with(['taxonomies.parent', 'taxonomies' => function ($query) {
            $query->whereIn('parent_id', [
                ProductCategories::MATERIAL->value,
                ProductCategories::END->value,
                ProductCategories::MARINE->value,
                ProductCategories::WATERWORKS->value,
                ProductCategories::MARITIME->value,
                ProductCategories::REMOTE->value,
            ]);
        }])
        ->orderBy('id')
        ->search($this->search)
        ->paginate($this->paginate);
    }

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

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

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

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

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

        activity()->performedOn($product)->causedBy(auth()->id())->log('Ürün silindi');

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

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