<?php

namespace App\Livewire\Pricing;

use App\Domain\Pricing\Enums\PromotionType;
use App\Domain\Pricing\Models\Promotion;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('العروض والكوبونات')]
class PromotionList extends Component
{
    use WithPagination, WithSorting, UsesBranchScope;

    #[Url]
    public string $search = '';

    #[Url]
    public string $type = '';

    #[Url]
    public string $activeFilter = '';

    public function mount(): void
    {
        $this->authorize('pricing.list');
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedType(): void
    {
        $this->resetPage();
    }

    public function updatedActiveFilter(): void
    {
        $this->resetPage();
    }

    public function toggleActive(string $uuid): void
    {
        $this->authorize('pricing.update');
        $promotion = Promotion::where('uuid', $uuid)->firstOrFail();
        $promotion->update(['is_active' => !$promotion->is_active]);
    }

    public function render()
    {
        $branchId = $this->getActiveBranchId();
        $query = Promotion::query()
            ->when($branchId, fn ($q) => $q->where(fn ($b) => $b->whereNull('branch_id')->orWhere('branch_id', $branchId)))
            ->with(['branch'])
            ->when($this->search, fn ($q) => $q->where(function ($q2) {
                $q2->where('name_ar', 'ilike', "%{$this->search}%")
                   ->orWhere('code', 'ilike', "%{$this->search}%");
            }))
            ->when($this->type, fn ($q) => $q->where('type', $this->type))
            ->when($this->activeFilter !== '', fn ($q) => $q->where('is_active', $this->activeFilter === '1'))
            ->orderBy($this->sortBy, $this->sortDir);

        return view('livewire.pricing.promotion-list', [
            'promotions' => $query->paginate(20),
            'promotionTypes' => collect(PromotionType::cases())->mapWithKeys(fn ($t) => [$t->value => $t->label()])->toArray(),
        ]);
    }
}
