<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Project;
use App\Models\User;

class ProgressController extends Controller
{
    public function index(Request $request)
    {
        if (!Auth::check() && !session('is_admin_logged_in')) {
            return redirect('/login');
        }
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->role !== 'Super Admin' && $user->role !== 'Admin') {
                return redirect('/');
            }
        }

        $allUsers = User::whereNotIn('role', ['Super Admin', 'Admin'])->get();
        $allProjects = Project::orderBy('name', 'asc')->get();

        $weekFilter = $request->query('week', 'current');
        
        if ($weekFilter === 'last') {
            $startOfThisWeek = now()->subWeek()->startOfWeek(); 
            $endOfThisWeek = now()->subWeek()->endOfWeek();
            $startOfLastWeek = now()->subWeeks(2)->startOfWeek();
            $endOfLastWeek = now()->subWeeks(2)->endOfWeek();
        } else {
            $startOfThisWeek = now()->startOfWeek(); 
            $endOfThisWeek = now()->endOfWeek();
            $startOfLastWeek = now()->subWeek()->startOfWeek();
            $endOfLastWeek = now()->subWeek()->endOfWeek();
        }

        $completedThisWeek = \App\Models\Task::where('status', 'Completed')
            ->whereBetween('created_at', [$startOfThisWeek, $endOfThisWeek])
            ->count();

        $completedLastWeek = \App\Models\Task::where('status', 'Completed')
            ->whereBetween('created_at', [$startOfLastWeek, $endOfLastWeek])
            ->count();

        $growthAbsolute = $completedThisWeek - $completedLastWeek;
        $growthPercentage = $completedLastWeek > 0 
            ? round(($growthAbsolute / $completedLastWeek) * 100) 
            : ($completedThisWeek > 0 ? 100 : 0);

        $chartEndDate = $weekFilter === 'last' ? now()->subWeek()->endOfDay() : now()->endOfDay();
        $chartStartDate = $chartEndDate->copy()->subDays(6)->startOfDay();

        $addedTasksChart = \App\Models\Task::whereBetween('created_at', [$chartStartDate, $chartEndDate])->get();
        $completedTasksChart = \App\Models\Task::where('status', 'Completed')
            ->whereBetween('created_at', [$chartStartDate, $chartEndDate])->get();

        $dailyAddedData = [];
        $dailyData = [];
        $chartLabels = [];

        for ($i = 0; $i < 7; $i++) {
            $d = $chartStartDate->copy()->addDays($i);
            $key = $d->format('Y-m-d');
            $dailyAddedData[$key] = 0;
            $dailyData[$key] = 0;
            $chartLabels[$key] = [
                'dayName' => $d->format('D'),
                'dateLabel' => $d->format('d M')
            ];
        }

        foreach ($addedTasksChart as $task) {
            $key = $task->created_at->format('Y-m-d');
            if (isset($dailyAddedData[$key])) {
                $dailyAddedData[$key]++;
            }
        }

        foreach ($completedTasksChart as $task) {
            $key = $task->created_at->format('Y-m-d');
            if (isset($dailyData[$key])) {
                $dailyData[$key]++;
            }
        }

        $todayDayKey = now()->format('Y-m-d');
        $todayCompletedTasks = $dailyData[$todayDayKey] ?? 0;

        $bestDayCount = empty($dailyData) ? 0 : max($dailyData);
        $bestDay = empty($dailyData) ? null : array_search($bestDayCount, $dailyData);
        $bestDayFull = $bestDay ? \Carbon\Carbon::parse($bestDay)->format('l') : 'None';

        $totalWeekly = array_sum($dailyData);
        $avgPerDay = round($totalWeekly / 7, 1);
        $highest = $bestDayCount;
        $lowest = empty($dailyData) ? 0 : min($dailyData);

        $highestDaysKeys = array_keys(array_filter($dailyData, fn($v) => $v == $highest));
        $lowestDaysKeys = array_keys(array_filter($dailyData, fn($v) => $v == $lowest));

        $highestDays = array_map(fn($k) => \Carbon\Carbon::parse($k)->format('D'), $highestDaysKeys);
        $lowestDays = array_map(fn($k) => \Carbon\Carbon::parse($k)->format('D'), $lowestDaysKeys);

        $highestStr = implode(', ', $highestDays);
        $lowestStr = implode(', ', $lowestDays);

        $summary = [
            'total_this_week' => $totalWeekly,
            'avg_per_day' => $avgPerDay,
            'highest' => $highest,
            'highest_days' => $highestStr,
            'lowest' => $lowest,
            'lowest_days' => $lowestStr,
        ];

        $progressTrackerProjects = Project::with(['tasks.user'])
        ->withCount([
            'tasks as total_tasks',
            'tasks as achieved_tasks' => function ($q) {
                $q->where('status', 'Completed');
            },
            'tasks as pending_tasks' => function ($q) {
                $q->where('status', 'Pending');
            },
            'tasks as this_week_completed' => function ($q) use ($startOfThisWeek, $endOfThisWeek) {
                $q->whereBetween('created_at', [$startOfThisWeek, $endOfThisWeek]);
            },
            'tasks as last_week_completed' => function ($q) use ($startOfLastWeek, $endOfLastWeek) {
                $q->whereBetween('created_at', [$startOfLastWeek, $endOfLastWeek]);
            },
        ])->orderBy('name', 'asc')->get();

        return view('admin.progress.progress', compact(
            'progressTrackerProjects', 'allUsers', 'allProjects',
            'startOfThisWeek', 'endOfThisWeek', 'startOfLastWeek', 'endOfLastWeek',
            'completedThisWeek', 'completedLastWeek', 'growthAbsolute', 'growthPercentage',
            'dailyData', 'dailyAddedData', 'chartLabels', 'bestDayFull', 'bestDayCount', 'summary', 'weekFilter', 'todayCompletedTasks'
        ));
    }
}
