<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TransportationMode;
use App\Models\TaxMaster;

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

        $data = TransportationMode::select(
            'tax_masters.name as tax',
            'transportation_modes.*')
        ->leftJoin('tax_masters','tax_masters.id','transportation_modes.tax_slab_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('transportation_modes.name', 'like', '%'.$search_query.'%');
                        })
                        ->orderBy('priority', 'ASC')
                        ->paginate($sort_by);

            return view('transportation-mode.table', compact('data'));
        }
        else
        {  
            $data   = $data->orderBy('priority', 'ASC')->paginate(10);

            return view('transportation-mode.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = TransportationMode::max('priority');
        $priority = $priority != '' ? $priority : 0;
        
        $taxname = TaxMaster::select('id','name')->get();
        return view('transportation-mode.create', compact('priority','taxname'));
    }

    /**
     * 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',
            'code' => 'required|unique:transportation_modes',
        ]);

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

        $default_check = TransportationMode::where(['is_default' => '1','status' => '1'])->first();

        if (!$default_check) {
            $data['is_default'] = '1';
        }
        $quality = TransportationMode::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Transportation Mode created successfully',
                'data'    => $quality
            ]);
        }
        return redirect()->route('transportation-mode.index')
            ->with('success','Transportation Mode 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)
    { 
      $taxname = TaxMaster::select('id','name')->get();

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

        return view('transportation-mode.edit',compact('type','taxname'));
    }

    /**
     * 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',
            'code' => 'required|unique:transportation_modes,name,'.$id,
        ]);

        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 = TransportationMode::find($id);

        if (!$type) {
            return redirect()->route('transportation-mode.index')
                ->with('error','Transportation Mode not found!');
        }

        $type->update($data);

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

        return redirect()->route('transportation-mode.index')
            ->with('success','Transportation Mode updated successfully');
    }

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

        if ($account->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $account->delete();

        $Redirect = 'transportation-mode';

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

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

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = TransportationMode::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default transportation mode!'],
                    'data'    => []
                ]);
            }

            $Update = TransportationMode::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Transportation Mode default status successfully changed.'],
                    'data'=>[
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }


}
