<?php

namespace App\Http\Controllers;

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

class HalamanUjianController extends Controller
{

    function fetchQuestion(Request $request) {
        $data_question = DataSoalModel::all();
        if($data_question != null) {
            $number_question = $request->question_index;
            if($number_question <= 0 || $number_question > count($data_question)) {
                $number_question = 1;
            }
            return response()->json([
                'status' => true,
                'data' => $data_question[$number_question - 1]
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => 'Data soal tidak ditemukan.'
            ]);
        }
    }

    public function getCurrentAnswer(Request $request) {
        $data_choice = DataSoalModel::where('id_soal', $request->id_question)->get();
        $choices = [];
        if($data_choice != null) {
            foreach($data_choice as $choice) {
                if($choice->jawaban_a != null) {
                    $choices[] = [
                        'key' => 'a',
                        'value' => $choice->jawaban_a
                    ];
                }
                if($choice->jawaban_b != null) {
                    $choices[] = [
                        'key' => 'b',
                        'value' => $choice->jawaban_b
                    ];
                }
                if($choice->jawaban_c != null) {
                    $choices[] = [
                        'key' => 'c',
                        'value' => $choice->jawaban_c
                    ];
                }
                if($choice->jawaban_d != null) {
                    $choices[] = [
                        'key' => 'd',
                        'value' => $choice->jawaban_d
                    ];
                }
                if($choice->jawaban_e != null) {
                    $choices[] = [
                        'key' => 'e',
                        'value' => $choice->jawaban_e
                    ];
                }
            }
        } else {
            return response()->json([
                'status' => false,
                'jawaban' => null,
                'choices' => null
            ]);
        }
        $data_answer = DetailTestModel::where('id_soal', $request->id_question)
            ->where('id_test_sessions', $request->session_id)
            ->first();

        if($data_answer != null) {
            return response()->json([
                'status' => true,
                'jawaban' => $data_answer->jawaban,
                'choices' => $choices
            ]);
        } else {
            return response()->json([
                'status' => true,
                'jawaban' => null,
                'choices' => $choices
            ]);
        }
    }

    public function getNavigationField(Request $request) {
        $id_session = null;
        if(session('session_id') != null) {
            $id_session = session('session_id');
        } else if($request->session_id != null) {
            $id_session = $request->session_id;
        } else {
            return response()->json([
                'status' => false,
                'msg' => 'Test session id tidak ditemukan'
            ]);
        }

        $data_soal = DataSoalModel::all();
        $result = [];
        $index = 1;
        foreach($data_soal as $soal) {
            $data_jawaban = DetailTestModel::where(['id_soal' => $soal->id_soal, 'id_test_sessions' => $id_session])->first();
            if($data_jawaban != null) {
                $result[] = [
                    'index' => $index,
                    'answered' => true,
                    'data' => $data_jawaban
                ];
            } else {
                $result[] = [
                    'index' => $index,
                    'answered' => false
                ];
            }
            $index += 1;
        }

        return response()->json([
            'status' => true,
            'data' => $result
        ]);
    }

    public function getTimeLeft(Request $request) {
        $data_session = TestSessionsModel::where('id_test_sessions', $request->session_id)->first();
        if($data_session != null) {
            if($data_session->status_session != '1') {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Data sesi tes belum dimulai atau telah usai. Silahkan cek status dengan kode untuk informasi lebih lanjut.'
                ]);
            } else if($data_session->status_session == '1') {
                if($data_session->is_active == '1') {
                    $time_left = $data_session->unix_end_time - time();
                    if($time_left <= 0) {
                        $data_session->update([
                            'status_session' => '2',
                            'is_active' => '0'
                        ]);
                        return response()->json([
                            'status' => 'error',
                            'message' => 'Waktu sesi tes telah habis. Silahkan cek status dengan kode untuk informasi lebih lanjut.'
                        ]);
                    } else {
                        return response()->json([
                            'status' => 'success',
                            'time_left' => $data_session->unix_end_time
                        ]);
                    }
                } else {
                    return response()->json([
                        'status' => 'error',
                        'message' => 'Sesi tes belum aktif. Silahkan mulai tes terlebih dahulu.'
                    ]);
                }
            }
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Data sesi tes tidak ditemukan. Silakan mulai tes terlebih dahulu.'
            ]);
        }
    }

    /**
     * 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) {
            if($data_session->status_session != '1') {
                return redirect()->route('cek-status.index')->with('error', 'Data sesi tes belum dimulai atau telah usai. Silahkan cek status dengan kode untuk informasi lebih lanjut.');
            } else if($data_session->status_session == '1') {
                if($data_session->is_active == '0') {
                    $data_session->update([
                        'is_active' => '1',
                        'unix_start_time' => time(),
                        'unix_end_time' => time() + (20 * 60)
                    ]);
                } else if($data_session->is_active == '1') {
                    if(time() > $data_session->unix_end_time) {
                        $data_booking = BookingModel::where('id_booking', $data_session->id_booking)->first();
                        $data_session->update([
                            'status_session' => '2',
                            'is_active' => '0'
                        ]);
                        $data_booking->update([
                            'status_tes' => '2'
                        ]);
                        return redirect()->route('cek-status.index')->with('error', 'Waktu sesi tes telah habis. Silahkan cek status dengan kode untuk informasi lebih lanjut.');
                    }
                }
            }
        } else {
            return redirect()->route('cek-status.index')->with('error', 'Data sesi tes tidak ditemukan. Silakan mulai tes terlebih dahulu.');
        }

        // $question_number = null;
        // $data_question = null;
        // if(session('question') != null) {
        //     $question_number = session('question');
        // } else if($request->question != null) {
        //     $question_number = $request->question;
        // } else {
        //     $question_number = 1;
        // }

        // $data_question = DataSoalModel::all();
        // $answered_question = [];
        // $index_question = 1;
        // foreach($data_question as $detail) {
        //     $detail_answer = DetailTestModel::where('id_soal', $detail->id_soal)
        //         ->where('id_test_sessions', $id_session)
        //         ->first();
        //     if($detail_answer != null) {
        //         $answered_question[] = [
        //             'id_soal' => $detail->id_soal,
        //             'nomor_soal' => $index_question,
        //             'answered' => true,
        //             'jawaban' => $detail_answer->jawaban
        //         ];
        //     } else {
        //         $answered_question[] = [
        //             'id_soal' => $detail->id_soal,
        //             'nomor_soal' => $index_question,
        //             'answered' => false,
        //             'jawaban' => null
        //         ];
        //     }
        //     $index_question++;
        // }

        // $total_question = null;
        // $is_last_question = false;
        // if($question_number <= 0 || $question_number > count($data_question)) {
        //     $question_number = 1;
        // }
        // if(count($data_question) == $question_number) {
        //     $is_last_question = true;
        // }
        // $total_question = count($data_question);
        // $data_question = $data_question[$question_number - 1];

        // $answer = [];
        // if($data_question->jawaban_a != null) {
        //     $answer[] = [
        //         'key' => 'a',
        //         'value' => $data_question->jawaban_a
        //     ];
        // }
        // if($data_question->jawaban_b != null) {
        //     $answer[] = [
        //         'key' => 'b',
        //         'value' => $data_question->jawaban_b
        //     ];
        // }
        // if($data_question->jawaban_c != null) {
        //     $answer[] = [
        //         'key' => 'c',
        //         'value' => $data_question->jawaban_c
        //     ];
        // }
        // if($data_question->jawaban_d != null) {
        //     $answer[] = [
        //         'key' => 'd',
        //         'value' => $data_question->jawaban_d
        //     ];
        // }
        // if($data_question->jawaban_e != null) {
        //     $answer[] = [
        //         'key' => 'e',
        //         'value' => $data_question->jawaban_e
        //     ];
        // }

        // dd($answer);

        return view("user.pages.ujian.temp_index", compact('data_session'));
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $data_session = TestSessionsModel::where('id_test_sessions', $request->session_id)->first();
        if($data_session != null) {
            if($data_session->status_session != '1') {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Data sesi tes belum dimulai atau telah usai. Silahkan cek status dengan kode untuk informasi lebih lanjut.'
                ]);
            }
            DetailTestModel::updateOrCreate(
                [
                    'id_soal' => $request->id_question,
                    'id_test_sessions' => $request->session_id
                ],
                [
                    'jawaban' => $request->jawaban_final
                ]
            );
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Data sesi tes tidak ditemukan. Silakan mulai tes terlebih dahulu.'
            ]);
        }

    }

    /**
     * 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)
    {
        //
    }
}
