<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\MasterSetting;
use App\Models\AdvanceSetting;

class MasterSettingsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:master-settings-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = MasterSetting::select([
                'master_settings.id',
                'master_settings.field',
                'master_settings.type',
                'master_settings.is_readonly',
                'master_settings.default_value',
                'master_settings.status',
                'master_settings.is_mandatory',
                'master_settings.select_options',
                'advance_settings.value',
            ])
            ->leftjoin('advance_settings', function($join) {
                $join->on('advance_settings.master_setting_id', 'master_settings.id')
                    ->whereNull('advance_settings.voucher_type_id')
                    ->whereNull('advance_settings.voucher_master_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('master_settings.field', 'like', '%'.$search_query.'%')
                            ->orWhere('master_settings.type', 'like', '%'.$search_query.'%')
                            ->orWhere('master_settings.default_value', 'like', '%'.$search_query.'%')
                            ->orWhere('master_settings.select_options', 'like', '%'.$search_query.'%');
                    })
                    ->paginate($sort_by);

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

            return view('master-settings.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('master-settings.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(), [
            'field'               => 'required',
            'type'                => 'required',
            'select_options'      => 'required_if:type,radio,selection',
        ]);

        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['status'] = 1;

        MasterSetting::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Setting has been created successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Setting has been 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)
    {
        $field = MasterSetting::select([
                'master_settings.*',
                'advance_settings.value',
            ])
            ->leftjoin('advance_settings', function($join) {
                $join->on('advance_settings.master_setting_id', 'master_settings.id')
                    ->whereNull('advance_settings.voucher_type_id')
                    ->whereNull('advance_settings.voucher_master_id');
            })
            ->where('master_settings.id', $id)
            ->first();

        return view('master-settings.edit', compact('field'));
    }

    /**
     * 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(), [
            'field'               => 'required',
            'type'                => 'required',
            'select_options'      => 'required_if:type,radio,checkbox,selection',
        ]);

        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',
            'value'
        ]);

        $field = MasterSetting::find($id);

        if (!$field) {
            return redirect()->route('master-settings.index')
                ->with('error','Master Setting not found!');
        }

        $field->update($data);

        AdvanceSetting::where('master_setting_id', $id)
                    ->whereNull('voucher_type_id')
                    ->whereNull('voucher_master_id')
                    ->update([
                        'value' => $request->value
                    ]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Master Setting has been updated successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Master Setting updated successfully');
    }

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

        if (!$field) {
            return redirect()->route('master-settings.index')
                ->with('error','Master Setting not found!');
        }

        $field->delete();

        AdvanceSetting::where('master_setting_id', $request->id)->delete();

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

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

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

    public function refreshSettings(Request $request)
    {
        $class = "MasterSettingsTableSeeder";

        \Artisan::call("db:seed", ['--class' => $class]);

        return redirect()->back()->with('success', 'Settings refreshed successfully.');
    }
}
