<?php

namespace App\Livewire\CashSessions;

use App\Domain\Financial\Models\CashSession;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Livewire\Concerns\AppliesRoleScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('الورديات النقدية')]
class CashSessionList extends Component
{
    use WithPagination, UsesBranchScope, AppliesRoleScope;

    protected string $scopePermission = 'cash_sessions.list';

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

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

    public function render()
    {
        $branchId = $this->getActiveBranchId();

        $query = CashSession::query()
            ->with(['user', 'branch'])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->orderByDesc('opened_at');

        $this->applyRoleScope($query);

        return view('livewire.cash-sessions.cash-session-list', [
            'sessions' => $query->paginate(20),
            'statusOptions' => [
                'open' => 'مفتوحة',
                'closed' => 'مغلقة',
                'suspended' => 'معلقة',
            ],
        ]);
    }
}
