<?php

namespace App\Http\Controllers;

use App\Models\Task;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class TaskDashboardController extends Controller
{
    public function index()
    {
        $statusCounts = Task::select('status', DB::raw('COUNT(*) as total'))
            ->groupBy('status')
            ->pluck('total', 'status')
            ->toArray();

        $types = ['SA', 'DB', 'FE', 'BE', 'SI', 'AS'];
        $typeCounts = array_fill_keys($types, 0);
        Task::select('types')->get()->each(function ($t) use (&$typeCounts) {
            $arr = $t->types ?? [];
            foreach ($arr as $type) {
                if (isset($typeCounts[$type])) {
                    $typeCounts[$type]++;
                }
            }
        });

        $months = [];
        $monthCounts = [];
        $tasksByMonth = Task::select(DB::raw("DATE_FORMAT(COALESCE(recorded_at, created_at), '%Y-%m') as ym"), DB::raw('COUNT(*) as total'))
            ->groupBy('ym')
            ->orderBy('ym')
            ->get();
        foreach ($tasksByMonth as $row) {
            $months[] = Carbon::createFromFormat('Y-m', $row->ym)->translatedFormat('M Y');
            $monthCounts[] = (int) $row->total;
        }

        $overdueTasks = Task::where('status', '!=', 'Selesai')
            ->whereDate('target_date', '<', Carbon::today())
            ->orderBy('target_date')
            ->limit(10)
            ->get();

        $nearDueTasks = Task::where('status', '!=', 'Selesai')
            ->whereDate('target_date', '>=', Carbon::today())
            ->orderBy('target_date')
            ->limit(10)
            ->get();

        return view('tasks.dashboard', [
            'statusCounts' => [
                'Tersampaikan' => $statusCounts['Tersampaikan'] ?? 0,
                'Sedang Dikerjakan' => $statusCounts['Sedang Dikerjakan'] ?? 0,
                'Selesai' => $statusCounts['Selesai'] ?? 0,
            ],
            'typeCounts' => $typeCounts,
            'months' => $months,
            'monthCounts' => $monthCounts,
            'nearDueTasks' => $nearDueTasks,
            'overdueTasks' => $overdueTasks,
        ]);
    }
}
