<?php

namespace App\Http\Controllers\AcademicManager;

use DB;
use Hash;
use App\Models\LmsSection;
use App\Models\LmsClasses;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Models\LmsClassSection;
use Yajra\DataTables\DataTables;
use Spatie\Permission\Models\Role;
use App\Http\Controllers\Controller;
use App\Models\LmsCourse;

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

        $data = LmsClasses::select(
            'lms_classes.*','lms_courses.course_title',
            \DB::raw("GROUP_CONCAT(lms_sections.section) AS sections")
        )
            ->leftJoin('lms_class_sections', 'lms_class_sections.class_id', 'lms_classes.id')
            ->leftJoin('lms_sections', 'lms_class_sections.academics_section_id', 'lms_sections.id')
            ->leftJoin('lms_courses','lms_classes.course_id','lms_courses.id');

        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('class_name', 'like', '%'.$search_query.'%');
            })
            ->orderBy('priority','ASC')
            ->groupBy('lms_classes.id')
            ->paginate($sort_by);

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

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

    public function list(Request $request)
    {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $sections = LmsSection::all();
        $priority =  LmsClasses::max('priority');
        $coursers = LmsCourse::get(['course_title','id']);
        $priority = $priority != '' ? $priority : 0;

        return view('classes.create', compact('sections','priority','coursers'));
    }

    /**
     * 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(), [
            'class_name' => 'required|unique:lms_classes',
            'priority'   => 'required',
            'sections'   => 'required'
        ]);

        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', 'sections']);
        $data = LmsClasses::create($data);

        if (isset($request->sections)) {
            foreach ($request->sections as $key => $section) {
                LmsClassSection::create([
                    'class_id'             => $data->id,
                    'academics_section_id' => $section
                ]);
            }
        }

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

        return redirect()->route('classes.index')
            ->with('success', 'Class 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 = LmsClasses::find($id);
        $sections = LmsSection::all();
        $selectedSections = LmsClassSection::select(
            \DB::raw("GROUP_CONCAT(academics_section_id) AS sections")
        )->whereClassId($id)
        ->groupBy('class_id')
        ->first();
        $coursers = LmsCourse::select(['course_title','id'])->get();
        return view('classes.edit', compact('data', 'sections', 'selectedSections','coursers'));
    }

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

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

        if (isset($request->sections)) {
            LmsClassSection::whereClassId($id)->delete();
            foreach ($request->sections as $key => $section) {
                LmsClassSection::create([
                    'class_id'             => $data->id,
                    'academics_section_id' => $section
                ]);
            }
        }

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

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

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

        $Redirect = 'classes';

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

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