<?php

namespace App\Http\Controllers\Shop;

use App\Http\Middleware\CheckSuperadmin;
use App\Http\Middleware\CheckSuperadminOrDistributor;
use App\Models\Catalogs\Tax;
use App\Models\Shop\ShopProduct;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;

class ShopProductController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(CheckSuperadmin::class)->except(['getShopProduct']);
        $this->middleware(CheckSuperadminOrDistributor::class)->only(['getShopProduct']);
    }

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

        //Vista
        return view('shop.shop_products.index', compact('results'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $taxes = Tax::populateSelect()->pluck('name', 'id');
        return view('shop.shop_products.create', compact('taxes'));
    }

    /**
     * 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' => 'nullable|unique:system.shop_products',
        ], [
            'code.unique' => __('shop/shop_product.error_code_unique'),
        ]);

        \DB::connection('tenant')->beginTransaction();
        try {
            //Logica
            $request->merge(['created_uid' => \Auth::user()->id]);
            $request->merge(['updated_uid' => \Auth::user()->id]);
            $request->merge(['price' => (double)$request->price]);
            $request->merge(['price_distributor' => (double)$request->price_distributor]);
            $request->merge(['quantity_folio' => (int)$request->quantity_folio]);
            $request->merge(['top' => !empty($request->top) ? 1 : 0]);
            $request->merge(['sort_order' => (int)$request->sort_order]);
            $request->merge(['status' => !empty($request->status) ? 1 : 0]);

            //Guardar
            //Registro principal
            $shop_product = ShopProduct::create($request->input());

            //Impuestos
            if (!empty($request->taxes)) {
                $shop_product->taxes()->sync($request->taxes);
            } else {
                $shop_product->taxes()->sync([]);
            }

            \DB::connection('tenant')->commit();

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

            //Redireccion
            return redirect('/shop/shop-products');
        } catch (\Exception $e) {
            \DB::connection('tenant')->rollback();
            flash($e->getMessage())->error();
            return back()->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Shop\ShopProduct  $shop_product
     * @return \Illuminate\Http\Response
     */
    public function show(ShopProduct $shop_product)
    {
        return redirect('/shop/shop-products');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Shop\ShopProduct  $shop_product
     * @return \Illuminate\Http\Response
     */
    public function edit(ShopProduct $shop_product)
    {
        $taxes = Tax::populateSelect()->pluck('name', 'id');
        return view('shop.shop_products.edit', compact('shop_product', 'taxes'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Shop\ShopProduct  $shop_product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, ShopProduct $shop_product)
    {
        //Validacion
        $this->validation($request);
        $this->validate($request, [
            'code' => [
                'nullable',
                Rule::unique('system.shop_products')->ignore($shop_product->id)
            ],
        ], [
            'code.unique' => __('shop/shop_product.error_code_unique'),
        ]);

        \DB::connection('tenant')->beginTransaction();
        try {
            //Logica
            $request->merge(['updated_uid' => \Auth::user()->id]);
            $request->merge(['price' => (double)$request->price]);
            $request->merge(['price_distributor' => (double)$request->price_distributor]);
            $request->merge(['quantity_folio' => (int)$request->quantity_folio]);
            $request->merge(['top' => !empty($request->top) ? 1 : 0]);
            $request->merge(['sort_order' => (int)$request->sort_order]);
            $request->merge(['status' => !empty($request->status) ? 1 : 0]);
            $shop_product->fill($request->only([
                'updated_uid',
                'name',
                'code',
                'description',
                'price',
                'quantity_folio',
                'top',
                'sort_order',
                'status',
                'price_distributor',
            ]));

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

            //Impuestos
            if (!empty($request->taxes)) {
                $shop_product->taxes()->sync($request->taxes);
            } else {
                $shop_product->taxes()->sync([]);
            }

            \DB::connection('tenant')->commit();

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

            //Redireccion
            return redirect('/shop/shop-products');
        } catch (\Exception $e) {
            \DB::connection('tenant')->rollback();
            flash($e->getMessage())->error();
            return back()->withInput();
        }
    }

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

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

        //Redireccion
        return redirect('/shop/shop-products');
    }

    /**
     * Validacion de formulario
     *
     * @param Request $request
     */
    public function validation(Request $request)
    {
        $this->validate($request, [
            'description' => 'required',
        ], [
            'description.*' => __('shop/shop_product.error_description'),
        ]);
    }

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

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

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