<?php

namespace App\Http\Controllers\Catalogs;

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


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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('catalogs.sat_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|unique:tenant.sat_products|max:8',
        ], [
            'code.required' => __('catalogs/sat_product.error_code'),
            'code.max' => __('catalogs/sat_product.error_code_max'),
            'code.unique' => __('catalogs/sat_product.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
        $sat_product= SatProduct::create($request->input());

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

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

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

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

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

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

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

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

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

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

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

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

        //Logica
        if ($request->ajax() && !empty($term)) {
            $tmp = SatProduct::filter(['filter_search_select2' => $term])->active()->sortable('code')->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 productos sat
     *
     * @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 = SatProduct::filter($request->all())->active()->sortable('code')->limit(10)->get();

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

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


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

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

    /**
     * Modal para buscar poductos sat
     *
     * @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 = SatProduct::filter($request->all())->active()->sortable('code')->limit(10)->get();

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

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

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