<?php

namespace App\Livewire\Admin\Produk;

use App\Models\Category;
use App\Models\Partner;
use App\Models\Product;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.admin')]
#[Title('Produk')]
class Index extends Component
{
    use WithPagination;

    public string $search         = '';
    public string $filterKategori = '';
    public string $filterMitra    = '';
    public string $filterStatus   = '';

    public function updatingSearch(): void         { $this->resetPage(); }
    public function updatingFilterKategori(): void { $this->resetPage(); }
    public function updatingFilterMitra(): void    { $this->resetPage(); }
    public function updatingFilterStatus(): void   { $this->resetPage(); }

    public function toggleActive(int $id): void
    {
        $product = Product::findOrFail($id);
        $product->update(['is_active' => ! $product->is_active]);
        $this->dispatch('notify', type: 'success',
            message: 'Status produk berhasil diubah.');
    }

    public function toggleFeatured(int $id): void
    {
        $product = Product::findOrFail($id);
        $product->update(['is_featured' => ! $product->is_featured]);
        $this->dispatch('notify', type: 'success',
            message: 'Produk unggulan berhasil diubah.');
    }

    public function confirmDelete(int $id): void
    {
        $this->dispatch('confirm-delete', id: $id);
    }

    public function delete(int $id): void
    {
        $product = Product::findOrFail($id);
        if ($product->image) {
            \Illuminate\Support\Facades\Storage::disk('public')->delete($product->image);
        }
        $product->delete();
        $this->dispatch('notify', type: 'success', message: 'Produk berhasil dihapus.');
    }

    public function render()
    {
        $products = Product::with(['category', 'partner'])
            ->when($this->search, fn ($q) =>
                $q->where('name', 'like', "%{$this->search}%"))
            ->when($this->filterKategori, fn ($q) =>
                $q->where('category_id', $this->filterKategori))
            ->when($this->filterMitra, fn ($q) =>
                $q->where('partner_id', $this->filterMitra))
            ->when($this->filterStatus !== '', fn ($q) =>
                $q->where('is_active', (bool) $this->filterStatus))
            ->orderByRaw('CASE WHEN sort_order = 0 THEN 1 ELSE 0 END')
            ->orderBy('sort_order')
            ->orderByDesc('created_at')
            ->paginate(20);

        $categories = Category::where('is_active', true)->orderBy('name')->get();
        $partners   = Partner::where('is_active', true)->orderBy('name')->get();

        return view('livewire.admin.produk.index',
            compact('products', 'categories', 'partners'));
    }
}
