<?php

namespace App\Http\Controllers\AcademicManager;

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

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

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

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

    public function list(Request $request)
    {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $roles = Role::pluck('name', 'name')->all();

        return view('subjects.create', compact('roles'));
    }

    /**
     * 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_subjects',
            // 'meta_title'       => 'required',
            // 'meta_keywords'    => 'required',
            // 'open_graph_image' => 'required',
            // 'meta_description' => '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']);

        if ($request->hasFile('image')) {
            $path          = 'subjects/' . 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          = 'subjects/' . 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               = LmsSubject::create($data);

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

        return redirect()->route('subjects.index')
            ->with('success', 'Subject 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 = LmsSubject::find($id);

        return view('subjects.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_subjects,title,' . $id
            // 'image'            => 'required',
            // 'meta_title'       => 'required',
            // 'meta_keywords'    => 'required',
            // 'open_graph_image' => 'required',
            // 'meta_description' => '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']);
        $record = LmsSubject::find($id);

        if ($request->hasFile('image')) {
            $path          = 'subjects/' . 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          = 'subjects/' . 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['company_id'] = auth()->user()->company_id;
        $data               = LmsSubject::whereId($id)->update($data);
        $data               = LmsSubject::find($id);

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

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

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

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

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

        $Redirect = 'subjects';

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

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