<?php

namespace App\Http\Controllers;

use App\Models\CompetitionAthlete;
use App\Models\Competition;
use App\Models\Athlete;
use App\Models\Group;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Imports\CompetitionAthleteImport;
use Maatwebsite\Excel\Facades\Excel;
class CompetitionAthleteController extends Controller
{
    /**
     * Show all competition-athlete assignments.
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $query = CompetitionAthlete::with(['competition', 'athlete', 'group'])->latest();
        // If the user is a club account, restrict to their club’s entries
        if (!empty($user->is_club) && $user->is_club) {
            $query->whereHas('athlete', function ($q) use ($user) {
                $q->where('club_id', $user?->club?->id);
            });
        }

        $assignments = $query->get();

        return view('competition_athlete.index', compact('assignments'));
    }

    /**
     * Show create form.
     */
    public function create()
    {
        $user = Auth::user();

        // Ongoing competitions (today within start/end)
        $competitions = \App\Models\Competition::whereDate('start_date', '<=', now())->whereDate('end_date', '>=', now())->orderBy('start_date', 'desc')->get();

        // Active athletes (restricted to club if user is a club account)
        $athleteQuery = \App\Models\Athlete::with('club:id,name')->orderBy('first_name');

        if (!empty($user->is_club) && $user->is_club) {
            // assumes users table has club_id
            $athleteQuery->where('club_id', $user->club_id);
        }

        $athletes = $athleteQuery->get();

        // Groups (you can later filter by a selected competition via AJAX, if needed)
        $groups = \App\Models\Group::orderBy('name')->get();

        return view('competition_athlete.create', compact('competitions', 'athletes', 'groups'));
    }

    /**
     * Store a new competition-athlete assignment.
     */
    public function store(Request $request)
    {
        $request->validate([
            'competition_id' => 'required|exists:competitions,id',
            'athlete_id' => 'required|exists:athletes,id',
            'group_id' => 'nullable|exists:groups,id',
        ]);
        $competitionId = $request->competition_id;
        $athleteId = $request->athlete_id;

        // Block if athlete already tied to another ACTIVE competition
        $alreadyInActive = CompetitionAthlete::query()
            ->where('athlete_id', $athleteId)
            ->with('competition')
            ->whereHas('competition', function ($q) {
                $q->where(function ($qq) {
                    $qq->whereNull('end_date')->orWhere('end_date', '>', now());
                });
            })
            ->first();

        if ($alreadyInActive) {
            return back()
                ->withErrors(['athlete_id' => 'This athlete is already registered in another active competition.'])
                ->withInput();
        }
        CompetitionAthlete::create($request->only(['competition_id', 'athlete_id', 'group_id']));

        return redirect()->route('competitionathlete.index')->with('success', 'Athlete assigned successfully.');
    }

    /**
     * Show edit form for an assignment.
     */
    public function edit($id)
    {
        $user = Auth::user();
        $assignment = CompetitionAthlete::findOrFail($id);
        $competitions = \App\Models\Competition::whereDate('start_date', '<=', now())->whereDate('end_date', '>=', now())->orderBy('start_date', 'desc')->get();
        $athletes = \App\Models\Athlete::query()
            ->when(!empty($user->is_club) && $user->is_club, function ($query) use ($user) {
                $query->where('club_id', $user?->club?->id);
            })
            ->with('club:id,name')
            ->orderBy('first_name')
            ->get(['id', 'first_name', 'last_name', 'club_id']);
        $groups = Group::where('competition_id', $assignment->competition_id)->get();

        return view('competition_athlete.edit', compact('assignment', 'competitions', 'athletes', 'groups'));
    }

    /**
     * Update an existing assignment.
     */
    public function update(Request $request, $id)
    {
        $assignment = CompetitionAthlete::findOrFail($id);

        $request->validate([
            'competition_id' => 'required|exists:competitions,id',
            'athlete_id' => 'required|exists:athletes,id',
            'group_id' => 'nullable|exists:groups,id',
        ]);

        $assignment->update($request->only(['competition_id', 'athlete_id', 'group_id']));

        return redirect()->route('competitionathlete.index')->with('success', 'Assignment updated successfully.');
    }

    public function destroy($id)
    {
        $assignment = CompetitionAthlete::findOrFail($id);
        $assignment->delete();

        return redirect()->route('competitionathlete.index')->with('success', 'Assignment deleted.');
    }

    public function getGroups($competitionId)
    {
        $groups = Group::where('competition_id', $competitionId)->get(['id', 'name']);
        return response()->json($groups);
    }

    public function getAthletes($competitionId)
    {
        $competition = \App\Models\Competition::findOrFail($competitionId);
        $user = Auth::user();

        $athletes = \App\Models\Athlete::query()
            ->when($competition->gender !== 'mixed', function ($query) use ($competition) {
                $query->where('gender', $competition->gender);
            })
            ->when(!empty($user->is_club) && $user->is_club, function ($query) use ($user) {
                $query->where('club_id', $user?->club?->id);
            })
            ->with('club:id,name')
            ->orderBy('first_name')
            ->get(['id', 'first_name', 'last_name', 'club_id']);

        return response()->json($athletes);
    }

    public function importExcel(Request $request)
    {
        if ($request->file('excel')->getSize() < 20) {
            return back()->with('invalidRows', [['error' => 'Excel file has no data rows']]);
        }

        $import = new CompetitionAthleteImport();

        try {
            Excel::import($import, $request->file('excel'));
        } catch (\Exception $e) {
            return back()->with('invalidRows', [['error' => 'No data found in Excel']]);
        }

        return back()
            ->with('success', "Imported {$import->insertCount} rows successfully.")
            ->with('invalidRows', $import->invalid);
    }
}
