<?php

namespace App\Http\Controllers\AcademicManager;

use DB;
use Hash;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Models\LmsCourseLevel;
use Yajra\DataTables\DataTables;
use Spatie\Permission\Models\Role;
use App\Http\Controllers\Controller;

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

        $data = LmsCourseLevel::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('course-levels.table', compact('data'));
        } else {
            $data = $data->groupBy('id')
                ->orderBy('id','ASC')
                ->paginate(10);

            return view('course-levels.index',compact('data'));
        }
    }

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

    /**
     * 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(), [
            'title' => 'required|unique:lms_course_levels'
        ]);

        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 = LmsCourseLevel::create($data);

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

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

    /**
     * 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)
    {
        $data = LmsCourseLevel::find($id);

        return view('course-levels.edit', compact('data'));
    }

    /**
     * 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(), [
            'title' => 'required|unique:lms_course_levels,title,' . $id
        ]);

        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', '_method']);
        $data = LmsCourseLevel::whereId($id)->update($data);
        $data = LmsCourseLevel::find($id);

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

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

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

        $Redirect = 'Course Levels';

        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 = LmsCourseLevel::where('id', '=', $request->id)->update($data);

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