<?php

namespace App\Http\Controllers\Catalogs;

use App\Models\Catalogs\Tax;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\ValidationException;

class TaxController extends Controller
{
    private $list_factor = [];
    private $list_code = [];
    private $list_type = [];

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->list_factor = [
            Tax::TASA => __('catalogs/tax.text_factor_tasa'),
            Tax::CUOTA => __('catalogs/tax.text_factor_cuota'),
            Tax::EXENTO => __('catalogs/tax.text_factor_exento')
        ];

        $this->list_code = [
            Tax::ISR => __('catalogs/tax.text_code_isr'),
            Tax::IVA => __('catalogs/tax.text_code_iva'),
            Tax::IEPS => __('catalogs/tax.text_code_ieps')
        ];

        $this->list_type = [
            Tax::TRASLADO => __('catalogs/tax.text_type_traslado'),
            Tax::RETENCION => __('catalogs/tax.text_type_retencion'),
        ];
    }

    /**
     * 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 = Tax::filter($request->all())->sortable('general')->paginate($limit);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $list_factor = $this->list_factor;
        $list_code = $this->list_code;
        $list_type = $this->list_type;
        return view('catalogs.taxes.create',compact('list_factor', 'list_code', 'list_type'));
    }

    /**
     * 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);

        //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(['name' => str_replace(',', '',$request->name)]);
        $request->merge(['local_taxes' => !empty($request->local_taxes) ? 1 : 0]);
        $request->merge(['status' => 1]); //Por default activo

        //Guardar
        //Registro principal
        $tax = Tax::create($request->input());

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

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

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Catalogs\Tax  $tax
     * @return \Illuminate\Http\Response
     */
    public function edit(Tax $tax)
    {
        $list_factor = $this->list_factor;
        $list_code = $this->list_code;
        $list_type = $this->list_type;
        return view('catalogs.taxes.edit',compact('tax','list_factor', 'list_code', 'list_type'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Catalogs\Tax  $tax
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Tax $tax)
    {
        //Validacion
        $this->validation($request);

        //Logica
        $request->merge(['updated_uid' => \Auth::user()->id]);
        $request->merge(['name' => str_replace(',', '',$request->name)]);
        $request->merge(['sort_order' => (int)$request->sort_order]);
        $request->merge(['local_taxes' => !empty($request->local_taxes) ? 1 : 0]);
        $request->merge(['status' => !empty($request->status) ? 1 : 0]);
        $tax->fill($request->only([
            'updated_uid',
            'name',
            'code',
            'rate',
            'factor',
            'sort_order',
            'status',
            'local_taxes',
            'type'
        ]));

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

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

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

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

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

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

    /**
     * Validacion de formulario
     *
     * @param Request $request
     */
    public function validation(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'code' => 'nullable|max:3',
            'rate' => 'required|numeric',
            'factor' => 'required|string',
            'type' => 'required',
        ], [
            'name.*' => __('catalogs/tax.error_name'),
            'code.required' => __('catalogs/tax.error_code'),
            'code.max' => __('catalogs/tax.error_code_max'),
            'rate.*' => __('catalogs/tax.error_rate'),
            'factor.*' => __('catalogs/tax.error_factor'),
            'type.*' => __('catalogs/tax.error_type'),
        ]);

        $validator = \Validator::make([], []);

        if(empty($request->local_taxes) && empty($request->code)){
            $validator->after(function ($validator) {
                $validator->errors()->add('code', __('catalogs/tax.error_code'));
            });
        }

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }
    }
}
