<?php

namespace App\Http\Controllers;

use App\Enums\Status;
use App\Models\Team;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class TeamController extends Controller
{
    /**
     * Display the teams listing page.
     */
    public function index()
    {
        return view('teams.index');
    }

    /**
     * Get teams data for DataTable.
     */
    public function datatable(Request $request)
    {
        $query = Team::query();

        return DataTables::of($query)
            ->addColumn('status', function ($team) {
                return $team->status->value;
            })
            ->make(true);
    }

    /**
     * Store a new team.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:teams,code',
            'notes' => 'nullable|string',
        ]);

        $team = Team::create([
            'name' => $validated['name'],
            'code' => $validated['code'],
            'notes' => $validated['notes'] ?? null,
            'status' => Status::ACTIVE,
        ]);

        return response()->json([
            'success' => true,
            'message' => __('Team created successfully.'),
            'data' => $team,
        ]);
    }

    /**
     * Get a single team.
     */
    public function show(Team $team)
    {
        return response()->json([
            'success' => true,
            'data' => $team,
        ]);
    }

    /**
     * Update a team.
     */
    public function update(Request $request, Team $team)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:teams,code,'.$team->id,
            'notes' => 'nullable|string',
        ]);

        $team->update([
            'name' => $validated['name'],
            'code' => $validated['code'],
            'notes' => $validated['notes'] ?? null,
        ]);

        return response()->json([
            'success' => true,
            'message' => __('Team updated successfully.'),
            'data' => $team,
        ]);
    }

    /**
     * Delete a team.
     */
    public function destroy(Team $team)
    {
        $team->delete();

        return response()->json([
            'success' => true,
            'message' => __('Team deleted successfully.'),
        ]);
    }

    /**
     * Toggle team status.
     */
    public function toggleStatus(Team $team)
    {
        $team->status = $team->status === Status::ACTIVE ? Status::INACTIVE : Status::ACTIVE;
        $team->save();

        return response()->json([
            'success' => true,
            'message' => __('Team status updated successfully.'),
        ]);
    }

    /**
     * Generate a unique team code.
     */
    public function generateCode()
    {
        $lastTeam = Team::orderBy('id', 'desc')->first();
        $nextId = $lastTeam ? $lastTeam->id + 1 : 1;
        $code = 'TEAM'.str_pad($nextId, 4, '0', STR_PAD_LEFT);

        // Ensure the code is unique
        while (Team::where('code', $code)->exists()) {
            $nextId++;
            $code = 'TEAM'.str_pad($nextId, 4, '0', STR_PAD_LEFT);
        }

        return response()->json([
            'code' => $code,
        ]);
    }

    /**
     * Get active teams for dropdown.
     */
    public function getActiveTeams()
    {
        $teams = Team::where('status', Status::ACTIVE)
            ->get(['id', 'name', 'code']);

        return response()->json([
            'success' => true,
            'data' => $teams,
        ]);
    }
}
