<?php

namespace App\Http\Controllers;

use App\Enums\CampaignStatus;
use App\Models\Ad;
use App\Models\Billing;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class DashboardController extends Controller
{
    /**
     * Dashboard ringkasan (FR-DASH-01 .. FR-DASH-03).
     * Member hanya melihat datanya sendiri; admin melihat seluruh data.
     */
    public function __invoke(Request $request): Response
    {
        $user = $request->user();
        $isAdmin = $user->isAdmin();

        $campaignScope = fn ($q) => $isAdmin ? $q : $q->where('user_id', $user->id);

        $stats = [
            'total_campaigns' => Ad::when(! $isAdmin, fn ($q) => $q->where('user_id', $user->id))->count(),
            'active_campaigns' => Ad::when(! $isAdmin, fn ($q) => $q->where('user_id', $user->id))
                ->where('status', CampaignStatus::Aktif)->count(),
            'total_klik' => Ad::when(! $isAdmin, fn ($q) => $q->where('user_id', $user->id))->sum('klik'),
            'credit_balance' => $user->credit,
        ];

        // Campaign terbaru (FR-DASH-01).
        $recentCampaigns = Ad::with('kategoris')
            ->when(! $isAdmin, fn ($q) => $q->where('user_id', $user->id))
            ->latest()
            ->limit(5)
            ->get();

        // Billing/credit terbaru (FR-DASH-01).
        $recentBillings = Billing::with('user')
            ->when(! $isAdmin, fn ($q) => $q->where('user_id', $user->id))
            ->latest()
            ->limit(5)
            ->get();

        // Grafik performa campaign: judul vs klik (FR-DASH-02), iklan aktif/selesai.
        $performance = Ad::select('judul', 'klik')
            ->when(! $isAdmin, fn ($q) => $q->where('user_id', $user->id))
            ->whereIn('status', [CampaignStatus::Aktif, CampaignStatus::Selesai])
            ->orderByDesc('klik')
            ->limit(10)
            ->get();

        return Inertia::render('Dashboard', [
            'stats' => $stats,
            'recentCampaigns' => $recentCampaigns,
            'recentBillings' => $recentBillings,
            'performance' => $performance,
            'isAdmin' => $isAdmin,
        ]);
    }
}
