<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Team;
use App\Models\Business;
use Illuminate\Http\Request;

class TeamController extends Controller
{
    /**
     * Display a listing of teams
     */
    public function index()
    {
        $teams = Team::with('business')->paginate(50);

        $stats = [
            'total' => Team::count(),
            'active' => Team::where('status', 'active')->count(),
        ];

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

    /**
     * Display the specified team
     */
    public function show($id)
    {
        $team = Team::findOrFail($id);
        $team->load('business', 'members');

        return view('admin.teams.show', compact('team'));
    }

    /**
     * Show the form for creating a new team
     */
    public function create()
    {
        $businesses = Business::all();
        return view('admin.teams.create', compact('businesses'));
    }

    /**
     * Store a newly created team
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'business_id' => 'required|exists:businesses,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
        ]);

        $team = Team::create($validated);

        return redirect()->route('admin.teams.show', $team->id)
            ->with('success', 'Team created successfully.');
    }

    /**
     * Show the form for editing the specified team
     */
    public function edit($id)
    {
        $team = Team::findOrFail($id);
        $team->load('business');
        $businesses = Business::all();

        return view('admin.teams.edit', compact('team', 'businesses'));
    }

    /**
     * Update the specified team
     */
    public function update(Request $request, $id)
    {
        $team = Team::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'status' => 'required|in:active,inactive',
        ]);

        $team->update($validated);

        return redirect()->route('admin.teams.show', $team->id)
            ->with('success', 'Team updated successfully.');
    }

    /**
     * Delete the specified team
     */
    public function destroy($id)
    {
        $team = Team::findOrFail($id);
        $team->delete();

        return redirect()->route('admin.teams.index')
            ->with('success', 'Team deleted successfully.');
    }

    /**
     * Add a member to team
     */
    public function addMember(Request $request, $id)
    {
        $team = Team::findOrFail($id);

        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'role' => 'required|string|in:member,manager,admin',
        ]);

        // Check if user is already a member
        if ($team->members()->where('user_id', $validated['user_id'])->exists()) {
            return back()->with('error', 'User is already a member of this team.');
        }

        $team->members()->attach($validated['user_id'], ['role' => $validated['role']]);

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

    /**
     * Remove a member from team
     */
    public function removeMember(Request $request, $id)
    {
        $team = Team::findOrFail($id);

        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
        ]);

        $team->members()->detach($validated['user_id']);

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

    /**
     * Update member role in team
     */
    public function updateRole(Request $request, $id)
    {
        $team = Team::findOrFail($id);

        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'role' => 'required|string|in:member,manager,admin',
        ]);

        $team->members()->updateExistingPivot($validated['user_id'], ['role' => $validated['role']]);

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

