<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\Team;
use App\Models\User;
use App\Models\Activity;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $query = Project::where('company_id', $user->company_id)
            ->with(['owner', 'team', 'members'])
            ->withCount(['tasks', 'tasks as completed_tasks_count' => function ($q) {
                $q->where('status', 'completed');
            }]);

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('team_id')) {
            $query->where('team_id', $request->team_id);
        }
        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        $projects = $query->orderBy('updated_at', 'desc')->paginate(12);
        $teams = Team::where('company_id', $user->company_id)->get();

        return view('projects.index', compact('projects', 'teams'));
    }

    public function create()
    {
        $user = auth()->user();
        $teams = Team::where('company_id', $user->company_id)->get();
        $users = User::where('company_id', $user->company_id)->where('is_active', true)->get();
        return view('projects.create', compact('teams', 'users'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'team_id' => 'nullable|exists:teams,id',
            'status' => 'in:not_started,in_progress,on_hold,completed,cancelled',
            'priority' => 'in:low,medium,high,urgent',
            'color' => 'nullable|string|max:7',
            'start_date' => 'nullable|date',
            'due_date' => 'nullable|date|after_or_equal:start_date',
            'members' => 'nullable|array',
        ]);

        $validated['company_id'] = $request->user()->company_id;
        $validated['owner_id'] = $request->user()->id;

        $project = Project::create($validated);

        if ($request->has('members')) {
            $project->members()->attach($request->members);
        }

        Activity::log('created', $project, 'created project "' . $project->name . '"');

        return redirect()->route('projects.show', $project)
            ->with('success', 'Project created successfully.');
    }

    public function show(Request $request, Project $project)
    {
        $project->load(['owner', 'team', 'members']);

        $view = $request->get('view', 'board');

        $tasks = $project->tasks()
            ->with(['assignee', 'tags', 'subtasks', 'comments'])
            ->whereNull('parent_id')
            ->orderBy('position')
            ->get();

        $tasksByStatus = [
            'todo' => $tasks->where('status', 'todo'),
            'in_progress' => $tasks->where('status', 'in_progress'),
            'review' => $tasks->where('status', 'review'),
            'completed' => $tasks->where('status', 'completed'),
        ];

        $activityLimit = $view === 'activity' ? 50 : 20;

        $activities = Activity::where('subject_type', 'App\\Models\\Project')
            ->where('subject_id', $project->id)
            ->orWhere(function ($q) use ($project) {
                $q->where('subject_type', 'App\\Models\\Task')
                  ->whereIn('subject_id', $project->tasks()->pluck('id'));
            })
            ->with('causer')
            ->orderBy('created_at', 'desc')
            ->limit($activityLimit)
            ->get();

        $users = User::where('company_id', $request->user()->company_id)
            ->where('is_active', true)
            ->get();

        return view('projects.show', compact('project', 'tasks', 'tasksByStatus', 'view', 'activities', 'users'));
    }

    public function edit(Project $project)
    {
        $user = auth()->user();
        $teams = Team::where('company_id', $user->company_id)->get();
        $users = User::where('company_id', $user->company_id)->where('is_active', true)->get();
        return view('projects.edit', compact('project', 'teams', 'users'));
    }

    public function update(Request $request, Project $project)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'team_id' => 'nullable|exists:teams,id',
            'status' => 'in:not_started,in_progress,on_hold,completed,cancelled',
            'priority' => 'in:low,medium,high,urgent',
            'color' => 'nullable|string|max:7',
            'start_date' => 'nullable|date',
            'due_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $project->update($validated);

        Activity::log('updated', $project, 'updated project "' . $project->name . '"');

        return redirect()->route('projects.show', $project)
            ->with('success', 'Project updated successfully.');
    }

    public function destroy(Project $project)
    {
        $name = $project->name;
        $project->delete();

        return redirect()->route('projects.index')
            ->with('success', "Project \"{$name}\" deleted successfully.");
    }

    public function settings(Project $project)
    {
        $user = auth()->user();
        $project->load(['owner', 'team', 'members']);
        $teams = Team::where('company_id', $user->company_id)->get();
        $users = User::where('company_id', $user->company_id)->where('is_active', true)->get();
        return view('projects.settings', compact('project', 'teams', 'users'));
    }

    public function addMember(Request $request, Project $project)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'role' => 'in:member,admin,viewer',
        ]);

        $project->members()->syncWithoutDetaching([
            $request->user_id => ['role' => $request->input('role', 'member')],
        ]);

        return back()->with('success', 'Member added successfully.');
    }

    public function removeMember(Project $project, User $user)
    {
        $project->members()->detach($user->id);
        return back()->with('success', 'Member removed.');
    }

    public function archive(Project $project)
    {
        $project->update(['is_archived' => !$project->is_archived]);
        $action = $project->is_archived ? 'archived' : 'unarchived';
        return back()->with('success', "Project {$action} successfully.");
    }
}
