<?php

namespace App\Http\Controllers\AcademicManager;

use DB;
use Hash;
use App\Models\LmsTag;
use App\Models\Company;
use App\Models\LmsCourse;
use App\Models\LmsSubject;
use App\Models\LmsSection;
use App\Models\LmsClasses;
use App\Models\LmsLanguage;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Models\LmsAssignment;
use App\Models\LmsCourseType;
use App\Models\LmsVideoSource;
use App\Models\LmsCourseLevel;
use App\Models\LmsClassSection;
use Yajra\DataTables\DataTables;
use App\Models\LmsCourseCategory;
use Spatie\Permission\Models\Role;
use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\Website\Notice;

class CoursesController extends Controller
{
    // function __construct()
    // {
    //     $this->middleware('permission:courses-list|courses-create|courses-edit|courses-delete', ['only' => ['index', 'store']]);
    // }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // if (!$this->modulePermissionCheck('COURSES')) {
        //     abort(404);
        // }

        $data = LmsCourse::query();

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('title', 'like', '%'.$search_query.'%');
            })
            ->with('category')
            ->orderBy('id','ASC')
            ->groupBy('id')
            ->paginate($sort_by);

            return view('courses.table', compact('data'));
        } else {
            $data = $data->with('category')
                ->groupBy('id')
                ->orderBy('id','ASC')
                ->paginate(10);

            return view('courses.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $tags       = LmsTag::all()->where('status',1);
        $companies  = Company::all()->where('status',1);
        // $sections   = LmsSection::all();
        $classes    = LmsClasses::all()->where('status',1);
        $subjects   = LmsSubject::all()->where('status',1);
        $languages  = Language::all();
        $types      = LmsCourseType::all()->where('status',1);
        $levels     = LmsCourseLevel::all()->where('status',1);
        $categories = LmsCourseCategory::all()->where('status',1);

        return view('courses.create', compact(
            'tags',
            'types',
            'levels',
            'classes',
            // 'sections',
            'subjects',
            'companies',
            'languages',
            'categories',
        ));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'course_title'      => 'required|unique:lms_courses',
            'category_id'       => 'required',
            'course_type'       => 'required',
            'language_id'       => 'required',
            'subject_id'        => 'required',
            'course_level'      => 'required',
            'course_duration'   => 'required',
            'short_description' => 'required',
            'tags'              => 'required',
        ]);

        $customMessages = [
            'category_id.required' => 'The Category field is required.',
            'language_id.required' => 'The Language field is required.',
            'subject_id.required'  => 'The Subject field is required.',
        ];

        $validator->setCustomMessages($customMessages);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data               = $request->except(['_token', 'video_type', 'source']);
        $data['status']     = 1;
        $data['is_free']    = isset($request->is_free) ? $request->is_free : 0;
        $data['company_id'] = auth()->user()->company_id;
        $data['is_downloadable'] = isset($request->is_downloadable) ? $request->is_downloadable : 0;

        if ($request->hasFile('thumbnail')) {
            $path          = 'course-thumbnail/' . date('Y') . '/' . date('M');
            $response      = uploadImage($path, $request->thumbnail);

            if ($response['status'] == true) {
                $data['thumbnail'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }

                return redirect()->back()->with('error', $response['message']);
            }
        }

        if ($request->hasFile('open_graph_image')) {
            $path          = 'courses/' . date('Y') . '/' . date('M');
            $response      = uploadImage($path, $request->open_graph_image);

            if ($response['status'] == true) {
                $data['open_graph_image'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }

                return redirect()->back()->with('error', $response['message']);
            }
        }

        $source = '';
        if (isset($request->video_type) && $request->video_type == 'upload') {
            if ($request->hasFile('source')) {
                $path          = 'courses/' . date('Y') . '/' . date('M');
                $response      = uploadImage($path, $request->source);

                if ($response['status'] == true) {
                    $source = $response['file_name'];
                } else {
                    if ($request->ajax()) {
                        return response()->json([
                            'success' => false,
                            'message' => $response['message'],
                            'data'    => []
                        ]);
                    }

                    return redirect()->back()->with('error', $response['message']);
                }
            }
        } else {
            $source = $request->source;
        }

        if (isset($request->tags)) {
            $data['tags'] = implode(',', $request->tags);
        }

        $course = LmsCourse::create($data);
        LmsVideoSource::create([
            'course_id'  => $course->id,
            'video_type' => $request->video_type,
            'source'     => $source
        ]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Course created successfully',
                'data' => $course
            ]);
        }

        return redirect()->route('courses.index')
            ->with('success', 'Course created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $course = LmsCourse::select(
                        [
                            'lms_courses.id',
                            'lms_courses.course_title',
                            'lms_courses.course_duration',
                            'lms_courses.duration_type',
                            'lms_courses.short_description',
                            'lms_courses.thumbnail',
                            'lms_courses.course_price',
                            'lms_course_categories.title as category_name',
                            'lms_course_types.title as course_type',
                            'lms_classes.class_name',
                            'lms_subjects.title as subject_name'
                        ]
                        )
        ->leftJoin('lms_course_categories','lms_course_categories.id','=','lms_courses.category_id')
        ->leftJoin('lms_course_types','lms_course_types.id','=','lms_courses.course_type')
        ->leftJoin('lms_classes','lms_classes.id','=','lms_courses.class_id')
        ->leftJoin('lms_subjects','lms_subjects.id','=','lms_courses.subject_id')
        ->find($id);

        return view('courses.show', compact('course'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $tags       = LmsTag::all()->where('status',1);
        $companies  = Company::all()->where('status',1);
        // $sections   = LmsSection::all()->where('status',1);
        $classes    = LmsClasses::all()->where('status',1);
        $subjects   = LmsSubject::all()->where('status',1);
        $languages  = Language::all();
        $types      = LmsCourseType::all()->where('status',1);
        $levels     = LmsCourseLevel::all()->where('status',1);
        $categories = LmsCourseCategory::all()->where('status',1);
        $data       = LmsCourse::with('video_source')->find($id);
        $sections = LmsClassSection::select('lms_class_sections.*', 'lms_sections.section')
            ->leftJoin('lms_sections', 'lms_class_sections.academics_section_id', 'lms_sections.id')
            ->whereClassId($data->class_id)
            ->groupBy('lms_class_sections.id')
            ->get();

        return view('courses.edit', compact(
            'data',
            'tags',
            'types',
            'levels',
            'classes',
            'sections',
            'subjects',
            'companies',
            'languages',
            'categories',
        ));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'course_title'      => 'required|unique:lms_courses,course_title,' . $id,
            'category_id'       => 'required',
            'course_type'       => 'required',
            'language_id'       => 'required',
            'subject_id'        => 'required',
            'course_level'      => 'required',
            'course_duration'   => 'required',
            'short_description' => 'required',
            'tags'              => 'required',
        ]);

        $customMessages = [
            'category_id.required' => 'The Category field is required.',
            'language_id.required' => 'The Language field is required.',
            'subject_id.required'  => 'The Subject field is required.',
        ];

        $validator->setCustomMessages($customMessages);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data               = $request->except(['_token', 'video_type', 'source', '_method']);
        $data['is_free']    = isset($request->is_free) ? $request->is_free : 0;
        $data['company_id'] = auth()->user()->company_id;
        $data['is_downloadable'] = isset($request->is_downloadable) ? $request->is_downloadable : 0;

        $record = LmsCourse::with('video_source')->find($id);

        if ($request->hasFile('thumbnail')) {
            $path          = 'course-thumbnail/' . date('Y') . '/' . date('M');
            $response      = uploadImage($path, $request->thumbnail, $record->thumbnail);

            if ($response['status'] == true) {
                $data['thumbnail'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }

                return redirect()->back()->with('error', $response['message']);
            }
        }

        if ($request->hasFile('open_graph_image')) {
            $path          = 'courses/' . date('Y') . '/' . date('M');
            $response      = uploadImage($path, $request->open_graph_image, $record->open_graph_image);

            if ($response['status'] == true) {
                $data['open_graph_image'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }

                return redirect()->back()->with('error', $response['message']);
            }
        }

        $source = '';
        if (isset($request->video_type) && $request->video_type == 'upload') {
            if ($request->hasFile('source')) {
                $path          = 'courses/' . date('Y') . '/' . date('M');

                if (isset($record->video_source)) {
                    $response = uploadImage($path, $request->source, $record->video_source->soruce);
                } else {
                    $response = uploadImage($path, $request->source);
                }

                if ($response['status'] == true) {
                    $source = $response['file_name'];
                } else {
                    if ($request->ajax()) {
                        return response()->json([
                            'success' => false,
                            'message' => $response['message'],
                            'data'    => []
                        ]);
                    }

                    return redirect()->back()->with('error', $response['message']);
                }
            }
        } else {
            $source = $request->source;
        }

        if (isset($request->tags)) {
            $data['tags'] = implode(',', $request->tags);
        }

        $course = LmsCourse::whereId($id)->update($data);
        LmsVideoSource::whereCourseId($id)->update([
            'course_id'  => $id,
            'video_type' => $request->video_type,
            'source'     => $source
        ]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Course updated successfully',
                'data' => $data
            ]);
        }
        return redirect()->route('courses.index')
            ->with('success', 'Course updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = LmsCourse::find($request->id);
        $video = LmsVideoSource::whereCourseId($data->course_id);

        if ($data->thumbnail != '') {
            deleteImage($data->thumbnail);
        }

        if ($data->open_graph_image != '') {
            deleteImage($data->open_graph_image);
        }

        if (isset($video->video_type) && $video->video_type == 'upload') {
            deleteImage($video->source);
        }

        LmsCourse::find($request->id)->delete();
        LmsVideoSource::whereCourseId($data->course_id)->delete();

        $Redirect = 'courses';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }


    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data = array('status' => $request->status);
            $Update = LmsCourse::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Course status successfully change'],
                    'data' => [
                        'redirect' => '/courses/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function courseAssignments(Request $request)
    {
        $data = LmsAssignment::query();

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('title', 'like', '%'.$search_query.'%');
            })
            ->orderBy('id','ASC')
            ->groupBy('id')
            ->paginate($sort_by);

            return view('assignments.table', compact('data'));
        } else {
            $data = $data->groupBy('id')
                ->orderBy('id','ASC')
                ->paginate(10);

            return view('assignments.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function createAssignment()
    {
        return view('assignments.create');
    }

    public function storeAssignment(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'title'           => 'required',
            'deadline'        => 'required',
            'total_marks'     => 'required',
            'passing_marks'   => 'required',
            'attachment_file' => 'required',
            'course_id'       => 'required'
        ]);

        $customMessages = [
            'course_id.required' => 'The Course ID is required.'
        ];

        $validator->setCustomMessages($customMessages);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data               = $request->except(['_token']);
        $data['is_free']    = isset($request->is_free) ? $request->is_free : 0;

        if ($request->hasFile('attachment_file')) {
            $path          = 'assignments-attachments/' . date('Y') . '/' . date('M');
            $response      = uploadImage($path, $request->attachment_file);

            if ($response['status'] == true) {
                $data['attachment_file'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }

                return redirect()->back()->with('error', $response['message']);
            }
        }

        $data = LmsAssignment::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Assignment created successfully',
                'data' => $data
            ]);
        }

        return redirect()->back()->with('success', 'Assignment created successfully');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function editAssignment($id)
    {
        $data = LmsAssignment::find($id);

        return view('assignments.edit', compact('data'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function courseDestroy(Request $request)
    {
        $data = LmsAssignment::find($request->id);

        if ($data->attachment_file != '') {
            deleteImage($data->attachment_file);
        }

        LmsAssignment::find($request->id)->delete();

        $Redirect = 'assignments';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function getSections(Request $request)
    {
        if (isset($request->class) && $request->class != '') {
            $data = LmsClassSection::select('lms_class_sections.*', 'lms_sections.section')
                ->leftJoin('lms_sections', 'lms_class_sections.academics_section_id', 'lms_sections.id')
                ->whereClassId($request->class)
                ->groupBy('lms_class_sections.id')
                ->get();

            return response()->json([
                'success' => true,
                'message' => 'Sections are retrived successfully.',
                'data'    => $data
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Class ID not found in parameters!',
                'data' => []
            ]);
        }
    }

    public function courseNotice($course_id)
    {
        $notices = Notice::where('course_id',$course_id)->get();

        return view('courses.notice-table',compact('notices','course_id'));
    }
}
