<?php

namespace App\Http\Controllers\user;

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

class DashboardController extends Controller
{
    private function checkUser()
    {
        if (!Auth::check() && !session('is_user_logged_in')) {
            return redirect('/login');
        }
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->role === 'Super Admin' || $user->role === 'Admin') {
                return redirect('/');
            }
        }
        return null;
    }

    public function index(Request $request)
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();
        $userId = $user->id;

        $allProjects = \App\Models\Project::all();
        $totalDomains = \App\Models\Domain::where('user_id', $userId)->count();

        $query = Task::where('user_id', $userId);
        if ($request->filled('project_id')) {
            $query->where('project_id', $request->project_id);
        }
        if ($request->filled('filter_date')) {
            $query->whereDate('created_at', $request->filter_date);
        }

        $totalTasks = Task::where('user_id', $userId)->count();
        $filteredTotalTasks = (clone $query)->count();
        // $completedTasks = (clone $query)->where('status', 'Completed')->count();
        $completedTasks = (clone $query)->where('status', 'Completed')->where(function($q) {
            $q->where('is_verified', 0)->orWhereNull('is_verified');
        })->count();
        $inProgressTasks = (clone $query)->where('status', 'In Progress')->count();
        $pendingTasks = (clone $query)->where('status', 'Pending')->count();
        $holdTasks = (clone $query)->where('status', 'Hold')->count();
        $cancelledTasks = (clone $query)->where('status', 'Cancelled')->count();
        $verifiedTasks = (clone $query)->where('is_verified', 1)->count();

        $completedPercentage = $filteredTotalTasks > 0 ? round(($completedTasks / $filteredTotalTasks) * 100, 2) : 0;
        $inProgressPercentage = $filteredTotalTasks > 0 ? round(($inProgressTasks / $filteredTotalTasks) * 100, 2) : 0;
        $pendingPercentage = $filteredTotalTasks > 0 ? round(($pendingTasks / $filteredTotalTasks) * 100, 2) : 0;
        $holdPercentage = $filteredTotalTasks > 0 ? round(($holdTasks / $filteredTotalTasks) * 100, 2) : 0;
        $cancelledPercentage = $filteredTotalTasks > 0 ? round(($cancelledTasks / $filteredTotalTasks) * 100, 2) : 0;
        $verifiedPercentage = $filteredTotalTasks > 0 ? round(($verifiedTasks / $filteredTotalTasks) * 100, 2) : 0;

        $recentTasks = Task::with('project')->where('user_id', $userId)->latest()->take(4)->get();

        $upcomingTasks = Task::with('project')
            ->where('user_id', $userId)
            ->where('status', '!=', 'Completed')
            ->latest()
            ->take(3)
            ->get();

        $filterDate = $request->filter_date ? $request->filter_date : today()->toDateString();
        $activeProjectUsers = Task::select('project_id', 'user_id')
            ->whereDate('created_at', $filterDate)
            ->where('user_id', $userId)
            ->groupBy('project_id', 'user_id')
            ->get();

        $dailyDashboard = [];
        foreach ($activeProjectUsers as $pu) {
            $userProjectTasks = Task::where('project_id', $pu->project_id)
                                    ->where('user_id', $pu->user_id)
                                    ->whereDate('created_at', $filterDate)
                                    ->get();

            $total = $userProjectTasks->count();
            $completed = $userProjectTasks->where('status', 'Completed')->count();
            
            $progress = $total > 0 ? round(($completed / $total) * 100) : 0;
            $pending = 100 - $progress;

            $statusClass = 'pending';
            if ($progress == 100) {
                $statusClass = 'completed';
            } elseif ($progress > 0 && $progress < 100) {
                $statusClass = 'progress';
            }

            $project = Project::find($pu->project_id);

            if ($project && $total > 0) {
                $dailyDashboard[] = (object) [
                    'project_name' => $project->name,
                    'developer_name' => $user->name,
                    'progress' => $progress,
                    'pending' => $pending,
                    'statusClass' => $statusClass
                ];
            }
        }

        return view('user.dashboard.dashboard', compact(
            'user', 'totalTasks', 'filteredTotalTasks', 'completedTasks', 'inProgressTasks', 'pendingTasks', 'holdTasks', 'cancelledTasks', 'verifiedTasks',
            'completedPercentage', 'inProgressPercentage', 'pendingPercentage', 'holdPercentage', 'cancelledPercentage', 'verifiedPercentage',
            'recentTasks', 'upcomingTasks', 'allProjects', 'dailyDashboard', 'totalDomains'
        ));
    }
}
