<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ShippingRisk;

class ShippingRiskController extends Controller
{
       function __construct()
    {
        $this->middleware('permission:shipping-risk-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {


        $data = ShippingRisk::orderBy('priority', 'ASC')->paginate(10);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = ShippingRisk::when(!empty($search_query), function ($query) use ($search_query) {
                            return $query->where('shipping-risk.name', 'like', '%'.$search_query.'%');
                        })
                        ->orderBy('priority', 'ASC')
                        ->paginate($sort_by);

            return view('shipping-risk.table', compact('data'));
        }
        else
        {
            return view('shipping-risk.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = ShippingRisk::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('shipping-risk.create', compact('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(), [
            'name' => 'required|unique:shipping_risks'
        ]);

        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['code'] = strtoupper($data['code']);

        $quality = ShippingRisk::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Shipping Risk created successfully',
                'data'    => $quality
            ]);
        }
        return redirect()->route('shipping-risk.index')
            ->with('success','Shipping Risk 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)
    {
        $type = ShippingRisk::find($id);

        return view('shipping-risk.edit',compact('type'));
    }

    /**
     * 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(), [
            'name' => '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'
        ]);
        $data['code'] = strtoupper($data['code']);


        $type = ShippingRisk::find($id);

        if (!$type) {
            return redirect()->route('shipping-risk.index')
                ->with('error','Shipping Risk not found!');
        }

        $type->update($data);

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

        return redirect()->route('shipping-risk.index')
            ->with('success','Shipping Risk updated successfully');
    }

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

        $type->delete();

        $Redirect = 'shipping-risk';

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

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

