<?php

namespace App\Components\Monitoring;

use App\Models\History;
use App\Models\User\User;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component {
    use WithPagination;

    public ?int $filterUserId = null;
    public string $filterDateFrom = '';
    public string $filterDateTo = '';
    public string $filterTimeFrom = '';
    public string $filterTimeTo = '';
    public string $search = '';

    public function mount() {
        $this->authorize('monitoring.view');
    }

    public function updatedFilterUserId() { $this->resetPage(); }
    public function updatedFilterDateFrom() { $this->resetPage(); }
    public function updatedFilterDateTo() { $this->resetPage(); }
    public function updatedFilterTimeFrom() { $this->resetPage(); }
    public function updatedFilterTimeTo() { $this->resetPage(); }
    public function updatedSearch() { $this->resetPage(); }

    public function clearFilters() {
        $this->reset(['filterUserId', 'filterDateFrom', 'filterDateTo', 'filterTimeFrom', 'filterTimeTo', 'search']);
        $this->resetPage();
    }

    public function render() {
        $query = History::with('user')
            ->latest();

        if ($this->filterUserId) {
            $query->where('user_id', $this->filterUserId);
        }

        if ($this->search) {
            $query->where('action', 'like', '%' . $this->search . '%');
        }

        if ($this->filterDateFrom) {
            $from = $this->filterTimeFrom
                ? $this->filterDateFrom . ' ' . $this->filterTimeFrom . ':00'
                : $this->filterDateFrom . ' 00:00:00';
            $query->where('created_at', '>=', $from);
        }

        if ($this->filterDateTo) {
            $to = $this->filterTimeTo
                ? $this->filterDateTo . ' ' . $this->filterTimeTo . ':59'
                : $this->filterDateTo . ' 23:59:59';
            $query->where('created_at', '<=', $to);
        }

        return view('components.monitoring.index', [
            'history' => $query->paginate(50),
            'users'   => User::orderBy('name_first')->orderBy('name_last')->get(),
        ]);
    }
}
