<?php

namespace App\Http\Controllers;

use App\Models\City;
use App\Models\State;
use Illuminate\Http\Request;

class CityController extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:employee-type-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = City::select([
            'cities.id',
            'cities.name',
            'cities.state_id',
            'cities.status',
            'countries.name as country_name'
        ])
        ->leftJoin('states', 'cities.state_id', '=', 'states.id')
        ->leftJoin('countries', 'states.country_id', '=', 'countries.id');

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

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('name', 'like', '%'.$search_query.'%');
            })
            ->when(!empty($search_state), function ($query) use ($search_state) {
                return $query->where('state_id', $search_state );
            })
            ->when(!empty($search_country), function ($query) use ($search_country) {
                return $query->where('states.country_id', $search_country );
            })
            ->orderBy('cities.name','ASC')
            ->paginate($sort_by);

            return view('cities.table', compact('data'));
        } else {
            $data = $data->groupBy('id')
                ->orderBy('name','ASC')
                ->paginate(10);

            return view('cities.index',compact('data'));
        }
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $states = State::select('id','name')
        ->orderBy('states.name','asc')
        ->get();

        return view('cities.create',compact('states'));
    }

    /**
     * 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:cities'
        ]);

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


        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'City created successfully',
                'data'    => $data
            ]);
        }
        return redirect()->route('cities.index')
            ->with('success', 'City 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)
    {
        $states = State::select(['id','name'])->get();
        $data   = City::find($id);

        return view('cities.edit', compact('data','states'));
    }

    /**
     * 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|unique:cities,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 = City::whereId($id)->update($data);
        $data = City::find($id);

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

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

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

        $Redirect = 'cities';

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

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