<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Challenge;
use App\Models\PesertaChallenge;
use App\Models\Guru;
use Illuminate\Http\Request;

class ChallengeController extends Controller
{
    public function index(Request $request)
{
    $query = Challenge::with(['guru', 'kelas'])
        ->withCount('soal as soal_count');

    // Filter by guru
    if ($request->filled('id_guru')) {
        $query->where('id_guru', $request->id_guru);
    }

    // Search judul
    if ($request->filled('search')) {
        $query->where('judul_challenge', 'like', '%' . $request->search . '%');
    }

    $challenges = $query->latest()
        ->paginate(10)
        ->appends($request->all()); // ganti withQueryString() → appends()

    $guruList = Guru::orderBy('nama')->get(); // ambil semua guru, pakai model import

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

    public function show($id)
    {
        $challenge = Challenge::with(['kelas', 'soal', 'guru', 'peserta.siswa'])
            ->findOrFail($id);

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

    public function destroy($id)
    {
        Challenge::findOrFail($id)->delete();
        return redirect()->route('admin.challenge.index')
            ->with('success', 'Challenge berhasil dihapus.');
    }
}