<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Permission;
use App\Models\MenuModelPermission;
use Illuminate\Http\Request;
use App\Models\VoucherMaster;

class MenuModuleController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:modules-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $type = $request->get('type') ?? 'main';
        $data = MenuModelPermission::select(
                'menu_model_permissios.id',
                'menu_model_permissios.code',
                'menu_model_permissios.menu_name',
                'menu_model_permissios.priority',
                'menu_model_permissios.status',
                'menu_model_permissios.parent_id',
                'menu_model_permissios.icon',
                'menu_model_permissios.module_type',
            )
            ->when(($type == 'main'), function ($query) {
                return $query->whereNull('parent_id');
            })
            ->when(($type == 'sub'), function ($query) {
                return $query->whereNotNull('parent_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('menu_name', 'like', '%'.$search_query.'%');
                })
                ->paginate($sort_by);

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

        return view('menu-module.index',compact('data'));
      }
    }

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

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

    public function create()
    {
        $modules        = MenuModelPermission::where('parent_id', null)->get();
        $voucher_master = VoucherMaster::where('status', 1)->get();

        $priority = MenuModelPermission::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('menu-module.create', compact('modules','priority','voucher_master'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'menu_name'         => 'required|unique:menu_model_permissios',
            'priority'          => 'required|numeric',
            'code'              => 'required',
            // 'voucher_master_id' => 'required|numeric',
        ]);

        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'
        ]);
        $module = MenuModelPermission::create($data);

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $modules = MenuModelPermission::where('parent_id', null)->get();
        $voucher_master = VoucherMaster::where('status', 1)->get();

        $module = MenuModelPermission::find($id);

        return view('menu-module.edit',compact('module', 'modules', 'voucher_master'));
    }

    /**
     * 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(), [
            'menu_name' => 'required|unique:menu_model_permissios,menu_name,'.$id,
            'priority'  => 'required|numeric',
            'code'      => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $module = MenuModelPermission::find($id);

        if (!$module) {
            return redirect()->route('modules.index')
                ->with('error','Module not found!');
        }

        $module->update($data);

        return redirect()->route('modules.index')
            ->with('success','Module updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        Permission::where('module_id', $request->id)->delete();
        MenuModelPermission::find($request->id)->delete();

        $Redirect = 'modules';

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

    public function moduleInfo(Request $request,$id)
    {
        $module = MenuModelPermission::select('summernote','menu_name')->where('id', $id)->first();

        if (!$module) {
            return redirect()->route('modules.index')
                ->with('error','Module not found!');
        }

        return view('menu-module.information',compact('module','id'));
    }

    public function infoStore(Request $request,$id)
    {
        $module = MenuModelPermission::where('id', $id)->first();

        if (!$module) {
            return redirect()->route('modules.index')
                ->with('error','Module not found!');
        }
        $module->update(['summernote' => $request->summernote]);

        return redirect()->route('modules.index')
                ->with('success','Module Information stored successfully.');
    }

    public function helpText(Request $request,$id)
    {
        $module = MenuModelPermission::where('id', $id)->select('summernote')->first();

        if (!$module) {
            return response()->json([
                'success'=>false,
                'message'=>['Module not found!']
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Module help and support found.',
            'data'    => $module->summernote != ''? $module->summernote : '-'
        ]);
    }
}
