<?php

namespace App\Http\Controllers\System;

use App\Helpers\Helper;
use App\Http\Middleware\CheckSuperadmin;
use App\Http\Middleware\CheckSuperadminOrDistributor;
use App\Mail\SendActiveFolios;
use App\Models\Base\Folio;
use App\Models\System\SysSalesOrder;
use Hyn\Tenancy\Environment;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SysSalesOrderController extends Controller
{
    private $list_status = [];

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(CheckSuperadminOrDistributor::class);
        $this->list_status = [
            SysSalesOrder::PER_ACTIVE => __('system/sys_sales_order.text_status_per_active'),
            SysSalesOrder::ACTIVE => __('system/sys_sales_order.text_status_active'),
            SysSalesOrder::CANCELED => __('system/sys_sales_order.text_status_canceled'),
        ];
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //Variables
        $limit = ($request->has('limit') ? $request->get('limit') : 100);
        $list_status = $this->list_status;
        if (empty($request->filter_date_from)) {
            $request->request->add([
                'filter_date_from' => Helper::date(\Date::parse('first day of this month'))
            ]);
        }
        if (empty($request->filter_date_to)) {
            $request->request->add([
                'filter_date_to' => Helper::date(\Date::parse('last day of this month'))
            ]);
        }

        //Consulta
        if(\Auth::user()->distributor){
            $results = SysSalesOrder::filter($request->all())->userDistributor()->sortable(['created_at' => 'desc'])->paginate($limit);
        }else{
            $results = SysSalesOrder::filter($request->all())->sortable(['created_at' => 'desc'])->paginate($limit);
        }

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return redirect('/system/sales-orders');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        return redirect('/system/sales-orders');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\System\SysSalesOrder  $sales_order
     * @return \Illuminate\Http\Response
     */
    public function show(SysSalesOrder $sales_order)
    {
        return redirect('/system/sales-orders');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\System\SysSalesOrder  $sales_order
     * @return \Illuminate\Http\Response
     */
    public function edit(SysSalesOrder $sales_order)
    {
        return redirect('/system/sales-orders');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\System\SysSalesOrder  $sales_order
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, SysSalesOrder $sales_order)
    {
        return redirect('/system/sales-orders');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\System\SysSalesOrder  $sales_order
     * @return \Illuminate\Http\Response
     */
    public function destroy(SysSalesOrder $sales_order)
    {
        return redirect('/system/sales-orders');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\System\SysSalesOrder  $sys_sales_order
     * @return \Illuminate\Http\Response
     */
    public function activeFolios(SysSalesOrder $sys_sales_order)
    {
        //validacion el distribuidor del cliente debe tener los suficientes folios para asignarle
        if(!empty($sys_sales_order->sysCustomer->distributor)){
            $distributor = $sys_sales_order->sysCustomer->distributor;
            if($distributor->available_folio < $sys_sales_order->quantity_folio){
                //Mensaje
                flash(sprintf(__('auth/user.error_available_folio'),$distributor->name,$distributor->available_folio))->error();
                //Redireccion
                return redirect('/system/sys-sales-orders');
            }
        }

        //Logica
        if($sys_sales_order->status == SysSalesOrder::PER_ACTIVE) {
            $sys_sales_order->updated_uid = \Auth::user()->id;
            $sys_sales_order->activation_date = \Date::now();
            $sys_sales_order->status = SysSalesOrder::ACTIVE;
            $sys_sales_order->save();

            //Descuenta de los folios del distribuidor
            if(!empty($sys_sales_order->sysCustomer->distributor)) {
                $distributor = $sys_sales_order->sysCustomer->distributor;
                $distributor->available_folio -= $sys_sales_order->quantity_folio;
                $distributor->save();
            }

            //Activa folios en el entorno del cliente
            //Cambiamos entorno al del cliente creado
            $website = $sys_sales_order->sysCustomer->website ?? null;
            if(!empty($website) && !empty($sys_sales_order->folio_id)) {
                //Cambiamos entorno al del cliente
                app(Environment::class)->tenant($website);
                $folio = Folio::findOrFail($sys_sales_order->folio_id);
                if(!empty($folio)) {
                    $folio->updated_uid = \Auth::user()->id;
                    $folio->activation_date = \Date::now();
                    $folio->status = Folio::ACTIVE;
                    $folio->save();
                }

                //Correo de notificacion de activacion de folios
                \Mail::to($folio->createdUser)->send(new SendActiveFolios($folio));
                flash(__('general.text_form_success_add_active_sys_sales_order_notification'))->success();

                //Retornamos a entorno default
                app(Environment::class)->tenant(\Auth::user()->sysCustomer->website ?? null);
            }

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

        //Redireccion
        return redirect('/system/sys-sales-orders');
    }
}
