<?php

namespace App\Livewire\Pages\Dashboard;

use App\Domains\Analytics\Models\Click;
use App\Domains\Link\Models\Link;
use Illuminate\View\View;
use Livewire\Component;

class Overview extends Component
{
    public int $workspaceId = 0;

    public string $workspaceUlid = '';

    public function mount(): void
    {
        $workspace = require_workspace();
        $this->workspaceId = $workspace->id;
        $this->workspaceUlid = $workspace->ulid;
    }

    public function render(): View
    {
        $wsId = $this->workspaceId;

        // Hero metrics
        $today = Click::where('workspace_id', $wsId)
            ->whereDate('clicked_at', today())
            ->count();

        $last7 = Click::where('workspace_id', $wsId)
            ->where('clicked_at', '>=', now()->subDays(7))
            ->count();

        $last30 = Click::where('workspace_id', $wsId)
            ->where('clicked_at', '>=', now()->subDays(30))
            ->count();

        $totalLinks = Link::where('workspace_id', $wsId)->count();

        // Chart data: daily clicks for last 30 days
        $chartData = Click::where('workspace_id', $wsId)
            ->where('clicked_at', '>=', now()->subDays(29)->startOfDay())
            ->selectRaw('DATE(clicked_at) as date, COUNT(*) as total')
            ->groupBy('date')
            ->orderBy('date')
            ->pluck('total', 'date');

        $labels = [];
        $data = [];
        for ($i = 29; $i >= 0; $i--) {
            $date = now()->subDays($i)->toDateString();
            $labels[] = now()->subDays($i)->format('d.m');
            $data[] = $chartData[$date] ?? 0;
        }

        // Top links by clicks
        $topLinks = Link::where('workspace_id', $wsId)
            ->withCount(['clicks as total_clicks'])
            ->orderByDesc('total_clicks')
            ->limit(5)
            ->get();

        return view('livewire.pages.dashboard.overview', compact(
            'today', 'last7', 'last30', 'totalLinks', 'labels', 'data', 'topLinks'
        ))->layout('layouts.nimuli-app', ['title' => 'Dashboard']);
    }
}
