<?php

namespace App\Http\Controllers\Catalogs;

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

class DisabilityTypeController 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 = DisabilityType::filter($request->all())->sortable('general')->paginate($limit);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('catalogs.disability_types.create');
    }

    /**
     * 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.disability_types',
        ], [
            'code.required' => __('catalogs/disability_type.error_code'),
            'code.unique' => __('catalogs/disability_type.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
        $disability_type = DisabilityType::create($request->input());

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

        //Redireccion
        return redirect('/catalogs/disability-types');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Catalogs\DisabilityType  $disability_type
     * @return \Illuminate\Http\Response
     */
    public function show(DisabilityType $disability_type)
    {
        return redirect('/catalogs/disability-types');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Catalogs\DisabilityType  $disability_type
     * @return \Illuminate\Http\Response
     */
    public function edit(DisabilityType $disability_type)
    {
        return view('catalogs.disability_types.edit', compact('disability_type'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Catalogs\DisabilityType  $disability_type
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, DisabilityType $disability_type)
    {
        //Validacion
        $this->validation($request);
        $this->validate($request, [
            'code' => [
                'required',
                Rule::unique('tenant.disability_types')->ignore($disability_type->id)
            ],
        ], [
            'code.required' => __('catalogs/disability_type.error_code'),
            'code.unique' => __('catalogs/disability_type.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]);
        $disability_type->fill($request->only([
            'updated_uid',
            'name',
            'code',
            'sort_order',
            'status',
        ]));

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

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

        //Redireccion
        return redirect('/catalogs/disability-types');
    }

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

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

        //Redireccion
        return redirect('/catalogs/disability-types');
    }

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

    /**
     * Obtener registro
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDisabilityType(Request $request)
    {
        //Variables
        $id = $request->id;

        //Logica
        if ($request->ajax() && !empty($id)) {
            $disability_type = DisabilityType::findOrFail($id);
            return response()->json($disability_type, 200);
        }

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

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

        //Logica
        if ($request->ajax() && !empty($term)) {
            $tmp = DisabilityType::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->description_select2,
                        'description' => $result->description_select2
                    ];
                }
            }
            return response()->json($results, 200);
        }

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

    /**
     * Modal para buscar disability_types
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function modalSearch(Request $request)
    {
        //Variables
        $active_btn_select = (!empty($request->active_btn_select) ? $request->active_btn_select : '');
        $row_origin = (isset($request->row_origin) ? $request->row_origin : '');
        //En caso de estar vacio le asignamos un datos para mostrar los clientes con "a"
        $request->merge(['filter_search' => !empty($request->filter_search) ? $request->filter_search : '' ]);

        //Logica
        if ($request->ajax()) {
            $results = DisabilityType::filter($request->all())->active()->sortable('general')->limit(10)->get();

            //Busca cliente
            $html_disability_types = view('layouts.partials.disability_types.search',
                compact('results','active_btn_select','row_origin'))->render();

            //modal de buscar
            $html = view('layouts.partials.disability_types.modal_search',
                compact('html_disability_types','active_btn_select','row_origin'))->render();


            return response()->json(['html' => $html]);
        }

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

    /**
     * Modal para buscar disability_typeos
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function search(Request $request)
    {
        //Variables
        $active_btn_select = (!empty($request->active_btn_select) ? $request->active_btn_select : '');
        $row_origin = (isset($request->row_origin) ? $request->row_origin : '');
        //En caso de estar vacio le asignamos un datos para mostrar los clientes con "a"
        $request->merge(['filter_search' => !empty($request->filter_search) ? $request->filter_search : '' ]);

        //Logica
        if ($request->ajax()) {

            $results = DisabilityType::filter($request->all())->active()->sortable('general')->limit(10)->get();

            //Busca cliente
            $html = view('layouts.partials.disability_types.search',
                compact('results','active_btn_select','row_origin'))->render();

            return response()->json(['html' => $html]);
        }

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