<?php

namespace App\Http\Controllers\Admin;

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

class CurriculamController extends Controller
{

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

    //*** GET Request
    public function curriculam($id)
    {

        $data = Course::findOrFail($id);

        $show_lesson = false;
        foreach($data->sections as $sction){
            if(count($sction->lessons) > 0){
                $show_lesson = true;
            }
        }

        return view('admin.course.curriculam',compact('data','show_lesson'));
    }

    //*** GET Request
    public function curriculamLesson($id)
    {
        $lsn = Lesson::find($id);
        $data = Course::find($lsn->section->course->id);
        return view('admin.course.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);
    }



    //*** GET Request
    public function curriculamStatus(Request $request,$id)
    {
        $text = $request->text;
        return redirect()->route('admin-course-curriculam',$id)->with('success',$text);
    }

    //*** POST Request
    public function sectionStore(Request $request, $id)
    {
        //--- Logic Section

        $data = Course::find($id);
        $input = $request->all();
        $ck = $data->sections()->where('title',$input['title'])->count();
        $input['pos'] = $data->sections()->count() + 1;
        if($ck == 1){
            return response()->json(array('errors' => [ 0 => __('This Title Already Exists.') ]));
        }else{
            $data->sections()->create($input);
        }

        //--- Logic Section Ends

        //--- Redirect Section
        $msg = __('Section Created Successfully.');
        return response()->json($msg);
        //--- Redirect Section Ends

    }

    //*** POST Request
    public function sectionSortUpdate(Request $request, $id)
    {
        //--- Logic Section

        $data = Course::find($id);
        $input = $request->all();
        $i = 0;

        $pos = $input['pos'];

        foreach($data->sections()->oldest('pos')->get() as $section){
            $section->pos = $pos[$i];
            $section->update();
            $i++;
        }

        //--- Logic Section Ends

        //--- Redirect Section
        $msg = __('Section Sorted Successfully.');
        return redirect()->route('admin-course-curriculam',$id)->with('success',$msg);
        //--- Redirect Section Ends

    }

    //*** POST Request
    public function lessonStore(Request $request)
    {

        //--- Logic Section

        $input = $request->all();
        $data = Section::find($input['section_id']);
        $ck = $data->lessons()->where('title',$input['title'])->count();
        $input['pos'] = $data->lessons()->count() + 1;
        $links = ['youtube','vimeo','url'];
        $rules = null;
        if($ck == 1){
            return response()->json(array('errors' => [ 0 => __('This Title Already Exists.') ]));
        }else{
            if(!empty($input['video_file'])){

                if(in_array($input['video_file'], $links)){

                    //--- Validation Rules

                    $rules = [
                        'url'      => 'required'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                }else if($input['video_file'] == 'file'){

                    //--- Validation Rules

                    $rules = [
                        'file'      => 'mimes:mp4,ogg,webm|max:5000'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                    if ($file = $request->file('file')) {
                        $name = time().str_replace(' ', '', $file->getClientOriginalName());
                        $file->move('assets/files',$name);
                        $input['file'] = $name;
                    }

                }else if($input['video_file'] == 'document'){

                    //--- Validation Rules

                    $rules = [
                        'file'      => 'mimes:pdf,txt'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                    if ($file = $request->file('file')) {
                        $name = time().str_replace(' ', '', $file->getClientOriginalName());
                        $file->move('assets/files',$name);
                        $input['file'] = $name;
                    }

                }else if($input['video_file'] == 'image'){

                    //--- Validation Rules

                    $rules = [
                        'file'      => 'mimes:jpg,jpeg,png,gif'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                    if ($file = $request->file('file')) {
                        $name = time().str_replace(' ', '', $file->getClientOriginalName());
                        $file->move('assets/files',$name);
                        $input['file'] = $name;
                    }

                }else{

                    //--- Validation Rules

                    $rules = [
                        'iframe_code'      => 'required'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                }

            }

            $data->lessons()->create($input);
        }

        //--- Logic Section Ends

        //--- Redirect Section
        if($input['type'] == 'Lesson'){
            $msg = __('Lesson Created Successfully.');
        }else{
            $msg = __('Quiz Created Successfully.');
        }

        return response()->json($msg);
        //--- Redirect Section Ends

    }

    //*** GET Request
    public function lessonSort($id)
    {

        //--- Logic Section

        $data = Section::find($id);
        return view('admin.course.load.lessonSort',compact('data'));

        //--- Redirect Section Ends

    }

    //*** POST Request
    public function lessonSortUpdate(Request $request, $id)
    {
        //--- Logic Section

        $data = Section::find($id);
        $input = $request->all();
        $i = 0;
        $pos = $input['pos'];

        foreach($data->lessons()->oldest('pos')->get() as $lesson){
            $lesson->pos = $pos[$i];
            $lesson->update();
            $i++;
        }

        //--- Logic Section Ends

        //--- Redirect Section
        $msg = __('Lesson Sorted Successfully.');
        return redirect()->route('admin-course-curriculam',$data->course->id)->with('success',$msg);
        //--- Redirect Section Ends

    }

    //*** GET Request
    public function lessonEdit($id)
    {

        //--- Logic Section

        $data = Lesson::find($id);
        if($data->type == 'Lesson'){
            return view('admin.course.load.lesson',compact('data'));
        }else{
            return view('admin.course.load.quiz',compact('data'));
        }

        //--- Redirect Section Ends

    }

    //*** GET Request
    public function lessonQuiz($id)
    {

        //--- Logic Section

        $data = Lesson::find($id);
        return view('admin.course.load.quiz_question',compact('data'));

        //--- Redirect Section Ends

    }

    //*** POST Request
    public function lessonUpdate(Request $request, $id)
    {
        //--- Logic Section
        $section_id = $request->section_id;
        $sec = Section::find($section_id);
        $input = $request->all();
        $links = ['youtube','vimeo','url'];
        $ck = $sec->lessons()->where('id','!=',$id)->where('title',$input['title'])->count();
        $data = Lesson::find($id);

        if($ck == 1){
            return response()->json(array('errors' => [ 0 => __('This Title Already Exists.') ]));
        }else{

            if(!empty($input['video_file'])){

                if(in_array($input['video_file'], $links)){

                    //--- Validation Rules

                    $rules = [
                        'url'      => 'required'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                }else if($input['video_file'] == 'file'){

                    //--- Validation Rules

                    $rules = [
                        'file'      => 'mimes:mp4,ogg,webm|max:5000'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                    if($data->file != null){
                        if (file_exists(public_path().'/assets/files/'.$data->file)) {
                        unlink(public_path().'/assets/files/'.$data->file);
                        }
                    }

                    if ($file = $request->file('file')) {
                        $name = time().str_replace(' ', '', $file->getClientOriginalName());
                        $file->move('assets/files',$name);
                        $input['file'] = $name;
                    }

                }else if($input['video_file'] == 'document'){

                    //--- Validation Rules

                    $rules = [
                        'file'      => 'mimes:pdf,txt'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                    if($data->file != null){
                        if (file_exists(public_path().'/assets/files/'.$data->file)) {
                        unlink(public_path().'/assets/files/'.$data->file);
                        }
                    }

                    if ($file = $request->file('file')) {
                        $name = time().str_replace(' ', '', $file->getClientOriginalName());
                        $file->move('assets/files',$name);
                        $input['file'] = $name;
                    }

                }else if($input['video_file'] == 'image'){

                    //--- Validation Rules

                    $rules = [
                        'file'      => 'mimes:jpg,jpeg,png,gif'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                    if($data->file != null){
                        if (file_exists(public_path().'/assets/files/'.$data->file)) {
                        unlink(public_path().'/assets/files/'.$data->file);
                        }
                    }

                    if ($file = $request->file('file')) {
                        $name = time().str_replace(' ', '', $file->getClientOriginalName());
                        $file->move('assets/files',$name);
                        $input['file'] = $name;
                    }

                }else{

                    //--- Validation Rules

                    $rules = [
                        'iframe_code'      => 'required'
                    ];

                    $validator = Validator::make($request->all(), $rules);

                    if ($validator->fails()) {
                    return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
                    }

                    //--- Validation Rules Ends

                }

            }

            $data->update($input);
        }
        //--- Logic Section Ends

        //--- Redirect Section

        $msg = __('Section Updated Successfully.');
        return response()->json($msg);

        //--- Redirect Section Ends

    }

    //*** POST Request
    public function lessonDelete($id)
    {
        //--- Logic Section

        $data = Lesson::find($id);

        if($data->file != null)
        {

            if(file_exists(base_path('../assets/files/'.$data->file))){
                unlink(base_path('../assets/files/'.$data->file));
            }

        }

        $data->delete();

        
        //--- Logic Section Ends

        //--- Redirect Section
        if($data->type == 'Lesson'){
            $msg = __('Lesson Deleted Successfully.');
        }else{
            $msg = __('Quiz Deleted Successfully.');
        }
        return redirect()->route('admin-course-curriculam',$data->section->course_id)->with('success',$msg);

        //--- Redirect Section Ends

    }

    //*** POST Request
    public function sectionUpdate(Request $request, $id)
    {
        //--- Logic Section
        $crs = Course::find($id);
        $input = $request->all();
        $section_id = $request->section_id;
        $ck = $crs->sections()->where('id','!=',$section_id)->where('title',$input['title'])->count();
        $data = Section::find($section_id);

        if($ck == 1){
            return response()->json(array('errors' => [ 0 => __('This Title Already Exists.') ]));
        }else{
            $data->update($input);
        }
        //--- Logic Section Ends

        //--- Redirect Section
        $msg = __('Section Updated Successfully.');
        return response()->json($msg);
        //--- Redirect Section Ends

    }

    //*** POST Request
    public function sectionDelete($id)
    {
        //--- Logic Section

        $data = Section::find($id);
        $data->delete();

        //--- Logic Section Ends

        //--- Redirect Section

        $msg = __('Section Deleted Successfully.');
        return redirect()->route('admin-course-curriculam',$data->course_id)->with('success',$msg);

        //--- Redirect Section Ends

    }
}
