<?php

namespace Daylight\Core\Livewire\Store;

use Daylight\Core\Livewire\Tables\BaseTable;
use Daylight\Core\Livewire\Tables\Concerns\WithSearch;
use Daylight\Core\Models\Variant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\View\View;
use Livewire\Attributes\Url;

class VariantTable extends BaseTable
{
    use WithSearch;

    #[Url]
    public ?string $status = null;

    protected function getBaseQuery(): Builder
    {
        return Variant::query()
            ->with('basePrices', 'media', 'optionValues.option')
            ->latest()
            ->when($this->status, function ($query) {
                switch ($this->status) {
                    case 'purchasable':
                        return $query->wherePurchasable(1);
                    case 'unassigned':
                        return $query->wherePurchasable(1)->whereNull('product_id');
                    default:
                        return $query;
                }
            });
    }

    public function getFilters(): array
    {
        return [
            [
                'name' => __('All'),
                'url' => route('daylight.store.variants.index'),
                'active' => is_null($this->status),
                'count' => Variant::count(),
            ],
            [
                'name' => __('Purchasable'),
                'url' => route('daylight.store.variants.index', ['status' => 'purchasable']),
                'active' => $this->status === 'purchasable',
                'count' => Variant::wherePurchasable(1)->count(),
            ],
            [
                'name' => __('Unassigned'),
                'url' => route('daylight.store.variants.index', ['status' => 'unassigned']),
                'active' => $this->status === 'unassigned',
                'count' => Variant::wherePurchasable(1)->whereNull('product_id')->count(),
            ],
        ];
    }

    protected function applySearch(Builder $query, ?string $searchQuery): Builder
    {
        return $query->when($searchQuery, function ($query, $searchQuery) {
            $query
                ->when($this->status, function ($query) {
                    switch ($this->status) {
                        case 'purchasable':
                            return $query->wherePurchasable(1);
                        case 'unassigned':
                            return $query->wherePurchasable(1)->whereNull('product_id');
                        default:
                            return $query;
                    }
                })
                ->where(function ($query) use ($searchQuery) {
                    $query->where('sku', 'like', "%{$searchQuery}%")
                        ->orWhere('title', 'like', "%{$searchQuery}%");
                });
        });
    }

    public function render(): View
    {
        return view('daylight::livewire.store.variant-table');
    }
}
