<?php

namespace App\Http\Controllers\AcademicManager;

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

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

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

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

    public function list(Request $request)
    {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = LmsCourseCategory::whereNull('parent_id')->get();
        $priority = LmsCourseCategory::max('sort_order');
        $priority = $priority != '' ? $priority : 0;

        return view('course-categories.create', compact('categories','priority'));
    }

    /**
     * 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_categories',
            'sort_order'       => 'required',
        ]);
        $customMessages = [
            'sort_order.required' => 'The priority 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']);
        $data['is_featured'] = isset($request->is_featured) ? $request->is_featured : 0;

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

            if ($response['status'] == true) {
                $data['image'] = $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          = 'course-categories/' . 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']);
            }
        }

        $data['company_id'] = auth()->user()->company_id;
        $data               = LmsCourseCategory::create($data);

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

        return redirect()->route('course-categories.index')
            ->with('success', 'Course Category 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       = LmsCourseCategory::find($id);
        $categories = LmsCourseCategory::whereNull('parent_id')->get();

        return view('course-categories.edit', compact('data', '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(), [
            'title'             => 'required|unique:lms_course_categories,title,' . $id,
            'sort_order'        => 'required',
        ]);
        $customMessages = [
            'sort_order.required' => 'The priority field is 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', 'image', 'open_graph_image', '_method']);
        $data['is_featured'] = isset($request->is_featured) ? $request->is_featured : 0;
        $data['company_id'] = auth()->user()->company_id;
        $record = LmsCourseCategory::find($id);

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

            if ($response['status'] == true) {
                $data['image'] = $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          = 'course-categories/' . 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']);
            }
        }

        $data = LmsCourseCategory::whereId($id)->update($data);
        $data = LmsCourseCategory::find($id);

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

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

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

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

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

        $Redirect = 'course-categories';

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

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