<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Challenge;
use App\Models\SoalChallenge;
use App\Models\Kelas;
use App\Models\Badge;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

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

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

        $challenges = $query->orderBy('created_at', 'desc')
            ->paginate(10)
            ->appends($request->all());

        $kelas  = Kelas::orderBy('tingkat')->orderBy('nama_kelas')->get();
        $badges = Badge::all();

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

    public function store(Request $request)
    {
        $request->validate([
            'judul_challenge' => 'required|string|max:200',
            'deskripsi'       => 'nullable|string',
            'exp'             => 'required|integer|min:0',
            'id_badge'        => 'nullable|exists:badges,id_badge',
            'tenggat_waktu'   => 'required|date|after:now',
            'id_kelas'        => 'required|array|min:1',
            'id_kelas.*'      => 'exists:kelas,id_kelas',
            // Soal
            'pertanyaan'      => 'required|array|min:1',
            'pertanyaan.*'    => 'required|string',
            'opsi_a.*'        => 'required|string',
            'opsi_b.*'        => 'required|string',
            'opsi_c.*'        => 'required|string',
            'opsi_d.*'        => 'required|string',
            'jawaban_benar.*' => 'required|in:A,B,C,D',
            'exp_per_soal.*'  => 'required|integer|min:0',
        ], [
            'tenggat_waktu.after'  => 'Tenggat waktu harus lebih dari sekarang.',
            'pertanyaan.required'  => 'Minimal harus ada 1 soal.',
            'id_kelas.required'    => 'Pilih minimal 1 kelas.',
        ]);

        DB::transaction(function () use ($request) {
            $admin = Auth::guard('admin')->user();

            $challenge = Challenge::create([
                'id_admin'        => $admin->id_admin,
                'judul_challenge' => $request->judul_challenge,
                'deskripsi'       => $request->deskripsi,
                'exp'             => $request->exp,
                'id_badge'        => $request->id_badge,
                'tenggat_waktu'   => $request->tenggat_waktu,
            ]);

            // Attach ke kelas
            $challenge->kelas()->sync($request->id_kelas);

            // Simpan soal
            foreach ($request->pertanyaan as $i => $pertanyaan) {
                SoalChallenge::create([
                    'id_challenge'  => $challenge->id_challenge,
                    'pertanyaan'    => $pertanyaan,
                    'opsi_a'        => $request->opsi_a[$i],
                    'opsi_b'        => $request->opsi_b[$i],
                    'opsi_c'        => $request->opsi_c[$i],
                    'opsi_d'        => $request->opsi_d[$i],
                    'jawaban_benar' => $request->jawaban_benar[$i],
                    'exp_per_soal'  => $request->exp_per_soal[$i],
                ]);
            }
        });

        return redirect()->route('admin.challenge.index')
            ->with('success', 'Challenge berhasil dibuat!');
    }

    public function show($id)
    {
        $challenge = Challenge::with(['kelas', 'soal'])->findOrFail($id);
        return view('admin.challenge.show', compact('challenge'));
    }

    public function edit($id)
    {
        $challenge = Challenge::with(['kelas', 'soal'])->findOrFail($id);
        $kelas     = Kelas::orderBy('tingkat')->orderBy('nama_kelas')->get();
        $badges    = Badge::all();
        return view('admin.challenge.edit', compact('challenge', 'kelas', 'badges'));
    }

    public function update(Request $request, $id)
    {
        $challenge = Challenge::findOrFail($id);

        $request->validate([
            'judul_challenge' => 'required|string|max:200',
            'deskripsi'       => 'nullable|string',
            'exp'             => 'required|integer|min:0',
            'id_badge'        => 'nullable|exists:badges,id_badge',
            'tenggat_waktu'   => 'required|date',
            'id_kelas'        => 'required|array|min:1',
            'id_kelas.*'      => 'exists:kelas,id_kelas',
            'pertanyaan'      => 'required|array|min:1',
            'pertanyaan.*'    => 'required|string',
            'opsi_a.*'        => 'required|string',
            'opsi_b.*'        => 'required|string',
            'opsi_c.*'        => 'required|string',
            'opsi_d.*'        => 'required|string',
            'jawaban_benar.*' => 'required|in:A,B,C,D',
            'exp_per_soal.*'  => 'required|integer|min:0',
        ]);

        DB::transaction(function () use ($request, $challenge) {
            $challenge->update([
                'judul_challenge' => $request->judul_challenge,
                'deskripsi'       => $request->deskripsi,
                'exp'             => $request->exp,
                'id_badge'        => $request->id_badge,
                'tenggat_waktu'   => $request->tenggat_waktu,
            ]);

            $challenge->kelas()->sync($request->id_kelas);

            // Hapus soal lama, insert ulang
            SoalChallenge::where('id_challenge', $challenge->id_challenge)->delete();

            foreach ($request->pertanyaan as $i => $pertanyaan) {
                SoalChallenge::create([
                    'id_challenge'  => $challenge->id_challenge,
                    'pertanyaan'    => $pertanyaan,
                    'opsi_a'        => $request->opsi_a[$i],
                    'opsi_b'        => $request->opsi_b[$i],
                    'opsi_c'        => $request->opsi_c[$i],
                    'opsi_d'        => $request->opsi_d[$i],
                    'jawaban_benar' => $request->jawaban_benar[$i],
                    'exp_per_soal'  => $request->exp_per_soal[$i],
                ]);
            }
        });

        return redirect()->route('admin.challenge.index')
            ->with('success', 'Challenge berhasil diupdate!');
    }

    public function destroy($id)
    {
        Challenge::findOrFail($id)->delete();

        return redirect()->route('admin.challenge.index')
            ->with('success', 'Challenge berhasil dihapus.');
    }

    /**
     * AJAX — return data challenge untuk modal edit
     */
    public function editData($id)
    {
        $challenge = Challenge::with(['kelas', 'soal'])->findOrFail($id);

        return response()->json([
            'judul_challenge' => $challenge->judul_challenge,
            'deskripsi'       => $challenge->deskripsi,
            'exp'             => $challenge->exp,
            'id_badge'        => $challenge->id_badge,
            'tenggat_waktu'   => $challenge->tenggat_waktu,
            'kelas'           => $challenge->kelas->pluck('id_kelas'),
            'soal'            => $challenge->soal,
        ]);
    }
}