<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Lesson;
use App\Models\Course;

class CurriculamController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    //*** GET Request
    public function curriculamLesson($id)
    {
        $lsn = Lesson::find($id);
        $data = Course::find($lsn->section->course->id);
        return view('student.curriculam_view',compact('data','lsn'));
    }

    //*** POST Request
    public function result(Request $request)
    {
        $input = $request->all();
        $lsn = Lesson::find($input['lesson_id']);
        $answers = $input['answers'];
        $result = [];
        $result['correct_answers_count'] = 0;
        $result['correct_answers'] = [];
        $result['submitted_answers'] = [];
        $result['main_answers'] = [];

        $pi = 0;
        foreach($answers as $pans){
            $ci = 0;
            foreach($pans as $key => $ans){
                if($ans == 1){
                    $result['submitted_answers'][$pi][$ci] = $key;
                    $ci++;
                }

            }
            $pi++;
        }

        $pi = 0;
        foreach($lsn->questions()->oldest('pos')->get() as $key => $qsn){

            if($answers[$key] == json_decode($qsn->answers,true)){
                $result['main_answers'][$key] = true;
                $result['correct_answers_count']++;
            }else{
                $result['main_answers'][$key] = false;
            }

            $ci = 0;
            foreach(json_decode($qsn->answers,true) as $key => $ans){
                if($ans == 1){
                    $result['correct_answers'][$pi][$ci] = $key;
                    $ci++;
                }

            }

            $pi++;
        }


        return redirect()->back()->with('result',$result);
    }
}
