<?php

namespace App\Http\Controllers;

use App\Models\QuizQuestion;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\QuizQuestionChoice;

class QuizQuestionController extends Controller
{
    function uploadcsv(Request $request)
    {
        $category = Category::all();
        return view('questions.upload',compact('category'));
    }
    public function importcsv(Request $request)
    {
             // Validate the uploaded file.
            $request->validate([
                'csv_file' => 'required|mimes:csv,txt'
            ]);

            // Get the file from the request.
            $file = $request->file('csv_file');

            // Read the CSV file.
            $csvData = file_get_contents($file);

            // Convert the CSV data to an array of rows.
            $rows = array_map('str_getcsv', explode("\n", $csvData));
            // Remove the header row if it exists.
            $header = array_shift($rows);
           // dd($rows);
            $category = $request->category;
            foreach ($rows as $row) {
                // Create a new Question instance.
                if(!empty($row[0])){
                    $questionObj = new QuizQuestion();
                    $questionObj->cat_id = $category;
                    $questionObj->question = $row[0];
                    if($questionObj->save())
                    {
                        $choice1 = $row[1];
                        $choice2 = $row[2];
                        $choice3 = $row[3];
                        $choice4 = $row[4];
                        $choicearray = [$choice1,$choice2,$choice3,$choice4];
                        $correct = $row[5];
                        foreach($choicearray as $Key=>$val)
                        {
                            $choiceObj = new QuizQuestionChoice();
                            $choiceObj->question_id = $questionObj->id;
                            $choiceObj->choice = $val;
                            $iscorrect = 0;
                            if($correct == $val){
                                $iscorrect = 1;
                            }
                            $choiceObj->is_correct = $iscorrect;
                            $choiceObj->save();
                        }
                        
                    }
                }
              
        
              
            }
            return redirect()->route('question.index')->with('success', 'CSV imported successfully!');

    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $questions = QuizQuestion::with('choices', 'category')->orderByDesc('created_at')->paginate(10);
        //dd($questions);
        return view('questions.index',compact('questions'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $category = Category::all();
        return view('questions.create',compact('category'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $category = $request->category;
        $question = $request->question;
        $questionObj = new QuizQuestion();
        $questionObj->cat_id = $category;
        $questionObj->question = $question;
        if($questionObj->save())
        {
            $question_id = $questionObj->id;
            foreach($request->choice as $key=>$val)
            {
                $choiceObj = new QuizQuestionChoice();
                $choiceObj->question_id = $question_id;
                $choiceObj->choice = $val;
                $choiceObj->is_correct = $request->is_correct[$key];
                $choiceObj->save();
            }
            return redirect()->route('question.index')->with('success', 'Question has been added successfully');
        }
        return redirect()->route('question.create')->with('error', 'Something went wrong! Try again later.');
        
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\QuizQuestion  $quizQuestion
     * @return \Illuminate\Http\Response
     */
    public function show(QuizQuestion $quizQuestion)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\QuizQuestion  $quizQuestion
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $question = QuizQuestion::findOrFail($id);
        return view('questions.edit', compact('question'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\QuizQuestion  $quizQuestion
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $question = QuizQuestion::findOrFail($id);
    $question->question = $request->input('question');
    $question->save();

    // Update choices (options)
    $choices = $request->input('choices');
    $correctOption = $request->input('correct_option');

    // Validate correct_option selection
    if (!in_array($correctOption, array_keys($choices))) {
        return redirect()->back()->with('error', 'Please select a valid correct option.');
    }

    foreach ($choices as $choiceId => $choiceText) {
        $choice = QuizQuestionChoice::findOrFail($choiceId);
        $choice->choice = $choiceText;
        $choice->is_correct = $choiceId == $correctOption ? 1 : 0;
        $choice->save();
    }
    return redirect()->route('question.index', $question->id)->with('success', 'Quiz question and choices updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\QuizQuestion  $quizQuestion
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $question = QuizQuestion::findOrFail($id);
        $question->choices()->delete(); // Delete choices associated with the question
        $question->delete(); // Delete the question itself
        return redirect()->route('question.index')->with('success', 'Quiz question and choices deleted successfully.');
    }
}
