<?php

namespace App\Http\Controllers\Catalogs;

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('catalogs.dangerous_products.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',
        ], [
            'code.required' => __('catalogs/dangerous_product.error_code'),
        ]);

        //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
        $dangerous_product= DangerousProduct::create($request->input());

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

        //Redireccion
        return redirect('/catalogs/dangerous-products');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Catalogs\DangerousProduct  $dangerous_product
     * @return \Illuminate\Http\Response
     */
    public function show(DangerousProduct $dangerous_product)
    {
        return redirect('/catalogs/dangerous-products');
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Catalogs\DangerousProduct  $dangerous_product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, DangerousProduct $dangerous_product)
    {
        //Validacion
        $this->validation($request);
        $this->validate($request, [
            'code' => [
                'required',
            ],
        ], [
            'code.required' => __('catalogs/dangerous_product.error_code'),
        ]);

        //Logica
        $request->merge(['updated_uid' => \Auth::user()->id]);
        $request->merge(['sort_order' => (int)$request->sort_order]);
        $request->merge(['status' => !empty($request->status) ? 1 : 0]);
        $dangerous_product->fill($request->only([
            'updated_uid',
            'name',
            'code',
            'sort_order',
            'status',
            'class',
            'secondary',
            'tecnic_name'
        ]));

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

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

        //Redireccion
        return redirect('/catalogs/dangerous-products');
    }

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

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

        //Redireccion
        return redirect('/catalogs/dangerous-products');
    }

    public function validation(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
        ], [
            'name.*' => __('catalogs/dangerous_product.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 = DangerousProduct::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);
    }
}
