<?php

namespace App\Livewire\Suppliers;

use App\Models\Province;
use App\Models\Supplier;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

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

    protected string $paginationTheme = 'tailwind';

    public function render(): \Illuminate\Contracts\View\View
    {
        // Get filter values from request
        $search = request('search');
        $provinceId = request('province');
        $status = request('status');

        $suppliers = Supplier::query()
            ->when($search, function ($query) use ($search) {
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', '%'.$search.'%')
                        ->orWhere('email', 'like', '%'.$search.'%')
                        ->orWhere('phone', 'like', '%'.$search.'%');
                });
            })
            ->when($provinceId, function ($query) use ($provinceId) {
                $query->whereHas('address', function ($q) use ($provinceId) {
                    $q->where('province_id', $provinceId);
                });
            })
            ->when($status !== null && $status !== '', function ($query) use ($status) {
                $query->where('is_active', (bool) $status);
            })
            ->orderByDesc('created_at')
            ->paginate(25)
            ->withQueryString();

        $provinces = Province::orderBy('name')
            ->get(['id', 'name'])
            ->map(fn ($p) => (object) ['id' => $p->id, 'name' => $p->name]);

        return view('livewire.suppliers.index', compact('suppliers', 'provinces'));
    }
}
