<?php

namespace App\Livewire\Dashboard;

use App\Models\Activity;
use App\Models\AgentLog;
use App\Models\Contact;
use App\Models\Event;
use App\Models\Note;
use App\Models\Task;
use Carbon\Carbon;
use Livewire\Component;

class Index extends Component
{
    public $birthdaysToday = [];
    public $birthdaysSoon  = [];
    public string $locale  = 'de';

    public function mount(): void
    {
        $this->locale = auth()->user()->locale ?? 'de';
        $tz    = auth()->user()->timezone;
        $today = now($tz)->format('m-d');

        $this->birthdaysToday = Contact::where('user_id', auth()->id())
            ->whereNotNull('birthday')
            ->get()
            ->filter(fn ($c) => Carbon::parse($c->birthday)->format('m-d') === $today)
            ->values();

        $this->birthdaysSoon = Contact::where('user_id', auth()->id())
            ->whereNotNull('birthday')
            ->get()
            ->filter(function ($c) use ($tz) {
                $days = now($tz)->diffInDays(
                    Carbon::parse($c->birthday)->setYear(now($tz)->year),
                    false
                );
                return $days > 0 && $days <= 7;
            })
            ->sortBy(fn ($c) => Carbon::parse($c->birthday)->format('m-d'))
            ->values();
    }

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

        $today     = now($tz)->toDateString();
        $todayDate = now($tz)->startOfDay()->utc();
        $todayEnd  = now($tz)->endOfDay()->utc();

        // ── Termine heute (inkl. mehrtägige und ganztägige Überschneidungen) ─
        $todayEvents = Event::where('user_id', $userId)
            ->where('starts_at', '<=', $todayEnd)   // startet vor/während heute
            ->where('ends_at',   '>=', $todayDate)  // endet nach/während heute
            ->orderByDesc('is_all_day')              // Ganztag-Termine zuerst
            ->orderBy('starts_at')
            ->limit(8)
            ->get();

        // ── Nächste Termine (ab jetzt) ────────────────────────────────────
        $upcomingEvents = Event::where('user_id', $userId)
            ->where('starts_at', '>', now()->utc())
            ->orderBy('starts_at')
            ->limit(3)
            ->get();

        // ── Offene Aufgaben (fällig heute oder überfällig + ohne Datum) ───
        $openTasks = Task::forUser($userId)
            ->where('status', '!=', Task::STATUS_DONE)
            ->orderByRaw("FIELD(priority, 'high', 'medium', 'low')")
            ->orderBy('due_at')
            ->limit(6)
            ->get();

        // ── Letzte Notizen ────────────────────────────────────────────────
        $recentNotes = Note::forUser($userId)
            ->orderByDesc('pinned')
            ->orderByDesc('created_at')
            ->limit(3)
            ->get();

        // ── Letzte Aktivitäten ────────────────────────────────────────────
        $recentActivities = Activity::forUser($userId)
            ->latest()
            ->limit(7)
            ->get();

        // ── Statistiken ───────────────────────────────────────────────────
        $stats = [
            'events_today'  => $todayEvents->count(),
            'open_tasks'    => Task::forUser($userId)->where('status', '!=', Task::STATUS_DONE)->count(),
            'notes_total'   => Note::forUser($userId)->count(),
            'credits_month' => AgentLog::where('user_id', $userId)
                ->where('created_at', '>=', now()->startOfMonth())
                ->sum('credits'),
            'overdue_tasks' => Task::forUser($userId)
                ->where('status', '!=', Task::STATUS_DONE)
                ->whereNotNull('due_at')
                ->whereDate('due_at', '<', $today)
                ->count(),
        ];

        // ── Plan & Credits ────────────────────────────────────────────────
        $subscription  = $user->subscription()->with('plan')->first()
            ?? $user->latestSubscription()->with('plan')->first();
        $plan          = $subscription?->plan;
        $creditLimit   = $user->effective_limit;
        $usagePercent  = $user->usage_percent;

        // ── Begrüßung ─────────────────────────────────────────────────────
        $hour   = now($tz)->hour;
        $greetingKey = match (true) {
            $hour >= 5 && $hour < 12  => 'dashboard.greeting_morning',
            $hour >= 12 && $hour < 18 => 'dashboard.greeting_afternoon',
            default                    => 'dashboard.greeting_evening',
        };
        $greeting = t($greetingKey, [], $this->locale);

        return view('livewire.dashboard.index', [
            'user'             => $user,
            'firstName'        => explode(' ', $user->name)[0],
            'greeting'         => $greeting,
            'tz'               => $tz,
            'todayEvents'      => $todayEvents,
            'upcomingEvents'   => $upcomingEvents,
            'openTasks'        => $openTasks,
            'recentNotes'      => $recentNotes,
            'recentActivities' => $recentActivities,
            'stats'            => $stats,
            'plan'             => $plan,
            'subscription'     => $subscription,
            'creditLimit'      => $creditLimit,
            'usagePercent'     => $usagePercent,
        ])->layout('layouts.app');
    }
}
