<?php

namespace App\Http\Controllers;

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

class StatesController 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 = State::select([
            'id',
            'name',
            'country_id',
            'status',
        ])->with('getCountry');

        if ($request->ajax()) {
            $sort_by        = $request->get('sortby') ?? 10;
            $sort_type      = $request->get('sorttype');
            $search_query   = $request->get('query');
            $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_country), function ($query) use ($search_country) {
                    return $query->where('country_id', 'like', '%' . $search_country . '%');
                })
                ->orderBy('name', 'ASC')
                ->paginate($sort_by);

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

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

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

    /**
     * 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:states',
            'country_id' => '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'
        ]);
        $data = State::create($data);


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

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

    /**
     * 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:states,name,' . $id,
            'country_id' => '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 = State::whereId($id)->update($data);
        $data = State::find($id);

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

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

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

        $Redirect = 'states';

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

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

    public function searchCountries(Request $request)
    {
        $searchTerm = $request->search_text;
        $results    = Country::select(['countries.id','countries.name'])
                    ->where('countries.name', 'LIKE', '%' . $searchTerm . '%')
                    ->get();

        return response()->json(['result' => $results, 'status' => true]);
    }


    public function searchStates(Request $request)
    {
        $searchTerm = $request->search_text;
        $country_id = $request->country;
        $results    = State::select(['states.id','states.name'])
                    ->where('states.name', 'LIKE', '%' . $searchTerm . '%')
                    ->when(!empty($country_id), function ($query) use ($country_id) {
                        return $query->where('states.country_id', $country_id );
                    })
                    ->get();

        return response()->json(['result' => $results, 'status' => true]);
    }
}
