<?php

namespace App\Http\Controllers\Catalogs;

use App\Models\Catalogs\Station;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Catalogs\TransportType;
use Illuminate\Validation\Rule;

class StationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //Variables
        $limit = ($request->has('limit') ? $request->get('limit') : 100);

        //Consulta
        $results =Station::filter($request->all())->sortable('general')->paginate($limit);

        //Vista
        return view('catalogs.stations.index', compact('results'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $transport_types = TransportType::populateSelect()->get()->pluck('name_sat', 'id');
        return view('catalogs.stations.create', compact('transport_types'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //Validacion
        $this->validation($request);
        $this->validate($request, [
            'code' => 'required|unique:tenant.stations',
        ], [
            'code.required' => __('catalogs/station.error_code'),
            'code.unique' => __('catalogs/station.error_code_unique'),
        ]);

        //Logica
        $request->merge(['created_uid' => \Auth::user()->id]);
        $request->merge(['updated_uid' => \Auth::user()->id]);
        $request->merge(['sort_order' => (int)$request->sort_order]);
        $request->merge(['status' => 1]); //Por default activo

        //Guardar
        //Registro principal
        $station= Station::create($request->input());

        //Mensaje
        flash(__('general.text_form_success_add'))->success();

        //Redireccion
        return redirect('/catalogs/stations');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Catalogs\Station  $station
     * @return \Illuminate\Http\Response
     */
    public function show(Station $station)
    {
        return redirect('/catalogs/stations');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Catalogs\Station  $station
     * @return \Illuminate\Http\Response
     */
    public function edit(Station $station)
    {
        $transport_types = TransportType::populateSelect()->get()->pluck('name_sat', 'id');

        return view('catalogs.stations.edit', compact('station', 'transport_types'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Catalogs\Station  $station
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Station $station)
    {
        //Validacion
        $this->validation($request);
        $this->validate($request, [
            'code' => [
                'required',
                Rule::unique('tenant.stations')->ignore($station->id)
            ],
        ], [
            'code.required' => __('catalogs/station.error_code'),
            'code.unique' => __('catalogs/station.error_code_unique'),
        ]);

        //Logica
        $request->merge(['updated_uid' => \Auth::user()->id]);
        $request->merge(['sort_order' => (int)$request->sort_order]);
        $request->merge(['status' => !empty($request->status) ? 1 : 0]);
        $station->fill($request->only([
            'updated_uid',
            'name',
            'code',
            'sort_order',
            'status',
            'transport_type_id',
            'nationality',
            'designator',
            'railway_line',
        ]));

        //Guardar
        //Registro principal
        $station->save();

        //Mensaje
        flash(__('general.text_form_success_edit'))->success();

        //Redireccion
        return redirect('/catalogs/stations');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Catalogs\Station  $station
     * @return \Illuminate\Http\Response
     */
    public function destroy(Station $station)
    {
        //Logica
        $station->updated_uid = \Auth::user()->id;
        $station->status = 0;
        $station->save();

        //Mensaje
        flash(__('general.text_form_success_delete'))->success();

        //Redireccion
        return redirect('/catalogs/stations');
    }

    public function validation(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
        ], [
            'name.*' => __('catalogs/station.error_name'),
        ]);
    }

    /**
     * Autoacompletar select2 de clientes
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function autocomplete(Request $request)
    {
        //Variables
        $term = $request->term;

        //Logica
        if ($request->ajax() && !empty($term)) {
            $tmp = Station::filter(['filter_search_select2' => $term])->active()->sortable('name')->limit(16)->get();
            $results = [];
            if ($tmp->isNotEmpty()) {
                foreach ($tmp as $result) {
                    $results[] = [
                        'id' => $result->id,
                        'text' => $result->text_select2,
                        'description' => $result->description_select2
                    ];
                }
            }
            return response()->json($results, 200);
        }

        return response()->json(['error' => __('general.error_general')], 422);
    }
}
