<?php

namespace App\Livewire\Dashboard\Payment;

use App\Models\Client;
use App\Models\Payment;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public $id;
    public $search = '';
    public $client_id;
    public $is_super_admin;


    protected $queryString = ['search'];

    // Resetea la paginación al realizar una nueva búsqueda
    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function mount(?int $id = null)
    {
        $this->is_super_admin = in_array(auth()->user()->role, ['super_admin', 'admin']);

        if ($id != null) {
            $this->client_id = $id;
            $client = Client::findOrFail($id);

            // Solo verifica el company_id si el usuario no es super_admin
            if (Auth::user()->role !== 'super_admin' && Auth::user()->company_id !== $client->user->company_id) {
                session()->flash('error', 'No tienes acceso a esta página.');
                return redirect()->route('d-client-index');
            }
        }
    }

    public function render()
{
    $query = Payment::query()->orderBy('id', 'desc');

    // Filtra por client_id si está definido
    if ($this->client_id) {
        $query->where('client_id', $this->client_id);
    }

    // Si el usuario no es super_admin, aplica filtro por company_id a través de la relación con User
    if (Auth::user()->role !== 'super_admin') {
        $query->whereHas('client.user', function ($subQuery) {
            $subQuery->where('company_id', Auth::user()->company_id);
        });
    }

    // Aplica filtro de búsqueda si hay texto en $search
    if (!empty($this->search)) {
        $query->where(function ($subQuery) {
            $subQuery->where('payment_date', 'like', '%' . $this->search . '%')
                ->orWhere('amount', 'like', '%' . $this->search . '%')
                ->orWhereHas('client.user', function ($userQuery) {
                    $userQuery->where('name', 'like', '%' . $this->search . '%');
                });
        });
    }

    $payments = $query->paginate(10);

    return view('livewire.dashboard.payment.index', [
        'payments' => $payments,
    ])->layout('layouts.app');
}


    public function delete(Payment $payment): void
    {
        $payment->delete();
        $this->dispatch('deleted');
    }
}
