<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Task;
use App\Models\Status;
use App\Models\Meeting;
use App\Models\Note;
use Illuminate\Support\Facades\Auth;

class EmployeeDashboard extends Controller
{
    public function index()
    {
        $employeeId = Auth::id();
        $sixMonthsAgo = \Carbon\Carbon::now()->subMonths(6);

        // Get all statuses
        $statuses = Status::all();

        // Get counts of tasks for each status where the current employee is assigned
        $statusCounts = Task::select('status_id', \DB::raw('count(*) as total'))
                            ->join('employee_task', 'tasks.id', '=', 'employee_task.task_id')
                            ->where('employee_task.employee_id', $employeeId)
                            ->groupBy('status_id')
                            ->get();

        // Initialize arrays to hold labels and data for each status
        $taskDataByStatus = [];
        $months = \DB::table('tasks')
            ->select(\DB::raw("DISTINCT(MONTHNAME(start_date)) as month"))
            ->where('start_date', '>=', $sixMonthsAgo)
            ->orderBy('start_date', 'ASC')
            ->pluck('month');

        foreach ($statuses as $status) {
            // Get task data for each status in the last 6 months
            $taskDataByStatus[$status->id] = Task::select(\DB::raw("COUNT(*) as count"), \DB::raw("MONTHNAME(start_date) as month"))
                ->where('start_date', '>=', $sixMonthsAgo)
                ->where('status_id', $status->id)
                ->whereHas('employees', function ($query) use ($employeeId) {
                    $query->where('employee_id', $employeeId);
                })
                ->groupBy('month')
                ->orderBy('start_date', 'ASC')
                ->pluck('count', 'month')
                ->toArray();
        }

        // Fill missing months for each status with 0
        foreach ($taskDataByStatus as &$data) {
            foreach ($months as $month) {
                if (!isset($data[$month])) {
                    $data[$month] = 0;
                }
            }
            ksort($data); // Sort by month
        }

        // Get recent tasks for the table
        $tasks = Task::with('project', 'status')
            ->whereHas('employees', function ($query) use ($employeeId) {
                $query->where('employee_id', $employeeId);
            })
            ->orderBy('end_date', 'desc')
            ->take(5)
            ->get();

        // Get total count of meetings where the employee is involved
        $totalMeetings = Meeting::whereJsonContains('employee_ids', (string) $employeeId)->count();

        // Get total count of notes created by the authenticated user
        $totalNotes = Note::where('author_id', $employeeId)->count();

        // Statuses and colors (for recent tasks table)
        $statuses_color = Status::pluck('name', 'id');
        $statusColors = Status::pluck('color', 'id');

        return view('employee.dashboard.index', compact(
            'statusCounts', 'statuses', 'statusColors', 'totalMeetings', 'totalNotes', 
            'taskDataByStatus', 'months', 'tasks', 'statuses_color'
        ));
    }
}
