<?php

namespace App\Http\Controllers;

use App\Models\AlternatifSolusi;
use App\Models\Category;
use App\Models\FinalAkhir;
use App\Models\JawabanAlternatif;
use App\Models\JawabanKuis;
use App\Models\JawabanPuzle;
use App\Models\PuzleQuestion;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class HasilController extends Controller
{
    public function index()
    {
        $data = User::withCount('answer')->where('role', 'user')->get();
        // dd($data);
        return view('admin.hasil.index', compact('data'));
    }

    public function detail($id)
    {
        $id = Crypt::decrypt($id);
        $user = User::findOrFail($id);
        $data = Category::withCount([
            'jawabanUser as total_jawaban' => function ($query) use ($id) {
                $query->where('user_id', $id);
            }
        ])->get();
        // dd($data);
        return view('admin.hasil.detail', compact('user', 'data'));
    }

    public function detailKategori($id, $userId)
    {
        $id = Crypt::decrypt($id);
        $data = FinalAkhir::with('caseStudy')->where('user_id', $userId)->where('category_id', $id)->get();
        $user = User::findOrFail($userId);
        // dd($jawaban);
        return view('admin.hasil.detail_kategori', compact('user', 'data'));
    }

    public function detailJawaban($id)
    {
        $id = Crypt::decrypt($id);
        $jawaban = FinalAkhir::with('caseStudy')->with('user')->find($id);
        $user = $jawaban->user_id;
        $sesi = $jawaban->sesi;
        $case_id = $jawaban->case_study_id;
        $quiz = JawabanKuis::with('choice')
            ->where('user_id', $jawaban->user_id)
            ->where('case_study_id', $jawaban->case_study_id)
            ->where('sesi', $jawaban->sesi)
            ->get();
        // dd($quiz);

        $alternatif = JawabanAlternatif::where('user_id', $user)->where('case_study_id', $case_id)->where('sesi', $sesi)->first();
        $alternatif_question = AlternatifSolusi::where('case_study_id', $case_id)->first();
        $puzzle = JawabanPuzle::where('user_id', $user)->where('case_study_id', $case_id)->where('sesi', $sesi)->first();
        $puzzle_question = PuzleQuestion::where('case_study_id', $case_id)->first();
        return view('admin.hasil.detail_jawaban', compact('jawaban', 'quiz', 'alternatif', 'alternatif_question', 'puzzle', 'puzzle_question'));
    }
}
