<?php

namespace App\Http\Controllers;

use App\Models\LmsCourse;
use Illuminate\Http\Request;
use App\Models\StudyMaterialType;
use App\Models\Semester;
use App\Models\StudyMaterial;
use Illuminate\Support\Facades\Auth;

class StudyMaterialTypesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $study_material_types = StudyMaterialType::select(
            'study_material_types.id as id',
            'study_material_types.name as name',
            'study_material_types.priority as priority',
            'study_material_types.is_default as is_default',
            'study_material_types.status as status',
        )->orderBy('study_material_types.priority', 'ASC');

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

            $study_material_types = $study_material_types->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('study_material_types.name', 'like', '%'. $search_query.'%');

            })->paginate($sort_by);

            return view('study-material-types.table', compact('study_material_types'));
        } else {
            $study_material_types = $study_material_types->paginate(10);

            return view('study-material-types.index', compact('study_material_types'));
        }
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $study_material_types = StudyMaterialType::findOrFail($id);

        return view('study-material-types.edit', compact('study_material_types'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $study_material_types = StudyMaterialType::findOrFail($id);
        $study_material_types->delete();

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

    public function createStudyMaterialTypes()
    {
       $study_material_types = StudyMaterialType::all();

       $priority = StudyMaterialType::max('priority');
       $priority = $priority != '' ? $priority : 0;

        return view('study-material-types.create', compact('study_material_types' , 'priority'));
    } 

    public function storeStudyMaterialTypes(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name'     => 'required',
            'priority' => 'required',
        ]);

        if ($validator->fails()) {

            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                    'redirect' => 'study-material-types.index'],
            ]);
        }

        $study_material_types = StudyMaterialType::create([
            'name'       => $request->name,
            'priority'   => $request->priority,
            'created_by' => Auth::user()->id,
        ]);

        return response()->json([
            'success'  => true,
            'message'  => 'Study Material Created successfully',
            'data'     => [
                'redirect' => 'study-material-types.index', 
            ]
        ]);
    }

    public function updateStudyMaterialTypes(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name'     => 'required',
            'priority' => 'required',
        ]);

        if ($validator->fails()) {
           return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                    'redirect' => 'study-material-types.index'],
            ]);
        }

        $study_material_types = StudyMaterialType::findOrFail($id);
        $study_material_types->update($request->all());

        return response()->json([
            'success'  => true,
            'message'  => 'Study Material updated successfully',
            'data'     => [
                'redirect' => 'study-material-types.index', 
            ]
        ]);
    }

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

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

    public function isDefaultchangeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $update = StudyMaterialType::where('id', '=', $request->id)->update($data);

            if($update){
                return response()->json([
                    'success' =>true,
                    'message' =>['Study Material is Default status successfully change'],
                    'data'    =>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success' =>false,
                   'message' =>['Error for change status'],
                   'data'    =>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }


    public function allData(Request $request,$course_id)
    {
        $study_material_types = StudyMaterialType::select(
            'study_material_types.id as id',
            'study_material_types.name as name',
            'study_material_types.priority as priority',
            'study_material_types.is_default as is_default',
            'study_material_types.status as status',
        )->orderBy('study_material_types.priority', 'ASC')->get();

      
            return view('study-material-types.all-data', compact('study_material_types','course_id'));
    }

    public function typeDetails(Request $request,$course_id,$material_type_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($course_id);
        
    // return view('study-material-types.show',$data);
$materialType = StudyMaterialType::find($material_type_id);

    $study_materials = StudyMaterial::leftjoin('study_material_types' , 'study_materials.material_type_id',  '=' , 'study_material_types.id' )
        ->leftjoin('lms_classes' , 'study_materials.semester_id',  '=' , 'lms_classes.id' )
        ->select(
            'study_materials.id as id',
            'study_materials.title as title',
            'study_materials.file_url as file_url',
            'study_materials.description as description',
            'study_materials.priority as priority',
            'study_materials.is_default as is_default',
            'study_materials.status as status',
            'study_materials.created_by as created_by',
            'study_material_types.name as study_material_type_name',
            'lms_classes.class_name as semester_name',
        )->orderBy('study_materials.priority', 'ASC')
        ->where('study_materials.course_id',$course_id)
        ->where('study_materials.material_type_id',$material_type_id);

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

            $study_materials = $study_materials->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('study_materials.title', 'like', '%'.$search_query.'%')
                            ->orWhere('study_materials.description', 'like', '%'.$search_query.'%')
                            ->orWhere('study_material_types.name', 'like', '%'.$search_query.'%')
                            ->orWhere('lms_classes.class_name', 'like', '%'.$search_query.'%');
            })->paginate($sort_by);

            return view('study-materials.table', compact('study_materials','course_id','material_type_id','course'));
        } else {
            $study_materials = $study_materials->paginate(10);

            return view('study-materials.index', compact('study_materials','course_id','material_type_id','course','materialType'));
        }

    }

}
