<?php

namespace App\Livewire\Pricing;

use App\Domain\Pricing\Models\BasePrice;
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 BasePriceList extends Component
{
    use WithPagination, WithSorting, UsesBranchScope;

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

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

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

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

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

    public function toggleActive(string $uuid): void
    {
        $this->authorize('pricing.update');
        // The uuid comes from the browser; BranchScope is what keeps it inside
        // this branch (or on an academy-wide row), so the lookup needs nothing
        // added to it.
        $price = BasePrice::where('uuid', $uuid)->firstOrFail();
        $price->update(['is_active' => !$price->is_active]);
    }

    public function render()
    {
        // No branch predicate here on purpose. BasePrice carries BelongsToBranch
        // in SHARED mode, so BranchScope already narrows this to
        // `branch_id = :active OR branch_id IS NULL` — the same predicate
        // BasePrice::scopeForBranch() spells out. Repeating it read as a filter
        // this screen owned, which is exactly the habit the global scope exists
        // to end.
        $query = BasePrice::query()
            ->with(['branch', 'priceable'])
            ->when($this->search, fn ($q) => $q->where('name_ar', 'ilike', "%{$this->search}%"))
            ->when($this->activeFilter !== '', fn ($q) => $q->where('is_active', $this->activeFilter === '1'))
            ->orderBy($this->sortBy, $this->sortDir);

        return view('livewire.pricing.base-price-list', [
            'prices' => $query->paginate(20),
        ]);
    }
}
