<?php

namespace App\Http\Controllers\Base;

use App\Helpers\Helper;
use App\Http\Middleware\CheckDemo;
use App\Http\Middleware\CheckSuperadmin;
use App\Models\Base\BranchOffice;
use App\Models\Base\DocumentType;
use App\Models\Catalogs\CfdiType;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;

class DocumentTypeController extends Controller
{
    private $list_nature = [];

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(CheckSuperadmin::class,['only' => ['create','store','show','destroy']]);
        $this->middleware(CheckDemo::class,['only' => ['update']]);

        $this->list_nature = [
            DocumentType::NO_NATURE => __('base/document_type.text_no_nature'),
            DocumentType::DEBIT => __('base/document_type.text_debit'),
            DocumentType::CREDIT => __('base/document_type.text_credit'),
        ];
    }

    /**
     * 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
        if(!empty(setting('folios_per_branch_office'))){
            $results = DocumentType::filter($request->all())->whereNotNull('branch_office_id')->sortable('name')->paginate($limit);
        }else{
            $results = DocumentType::filter($request->all())->whereNull('branch_office_id')->sortable('name')->paginate($limit);
        }

        //Vista
        return view('base.document_types.index', compact('results'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $list_nature = $this->list_nature;
        $cfdi_types = CfdiType::populateSelect()->get()->pluck('name_sat', 'id');
        $branch_offices = BranchOffice::populateSelect()->pluck('name', 'id');

        return view('base.document_types.create',compact('list_nature','cfdi_types','branch_offices'));
    }

    /**
     * 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',
        ], [
            'code.required' => __('base/document_type.error_code'),
        ]);
        if(!empty(setting('folios_per_branch_office'))){
            $this->validate($request, [
                'branch_office_id' => 'required',
            ], [
                'branch_office_id.required' => __('base/document_type.error_branch_office_id'),
            ]);
        }

        //Logica
        $company = Helper::defaultCompany(); //Empresa
        $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
        $request->merge(['company_id' => $company->id]);

        //Guardar
        //Registro principal
        $document_type = DocumentType::create($request->input());

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

        //Redireccion
        return redirect('/base/document-types');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Base\DocumentType  $document_type
     * @return \Illuminate\Http\Response
     */
    public function show(DocumentType $document_type)
    {
        return redirect('/base/document-types');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Base\DocumentType  $document_type
     * @return \Illuminate\Http\Response
     */
    public function edit(DocumentType $document_type)
    {
        $list_nature = $this->list_nature;
        $cfdi_types = CfdiType::populateSelect()->get()->pluck('name_sat', 'id');
        $branch_offices = BranchOffice::populateSelect()->pluck('name', 'id');

        return view('base.document_types.edit', compact('document_type','list_nature','cfdi_types','branch_offices'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Base\DocumentType  $document_type
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, DocumentType $document_type)
    {
        //Validacion
        $this->validation($request);
        $this->validate($request, [
            'code' => [
                'required',
            ],
        ], [
            'code.required' => __('base/document_type.error_code'),
        ]);

        //Logica
        $request->merge(['updated_uid' => \Auth::user()->id]);
        $request->merge(['sort_order' => (int)$request->sort_order]);
        $request->merge(['status' => !empty($request->status) ? 1 : 0]);

        if(\Auth::user()->superadmin) {
            $document_type->fill($request->only([
                'updated_uid',
                'name',
                'code',
                'prefix',
                'current_number',
                'increment_number',
                'nature',
                'cfdi_type_id',
                'sort_order',
                'status',
            ]));
        }else{
            $document_type->fill($request->only([
                'updated_uid',
                'name',
                'prefix',
                'current_number',
                'increment_number',
                'sort_order',
            ]));
        }

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

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

        //Redireccion
        return redirect('/base/document-types');
    }

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

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

        //Redireccion
        return redirect('/base/document-types');
    }

    /**
     * Validacion de formulario
     *
     * @param Request $request
     */
    public function validation(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'prefix' => 'required|max:34',
            'current_number' => 'required|integer',
            'increment_number' => 'required|integer',
            'nature' => 'required',
        ], [
            'name.*' => __('base/document_type.error_name'),
            'prefix.*' => __('base/document_type.error_prefix'),
            'current_number.*' => __('base/document_type.error_current_number'),
            'increment_number.*' => __('base/document_type.error_increment_number'),
            'nature.*' => __('base/document_type.error_nature'),
        ]);
    }

    /**
     * Modal para alta de documentos por sucursal
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function modalCreatePerBranchOffice(Request $request)
    {
        //Variables

        //Logica
        if ($request->ajax()) {

            $branch_offices = BranchOffice::populateSelect()->pluck('name', 'id');
            $document_types = DocumentType::filter([])->sortable('sort_order')->whereNull('branch_office_id')->get();

            //modal de buscar
            $html = view('layouts.partials.document_types.modal_create_per_branch_office', compact('branch_offices', 'document_types'))->render();


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

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

    /**
     * Modal para alta de documentos por sucursal
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function createPerBranchOffice(Request $request)
    {
        //Validacion de sucursal
        if(empty($request->branch_office_id)){
            flash(__('base/document_type.error_branch_office_id'))->error();
            return redirect()->route('document-types.index');
        }else{
            //Valida que no este registrado los folios para esta sucursal
            $document_type = DocumentType::filter([])->where('branch_office_id', '=', $request->branch_office_id)->first();
            if(!empty($document_type)){
                flash(__('base/document_type.error_branch_office_id_exists'))->error();
                return redirect()->route('document-types.index');
            }
        }

        \DB::connection('tenant')->beginTransaction();
        try {

            //Logica
            $company = Helper::defaultCompany(); //Empresa

            //Recorre arreglo y guarda los datos
            if (!empty($request->item)) {
                foreach ($request->item as $key => $item) {
                    $document_type_base = DocumentType::findOrFail($item['id']);
                    $document_type = DocumentType::create([
                        'created_uid' => \Auth::user()->id,
                        'updated_uid' => \Auth::user()->id,
                        'name' => $item['name'],
                        'code' => $document_type_base->code,
                        'prefix' => $item['prefix'],
                        'current_number' => (int)$item['current_number'] - 1,
                        'increment_number' => $document_type_base->increment_number,
                        'nature' => $document_type_base->nature,
                        'cfdi_type_id' => $document_type_base->cfdi_type_id,
                        'sort_order' => $document_type_base->sort_order,
                        'status' => 1,
                        'company_id' => $company->id,
                        'draft_prefix' => '',
                        'draft_current_number' => 0,
                        'branch_office_id' => $request->branch_office_id
                    ]);
                }
            }

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

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

            //Redireccion
            return redirect()->route('document-types.index');
        } catch (\Exception $e) {
            \DB::connection('tenant')->rollback();
            flash($e->getMessage())->error();
            return redirect()->route('document-types.index');
        }
    }
}
