<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Models\Warehouse;
use App\Http\Controllers\Controller;
use App\DTOs\WarehouseGuide\WarehouseGuideCreateDto;
use App\DTOs\WarehouseGuide\WarehouseGuideUpdateDto;
use App\Services\Interfaces\IWarehouseGuideService;
use App\Repositories\Interfaces\IWarehouseRepository;

class WarehouseGuideController extends Controller
{

    private $warehouseguideService;
    private $warehouseRepository;
    private $errorConnection = "";

    public function __construct(Request $request,
                                IWarehouseGuideService $warehouseguideService,
                                IWarehouseRepository $warehouseRepository)
    {
        if (isset($request['business_information'])) {
            $business_information = $request['business_information'];
            $ruc = $business_information['ruc_number'];

            $existe_conexion = $this->setDBClient($ruc);

            if($existe_conexion['error']){
                $this->errorConnection=$existe_conexion['message'];
                return $this->messageError("Se espera un número de RUC válido.", 201); 
            } else {
                $this->warehouseguideService = $warehouseguideService;
                $this->warehouseRepository = $warehouseRepository;
            }
        } else {
            $this->errorConnection='Error en la conexión. Se espera número de RUC';
            $this->errorConnection=json_encode($request->all());
        }
    }

    public function index(Request $request)
    {
        if($this->errorConnection != ''){
            return $this->messageError($this->errorConnection, 201); 
        }

        $result = $this->warehouseguideService->paginate($request->all());    

        if ($result) {
            return $this->successResponse($result, "Guías encontradas correctamente", 201);
        } else {
            return $this->errorResponse("No hay guías", 201);
        }
    }

    public function show(int $id)
    {
        if($this->errorConnection != ''){
            return $this->messageError($this->errorConnection, 201); 
        }

        $result = $this->warehouseguideService->find($id);

        if ($result) {
            return $this->successResponse($result, "Guía encontrada correctamente", 201);
        } else {
            return $this->errorResponse("Guía no encontrada", 201);
        }
    }

    public function store(Request $request)
    {
        try {
            if($this->errorConnection != ''){
                return $this->messageError($this->errorConnection, 201); 
            }

            $this->validate($request, [
                /*'code' => 'required|unique:tec_warehouses|max:10',
                'warehouse' => 'required|max:250',
                'address' => 'required|max:200',
                'location' => 'required|max:6',
                'external_guide_serie' => 'required|max:4',
                'external_guide_number' => 'required|max:8',
                'internal_guide_serie' => 'required|max:4',
                'internal_guide_number' => 'required|max:8'*/
            ]);

            $data = $request->except('business_information');
            $data['id'] = 0;
            $guide_type = $data['guide_type'];
            $warehouse_counter = $data['counter'];
            $warehouse = ""; $external_guide_number_post = ""; $internal_guide_number_post = "";
            if( $guide_type == "S" ){
                $warehouse_id = $data['warehouse_id'];
                $warehouse = $this->warehouseRepository->find($warehouse_id);
                if( !is_null($warehouse) && $warehouse != "" ){
                    if( $warehouse_counter == "externo" ){
                        if( !is_null($warehouse->external_guide_serie) && $warehouse->external_guide_serie != "" ){
                            $external_guide_number = ($warehouse->external_guide_number=="") ? 0 : $warehouse->external_guide_number;
                            $external_guide_number_post = $external_guide_number + 1;
                            $data['guide_number'] = $warehouse->external_guide_serie . "-" . $external_guide_number_post;
                        } else {
                            return $this->errorResponse("El almacén no tiene cargada una serie para la guía externa.", 201);
                        }
                    } elseif( $warehouse_counter == "interno" ){
                        if( !is_null($warehouse->internal_guide_serie) && $warehouse->internal_guide_serie != "" ){
                            $internal_guide_number = ($warehouse->internal_guide_number=="") ? 0 : $warehouse->internal_guide_number;
                            $internal_guide_number_post = $internal_guide_number + 1;
                            $data['guide_number'] = $warehouse->internal_guide_serie . "-" . $internal_guide_number_post;
                        } else {
                            return $this->errorResponse("El almacén no tiene cargada una serie para la guía interna.", 201);
                        }
                    } else {
                        return $this->errorResponse("No seleccionó un contador para el almacén.", 201);
                    }
                } else {
                    return $this->errorResponse("No existe el almacén seleccionado.", 201);
                }
            }
            $store = new WarehouseGuideCreateDto($data);
            $this->warehouseguideService->store($store);
            if( $guide_type == "S" && $warehouse != "" ){
                if( $warehouse_counter == "externo" ){
                    $warehouse->external_guide_number = $external_guide_number_post;
                    $warehouse->save();
                } elseif( $warehouse_counter == "interno" ){
                    $warehouse->internal_guide_number = $internal_guide_number_post;
                    $warehouse->save();
                }
            }
            $result = [];
    
            return $this->successResponse($result, "Guía creada correctamente", 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        }
    }

    public function update(int $id, Request $request)
    {
        try {
            if($this->errorConnection != ''){
                return $this->messageError($this->errorConnection, 201); 
            }

            $this->validate($request, [
                /*'code' => [
                    'required',
                    Rule::unique('tec_warehouses')->ignore($id),
                    'max:10'
                ],
                'warehouse' => 'required|max:250',
                'address' => 'required|max:200',
                'location' => 'required|max:6',
                'external_guide_serie' => 'required|max:4',
                'external_guide_number' => 'required|max:8',
                'internal_guide_serie' => 'required|max:4',
                'internal_guide_number' => 'required|max:8'*/
            ]);
    
            $data = $request->except('business_information');
            $data['id'] = $id;
    
            $guide_type = $data['guide_type'];
            $warehouse_counter = $data['counter'];
            $warehouse = ""; $external_guide_number_post = ""; $internal_guide_number_post = "";
            if( $guide_type == "S" ){
                $warehouse_id = $data['warehouse_id'];
                $warehouse = $this->warehouseRepository->find($warehouse_id);
                if( !is_null($warehouse) && $warehouse != "" ){
                    if( $warehouse_counter == "externo" ){
                        if( !is_null($warehouse->external_guide_serie) && $warehouse->external_guide_serie != "" ){
                            $external_guide_number = ($warehouse->external_guide_number=="") ? 0 : $warehouse->external_guide_number;
                            $external_guide_number_post = $external_guide_number + 1;
                            $data['guide_number'] = $warehouse->external_guide_serie . "-" . $external_guide_number_post;
                        } else {
                            return $this->errorResponse("El almacén no tiene cargada una serie para la guía externa.", 201);
                        }
                    } elseif( $warehouse_counter == "interno" ){
                        if( !is_null($warehouse->internal_guide_serie) && $warehouse->internal_guide_serie != "" ){
                            $internal_guide_number = ($warehouse->internal_guide_number=="") ? 0 : $warehouse->internal_guide_number;
                            $internal_guide_number_post = $internal_guide_number + 1;
                            $data['guide_number'] = $warehouse->internal_guide_serie . "-" . $internal_guide_number_post;
                        } else {
                            return $this->errorResponse("El almacén no tiene cargada una serie para la guía interna.", 201);
                        }
                    } else {
                        return $this->errorResponse("No seleccionó un contador para el almacén.", 201);
                    }
                } else {
                    return $this->errorResponse("No existe el almacén seleccionado.", 201);
                }
            }
            $entry = new WarehouseGuideCreateDto($data);
            $this->warehouseguideService->update($entry);
            if( $guide_type == "S" && $warehouse != "" ){
                if( $warehouse_counter == "externo" ){
                    $warehouse->external_guide_number = $external_guide_number_post;
                    $warehouse->save();
                } elseif( $warehouse_counter == "interno" ){
                    $warehouse->internal_guide_number = $internal_guide_number_post;
                    $warehouse->save();
                }
            }
            $result = $this->warehouseguideService->find($id);

            return $this->successResponse($result, "Guía actualizada correctamente", 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        }
    }

    public function destroy(int $id)
    {
        if($this->errorConnection != ''){
            return $this->messageError($this->errorConnection, 201); 
        }

        $result = $this->warehouseguideService->find($id);

        if ($result) {
            $this->warehouseguideService->destroy($id);

            return $this->successResponse($id, "Guía eliminada correctamente", 201);    
        } else {
            return $this->errorResponse("Guía ingresada no existe", 201);
        }
        
    }    
}
