<?php

namespace App\Livewire\Activity;

use App\Models\Activity;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;
use Livewire\Component;

class ActivityLogTable extends Component
{
    public $activities = [];
    public $startDate;
    public $endDate;
    public $isLoading = false;

    public function render()
    {

        return view('livewire.activity.activity-log-table');
    }

    public function mount()
    {
        $this->activities = Activity::query()
            ->where('created_at', '>=', now()->subWeeks(3))
            ->latest()
            ->get();

        if ($this->activities->isEmpty()) {

            $this->activities = DB::table('Luv2_activity_log')
                ->where('created_at', '>=', now()->subWeeks(3))
                ->latest()
                ->get();
        }
        $this->dispatch('refreshjs');

    }

    public function toFilterActivities()
    {
        $this->isLoading = true;
        $this->dispatch('filterActivities');
    }

    #[On('filterActivities')]
    public function filterActivities()
    {
        $query = Activity::query();

        if ($this->startDate && $this->endDate) {
            $query->whereBetween('created_at', [$this->startDate, $this->endDate]);
        }

        $this->activities = $query->latest()->get();

        if ($this->activities->isEmpty()) {
            $query = DB::table('Luv2_activity_log');

            if ($this->startDate && $this->endDate) {
                $query->whereBetween('created_at', [$this->startDate, $this->endDate]);
            }
            $this->activities = $query->latest()->get();
        }

        $this->dispatch('refreshjs');
        $this->dispatch('NotLoading');
    }

    #[On('NotLoading')]
    public function notLoading()
    {
        $this->isLoading = false;
        $this->dispatch('refreshjs');

    }
}
