<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Audit;
use App\Models\Tema;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $userId = $user->id;

        // Ambil bulan dari request atau default ke bulan ini
        $bulanAudit = request()->bulan_audit ?? Carbon::now()->format('Y-m');

        try {
            $startAudit = Carbon::createFromFormat('Y-m', $bulanAudit)->startOfMonth();
        } catch (\Exception $e) {
            $startAudit = Carbon::now()->startOfMonth();
        }

        // Statistik Audit
        $totalAudit = Audit::where('user_id', $userId)->count();

        $totalSelesai = Audit::where('user_id', $userId)
            ->where('status', 'Close')
            ->count();

        $totalBelum = Audit::where('user_id', $userId)
            ->where(function ($query) {
                $query->where('status', '!=', 'Close')
                      ->orWhereNull('status');
            })
            ->count();

        // Ambil distinct tema_id yang dipakai user ini
        $temaIds = Audit::where('user_id', $userId)
            ->distinct()
            ->pluck('tema_id')
            ->filter();

        // Ambil nama tema berdasarkan tema_id
        $labelsTema = Tema::whereIn('id', $temaIds)
            ->pluck('nama')
            ->toArray();

        $jumlahOpen = [];
        $jumlahClose = [];

        foreach ($temaIds as $temaId) {
            $jumlahOpen[] = Audit::where('user_id', $userId)
                ->where('tema_id', $temaId)
                ->where(function ($q) {
                    $q->whereNull('status')->orWhere('status', 'Open');
                })->count();

            $jumlahClose[] = Audit::where('user_id', $userId)
                ->where('tema_id', $temaId)
                ->where('status', 'Close')
                ->count();
        }

        // Notifikasi
        $notifications = $user->notifications()->latest()->take(5)->get();
        $unreadCount = $user->unreadNotifications()->count();

        return view('web_user.dashboard', compact(
            'totalAudit',
            'totalSelesai',
            'totalBelum',
            'labelsTema',
            'jumlahOpen',
            'jumlahClose',
            'bulanAudit',
            'startAudit',
            'notifications',
            'unreadCount'
        ));
    }
}
