<?php

namespace App\Livewire\POS;

use App\Domain\POS\Models\POSTransaction;
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 POSHistory extends Component
{
    use WithPagination, WithSorting, UsesBranchScope;

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

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

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

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

    public function mount(): void
    {
        $this->authorize('pos.list');
        $this->dateFrom = now()->subDays(7)->format('Y-m-d');
        $this->dateTo = now()->format('Y-m-d');
        if (!request()->has('sortBy')) {
            $this->sortBy = 'processed_at';
        }
    }

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

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

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

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

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

        $query = POSTransaction::query()
            ->with(['participant.person', 'processedBy'])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->search, fn ($q) => $q->where(function ($sq) {
                $sq->where('receipt_number', 'ilike', "%{$this->search}%")
                   ->orWhereHas('participant.person', fn ($pq) => $pq->where('name_ar', 'ilike', "%{$this->search}%"));
            }))
            ->when($this->dateFrom, fn ($q) => $q->whereDate('processed_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn ($q) => $q->whereDate('processed_at', '<=', $this->dateTo))
            ->when($this->paymentMethodFilter, fn ($q) => $q->where('payment_method', $this->paymentMethodFilter))
            ->orderBy($this->sortBy, $this->sortDir);

        return view('livewire.pos.pos-history', [
            'transactions' => $query->paginate(20),
        ]);
    }
}
