<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Challenge;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ChallengeController extends Controller
{
    public function index(): View
    {
        $challenges = Challenge::query()
            ->withCount('participants')
            ->latest()
            ->paginate(10);

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

    public function create(): View
    {
        return view('admin.challenges.create', ['challenge' => new Challenge()]);
    }

    public function store(Request $request): RedirectResponse
    {
        Challenge::create($this->validated($request));

        return redirect()->route('admin.challenges.index')->with('success', 'Challenge created successfully.');
    }

    public function edit(Challenge $challenge): View
    {
        return view('admin.challenges.edit', compact('challenge'));
    }

    public function show(Challenge $challenge): View
    {
        return view('admin.challenges.show', [
            'challenge' => $challenge->loadCount('participants'),
            'participants' => $challenge->participants()
                ->with('user')
                ->latest()
                ->paginate(20),
        ]);
    }

    public function update(Request $request, Challenge $challenge): RedirectResponse
    {
        $challenge->update($this->validated($request));

        return redirect()->route('admin.challenges.index')->with('success', 'Challenge updated successfully.');
    }

    public function destroy(Challenge $challenge): RedirectResponse
    {
        $challenge->delete();

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

    private function validated(Request $request): array
    {
        return $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:5000'],
            'rules' => ['nullable', 'string', 'max:10000'],
            'rewards' => ['nullable', 'string', 'max:10000'],
            'duration_days' => ['required', 'integer', 'min:1', 'max:365'],
            'is_active' => ['nullable', 'boolean'],
        ]) + ['is_active' => false];
    }
}
