<?php

namespace App\Http\Controllers\tables;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Quiz;
use App\Models\Nilai;
use App\Models\KartuKendali;
use App\Imports\QuizImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Auth;

class QuizController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $nilai = "";
        $kartuKendali = "";

        if ($user->role == "Siswa") {
            $nilai = Nilai::where("user_id", "=", $user->id)->first();
            $quiz = Quiz::where("jenjang", "=", $user->kelas)->get();
            $kartuKendali = KartuKendali::where("user_id", "=", $user->id)->first();
        } else {
            $quiz = Quiz::all();
        }

        return view('content.quiz.index', compact('quiz', 'nilai', 'kartuKendali'));
    }

    public function create()
    {
        return view('content.quiz.create');
    }

    public function edit(Request $request, $quizId)
    {
        $quiz = quiz::find($quizId);
        return view('content.quiz.edit', compact('quiz'));
    }

    public function insert(Request $request)
    {
        if (isset($request->file)) {
            Quiz::truncate();
            Excel::import(new QuizImport, request()->file('file'));
        } else {
            Quiz::create([
                "jenjang" => $request->jenjang,
                "jenis" => $request->jenis,
                "soal" => $request->soal,
                "jawaban" => $request->jawaban,
                "jawaban_benar" => $request->jawaban_benar,
            ]);
        }

        return redirect()->route("quiz")->with("success", "Data Berhasil Disimpan!");
    }
    public function update(Request $request, $quizId)
    {
        $quiz = Quiz::find($quizId);
        $quiz->fill($request->input())->save();

        return redirect()->route("quiz")->with("success", "Data Berhasil Diperbarui!");
    }

    public function calculate(Request $request)
    {
        $quizType = strtolower($request->data[0]["jenis"]);
        $nilai = Nilai::where("user_id", "=", $request->user["id"])->first();
        $scorePerItem = intval(100 / count($request->data));
        $score = 0;

        for ($i = 0; $i < count($request->data); $i++) {
            if ($request->data[$i]["jawaban_benar"] == $request->data[$i]["input_jawaban"]) {
                $score += $scorePerItem;
            }
        }

        if ($score > 100) {
            $score = 100;
        }

        $nilai->update([
            $quizType => $score
        ]);

        return $score;
    }

    public function destroy(Request $request, $quizId)
    {
        $id = $quizId;
        $quiz = Quiz::find($id);

        $quiz->delete();

        return redirect()->route("quiz")->with("success", "Data Berhasil Dihapus!");
    }
}
