<?php

namespace App\Http\Controllers;

use App\Models\BookingModel;
use App\Models\DataSoalModel;
use App\Models\DetailTestModel;
use App\Models\LogKecemasanModel;
use App\Models\TestSessionsModel;
use Illuminate\Http\Request;

class FinishUjianController extends Controller
{

    public function getNotAnswered(Request $request) {
        $data_session = TestSessionsModel::where('id_test_sessions', $request->id_test_sessions)->first();
        if($data_session != null) {
            if($data_session->status_session == '0') {
                return response()->json([
                    'status' => false,
                    'message' => 'Data sesi tes dinonaktifkan. Silahkan cek status dengan kode untuk informasi lebih lanjut.'
                ]);
            } else if($data_session->status_session == '2') {
                $soal = DataSoalModel::all();
                $data_ujian = [];
                foreach($soal as $detail) {
                    $data_soal = DetailTestModel::where('id_soal', $detail->id_soal)->where('id_test_sessions', $request->id_test_sessions)->first();
                    if($data_soal == null) {
                        $data_ujian[] = [
                            'id_soal' => $detail->id_soal,
                            'soal' => $detail->pertanyaan,
                            'skor' => 0
                        ];
                    }
                }
                return response()->json([
                    'status' => true,
                    'data' => $data_ujian
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => 'Data sesi tes tidak ditemukan.'
            ]);
        }
    }

    public function getAllAnswer(Request $request) {
        $data_session = TestSessionsModel::where('id_test_sessions', $request->id_test_sessions)->first();
        if($data_session != null) {
            if($data_session->status_session == '0') {
                return response()->json([
                    'status' => false,
                    'message' => 'Data sesi tes dinonaktifkan. Silahkan cek status dengan kode untuk informasi lebih lanjut.'
                ]);
            } else if($data_session->status_session == '2') {
                $detail_test = DetailTestModel::where('id_test_sessions', $request->id_test_sessions)->get();
                $data_ujian = [];
                foreach($detail_test as $detail) {
                    $data_soal = DataSoalModel::where('id_soal', $detail->id_soal)->first();
                    $data_jawaban = $detail->jawaban;
                    $skor = null;
                    if($data_jawaban == 'a') {
                        $data_jawaban = $data_soal->jawaban_a;
                        $skor = 1;
                    } else if($data_jawaban == 'b') {
                        $data_jawaban = $data_soal->jawaban_b;
                        $skor = 2;
                    } else if($data_jawaban == 'c') {
                        $data_jawaban = $data_soal->jawaban_c;
                        $skor = 3;
                    } else if($data_jawaban == 'd') {
                        $data_jawaban = $data_soal->jawaban_d;
                        $skor = 4;
                    } else if($data_jawaban == 'e') {
                        $data_jawaban = $data_soal->jawaban_e;
                    } else {
                        $data_jawaban = 'Tidak menjawab';
                    }

                    if($detail->jawaban == 'a' && $data_soal->is_reverse == 1) {
                        $skor = 4;
                    } else if($detail->jawaban == 'b' && $data_soal->is_reverse == 1) {
                        $skor = 3;
                    } else if($detail->jawaban == 'c' && $data_soal->is_reverse == 1) {
                        $skor = 2;
                    } else if($detail->jawaban == 'd' && $data_soal->is_reverse == 1) {
                        $skor = 1;
                    }

                    $data_ujian[] = [
                        'id_soal' => $detail->id_soal,
                        'jawaban' => $data_jawaban,
                        'is_reverse' => $data_soal->is_reverse,
                        'skor' => $skor,
                        'jawaban_key' => $detail->jawaban,
                        'soal' => $data_soal->pertanyaan
                    ];
                }
                return response()->json([
                    'status' => true,
                    'data' => $data_ujian
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => 'Data sesi tes tidak ditemukan.'
            ]);
        }
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $id_session = null;
        if(session('id_test_sessions') != null) {
            $id_session = session('id_test_sessions');
        } else if($request->id_test_sessions != null) {
            $id_session = $request->id_test_sessions;
        } else {
            return redirect()->route('cek-status.index')->with('error', 'Data sesi tes tidak ditemukan. Silakan mulai tes terlebih dahulu.');
        }

        $data_session = TestSessionsModel::where('id_test_sessions', $id_session)->first();
        if($data_session != null) {
            $start = strtotime($data_session->created_at);
            $end = strtotime($data_session->updated_at);
            $difference = gmdate("i:s", $end - $start);

            $data_booking = BookingModel::where('id_booking', $data_session->id_booking)->first();
            if($data_booking != null) {
                if($data_booking->status_tes == '0') {
                    return redirect()->route('cek-status.index')->with('error', 'Data sesi tes tidak ditemukan atau telah dinonaktifkan.');
                }
            }
            $data_information = [
                'kode' => $data_booking->kode_unik,
                'nama' => $data_booking->nama_lengkap,
                'email' => $data_booking->email,
                'no_hp' => $data_booking->no_telp,
            ];

            $screen_dim = [
                'width' => $data_session->screen_w,
                'height' => $data_session->screen_h
            ];

            $answered = DetailTestModel::where('id_test_sessions', $id_session)->where('jawaban', '!=', null)->count();
            $question_count = DataSoalModel::all()->count();
            $soalTerjawab = $answered;
            $soalTidakTerjawab = $question_count - $answered;

            $totalScore = 0;
            $detail_test = DetailTestModel::where('id_test_sessions', $request->id_test_sessions)->get();
            foreach($detail_test as $detail) {
                $data_soal = DataSoalModel::where('id_soal', $detail->id_soal)->first();
                $data_jawaban = $detail->jawaban;
                if($data_soal->is_reverse == 1) {
                    if($data_jawaban == 'a') {
                        $totalScore += 4;
                    } else if($data_jawaban == 'b') {
                        $totalScore += 3;
                    } else if($data_jawaban == 'c') {
                        $totalScore += 2;
                    } else if($data_jawaban == 'd') {
                        $totalScore += 1;
                    } else if($data_jawaban == 'e') {
                        $totalScore += 0;
                    }
                } else {
                    if($data_jawaban == 'a') {
                        $totalScore += 1;
                    } else if($data_jawaban == 'b') {
                        $totalScore += 2;
                    } else if($data_jawaban == 'c') {
                        $totalScore += 3;
                    } else if($data_jawaban == 'd') {
                        $totalScore += 4;
                    } else if($data_jawaban == 'e') {
                        $totalScore += 5;
                    }
                }
                
            }
            $data_aswered = [
                'total_question' => $question_count,
                'answered' => $answered,
                'unanswered' => $soalTidakTerjawab,
                'totalScore' => $totalScore
            ];

            $log_kecemasan = LogKecemasanModel::where('id_test_sessions', $id_session)->first();
            if($log_kecemasan == null) {
                LogKecemasanModel::create([
                    'id_booking' => $data_session->id_booking,
                    'id_test_sessions' => $id_session,
                    'start_timestamp' => $start,
                    'end_timestamp' => $end,
                    'difference_timestamp' => $end - $start,
                    'screen_width' => $data_session->screen_w,
                    'screen_height' => $data_session->screen_h,
                    'answered_count' => $answered,
                    'not_answered_count' => $soalTidakTerjawab,
                    'total_question' => $question_count,
                    'skor_kecemasan' => $totalScore
                ]);
            }

            $data_booking = BookingModel::where('id_booking', $data_session->id_booking)->first();
            if($data_session->status_session == '0') {
                return redirect()->route('cek-status.index')->with('error', 'Data sesi tes dinonaktifkan. Silahkan cek status dengan kode untuk informasi lebih lanjut.');
            } else if($data_session->status_session == '1') {
                $data_session->update([
                    'status_session' => '2',
                    'is_active' => '0'
                ]);
                $data_booking->update([
                    'status_tes' => '2'
                ]);
                return view('user.pages.finish_ujian.index', compact('id_session', 'difference', 'data_information', 'screen_dim', 'data_aswered'));
            } else if($data_session->status_session == '2') {
                $data_booking->update([
                    'status_tes' => '2'
                ]);
                return view('user.pages.finish_ujian.index', compact('id_session', 'difference', 'data_information', 'screen_dim', 'data_aswered'));
            }
        } else {
            return redirect()->route('cek-status.index')->with('error', 'Data sesi tes tidak ditemukan.');
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
