<?php

namespace App\Livewire\Activities;

use App\Models\Activity;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public string $search     = '';
    public string $filterType = '';   // '' | event | reminder | automation | contact | integration | system

    // Bei Filteränderung zurück auf Seite 1
    public function updatedSearch(): void    { $this->resetPage(); }
    public function updatedFilterType(): void { $this->resetPage(); }

    // ── Löschen ───────────────────────────────────────────────────────────

    public function delete(string $id): void
    {
        Activity::where('user_id', auth()->id())->where('id', $id)->delete();
    }

    public function clearAll(): void
    {
        Activity::where('user_id', auth()->id())->delete();
        $this->resetPage();
    }

    // ── Render ────────────────────────────────────────────────────────────

    public function render()
    {
        $userId = auth()->id();
        $tz     = auth()->user()->timezone ?? 'UTC';

        $query = Activity::forUser($userId)->latest();

        if ($this->search !== '') {
            $query->search($this->search);
        }

        if ($this->filterType !== '') {
            $query->ofType($this->filterType);
        }

        $activities = $query->paginate(20);

        // Datum-Gruppen für die Timeline (nach User-TZ)
        $grouped = $activities->getCollection()
            ->groupBy(fn($a) => $a->created_at->setTimezone($tz)->toDateString());

        // Statistiken (nur für ungefilterte Ansicht sinnvoll)
        $stats = Activity::forUser($userId)
            ->selectRaw("
                count(*) as total,
                sum(case when DATE(created_at) = CURRENT_DATE then 1 else 0 end) as today,
                sum(case when type like 'event%' then 1 else 0 end) as events,
                sum(case when type like 'automation%' then 1 else 0 end) as automations
            ")
            ->first();

        return view('livewire.activities.index', [
            'activities' => $activities,
            'grouped'    => $grouped,
            'stats'      => $stats,
            'tz'         => $tz,
        ])->layout('layouts.app');
    }
}
