<?php

namespace App\Livewire\CashSessions;

use App\Domain\Financial\Models\CashSession;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Livewire\Concerns\AppliesRoleScope;
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 CashSessionList extends Component
{
    use WithPagination, WithSorting, UsesBranchScope, AppliesRoleScope;

    protected string $scopePermission = 'cash_sessions.list';

    public function mount(): void
    {
        if (! request()->has('sortBy')) {
            $this->sortBy = 'opened_at';
        }
    }

    #[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))
            ->orderBy($this->sortBy, $this->sortDir);

        $this->applyRoleScope($query);

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