<?php

namespace App\Http\Controllers\System;

use App\Http\Middleware\CheckSuperadminOrDistributor;
use App\Models\Auth\User;
use App\Models\Shop\ShopProduct;
use App\Models\System\SysListPriceDistributor;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SysListPriceDistributorController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(CheckSuperadminOrDistributor::class);
    }

    /**
     * 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
        //Filtro solo los clientes del distribuidor
        if(\Auth::user()->distributor){
            $results = SysListPriceDistributor::filter($request->all())->userDistributor()->sortable('name')->paginate($limit);
        }else{
            $results = SysListPriceDistributor::filter($request->all())->sortable('name')->paginate($limit);
        }

        //Vista
        return view('system.sys_list_price_distributors.index', compact('results'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $distributors = User::distributor()->active()->pluck('name', 'id');
        $shop_products = ShopProduct::populateSelect()->pluck('description', 'id');
        return view('system.sys_list_price_distributors.create',compact('shop_products','distributors'));
    }

    /**
     * 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(['price' => (double)$request->price]);
        $request->merge(['sort_order' => (int)$request->sort_order]);
        $request->merge(['status' => !empty($request->status) ? 1 : 0]);
        if(\Auth::user()->distributor){
            $request->merge(['distributor_id' => \Auth::user()->id]);
        }

        //Guardar
        //Registro principal
        $list_price_distributor = SysListPriceDistributor::updateOrCreate(
            [
                'shop_product_id' => $request->shop_product_id,
                'distributor_id' => $request->distributor_id
            ],
            $request->input()
        );

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

        //Redireccion
        return redirect('/system/sys-list-price-distributors');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\System\SysListPriceDistributor  $sys_list_price_distributor
     * @return \Illuminate\Http\Response
     */
    public function show(SysListPriceDistributor $sys_list_price_distributor)
    {
        return redirect('/system/sys-list-price-distributors');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\System\SysListPriceDistributor  $sys_list_price_distributor
     * @return \Illuminate\Http\Response
     */
    public function edit(SysListPriceDistributor $sys_list_price_distributor)
    {
        $distributors = User::distributor()->active()->pluck('name', 'id');
        $shop_products = ShopProduct::populateSelect()->pluck('description', 'id');
        return view('system.sys_list_price_distributors.edit',compact('sys_list_price_distributor','shop_products','distributors'));
    }

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

        //Logica
        $request->merge(['created_uid' => \Auth::user()->id]);
        $request->merge(['updated_uid' => \Auth::user()->id]);
        $request->merge(['price' => (double)$request->price]);
        $request->merge(['sort_order' => (int)$request->sort_order]);
        $request->merge(['status' => !empty($request->status) ? 1 : 0]);
        if(\Auth::user()->distributor){
            $request->merge(['distributor_id' => \Auth::user()->id]);
        }

        $sys_list_price_distributor->fill($request->only([
            'updated_uid',
            'price',
        ]));

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

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

        //Redireccion
        return redirect('/system/sys-list-price-distributors');
    }

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

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

        //Redireccion
        return redirect('/system/sys-list-price-distributors');
    }

    /**
     * Validacion de formulario
     *
     * @param Request $request
     */
    public function validation(Request $request)
    {
        //Fix
        $request->merge(['base_price' => (double)$request->base_price]);
        $request->merge(['price' => (double)$request->price]);

        $this->validate($request, [
            'shop_product_id' => 'required|string',
            'price' => 'numeric|gt:base_price',
        ], [
            'shop_product_id.*' => __('system/sys_list_price_distributor.error_shop_product_id'),
            'price.*' => __('system/sys_list_price_distributor.error_price'),
        ]);

        if(\Auth::user()->superadmin){
            $this->validate($request, [
                'distributor_id' => 'required|string',
            ], [
                'distributor_id.*' => __('system/sys_list_price_distributor.error_distributor_id'),
            ]);
        }
    }
}
