<?php

namespace App\Http\Controllers;

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

class SemestersController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $semesters = Semester::leftJoin('lms_courses', 'lms_courses.id', '=', 'semesters.course_id')
        ->select(
            'semesters.id as id',
            'semesters.name as name',
            'semesters.course_id as course_id',
            'semesters.priority as priority',
            'semesters.is_default as is_default',
            'semesters.status as status',
            'semesters.created_by as created_by',
            'lms_courses.course_title as course_title',
        )
        ->orderBy('semesters.priority', 'ASC');

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

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

            return view('semesters.table', compact('semesters'));
        } else {
            $semesters = $semesters->paginate(10);

            return view('semesters.index', compact('semesters'));
        }
            // dd($semesters);
        // return view('semesters.table', compact('semesters'));
    }

    /**
     * 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)
    {
        $semesters = Semester::findOrFail($id);
        $courses   = LmsCourse::all();

        return view('semesters.edit', compact('semesters', 'courses'));
    }

    /**
     * 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)
    {
        $semesters = Semester::findOrFail($id);
        $semesters->delete();

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

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

    public function createSemesters()
    {
       $semesters = Semester::all();
       $courses   = LmsCourse::all();
       $priority  = Semester::max('priority');
       $priority  = $priority != '' ? $priority : 0;

        return view('semesters.create', compact('semesters' , 'priority' , 'courses'));
    } 

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

        if ($validator->fails()) {

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

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

        return response()->json([
            'success' => true,
            'message' => 'Semester Created successfully',
        ]);

        // return response()->json([
        //     'success'  => true,
        //     'message'  => 'Semester Created successfully',
        //     'data'     => [
        //         'redirect' => 'semesters.index', 
        //     ]
        // ]);
    }

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

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

        $semesters = Semester::findOrFail($id);
        $semesters->update($request->all());

        return response()->json([
            'success'  => true,
            'message'  => 'Semesterupdated successfully',
            'data'     => [
                'redirect' => 'semesters.index', 
            ]
        ]);
    }

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

            if($update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Semester status successfully change'],
                    'data'=>[
                       'redirect'=>'',
                       '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 = Semester::where('id', '=', $request->id)->update($data);

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