<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\DTOs\Warehouses\WarehouseCreateDto;
use App\DTOs\Warehouses\WarehouseUpdateDto;
use App\Repositories\Interfaces\IWarehouseRepository;
use Exception;
use App\Models\Warehouse;

class WarehouseController extends Controller
{

    private $warehouseRepository;

    private $errorConnection = "";

    public function __construct(Request $request, 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->warehouseRepository = $warehouseRepository;
            }
        } else {
            $this->errorConnection='Error en la conexión. Se espera número de RUC';
        }      
    }

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

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

        if ($result) {
            return $this->successResponse($result, "Almacenes encontrados correctamente", 201);
        } else {
            return $this->errorResponse("No hay Almacenes", 201);
        }
    }

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

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

        if ($result) {
            //return $result;
            return $this->successResponse($result, "Almacen encontrado correctamente", 201);
        } else {
            return $this->errorResponse("Almacen no encontrado", 201);
        }

        //return response('Almacen no encontrado', 404);
    }

    public function store(Request $request)
    {        
        try {
            if($this->errorConnection != ''){
                return $this->messageError($this->errorConnection, 201); 
            }
    
            $code = $request['code'];
            $codeExist = Warehouse::where('code', '=', $code)->get();

            if (count($codeExist) == 0) {
                $this->validate($request, [
                    'code' => 'required|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'
                ], [
                    'code.required' => 'El código de Almacen es requerido',
                    'code.max' => 'El código de Almacen no puede superar los :max caracteres',
                    'warehouse.required' => 'El nombre de Almacen es requerido',
                    'address.required' => 'La dirección del Almacen es requerido',
                    'location.required' => 'El distrito del Almacen es requerido',
                    'external_guide_serie.required' => 'La serie de la Guia Externa es requerido',
                    'external_guide_number.required' => 'El correlativo de la Guia Externa es requerido',
                    'internal_guide_serie.required' => 'La serie de la Guia Interna es requerido',
                    'internal_guide_number.required' => 'El correlativo de la Guia Interna es requerido'
                ]);
    
                $store = new WarehouseCreateDto($request->except('business_information'));
                $result = $this->warehouseRepository->store($store);
        
                return $this->successResponse($result, "Almacen creado correctamente", 201);
            } else {
                return $this->errorResponse("Codigo de Almacen ingresado ya existe", 201);
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        }        
      
        //return response($result, 201);
    }

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

            if ($result) {
                $code = $request['code'];
                $codeExist = Warehouse::where('id', '!=', $id)->where('code', '=', $code)->get();
    
                if (count($codeExist) == 0) {
                    $this->validate($request, [
                        'code' => [
                            'required',
                            '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'
                    ], [
                        'code.required' => 'El código de Almacen es requerido',
                        'code.max' => 'El código de Almacen no puede superar los :max caracteres',
                        'warehouse.required' => 'El nombre de Almacen es requerido',
                        'address.required' => 'La dirección del Almacen es requerido',
                        'location.required' => 'El distrito del Almacen es requerido',
                        'external_guide_serie.required' => 'La serie de la Guia Externa es requerido',
                        'external_guide_number.required' => 'El correlativo de la Guia Externa es requerido',
                        'internal_guide_serie.required' => 'La serie de la Guia Interna es requerido',
                        'internal_guide_number.required' => 'El correlativo de la Guia Interna es requerido'
                    ]);
            
                    $data = $request->except('business_information');
                    $data['id'] = $id;
            
                    $entry = new WarehouseUpdateDto($data);
            
                    $this->warehouseRepository->update($entry);
        
                    $result = $this->warehouseRepository->find($id);
        
                    return $this->successResponse($result, "Almacen actualizado correctamente", 201);
                } else {
                    return $this->errorResponse("Codigo de Almacen ingresado ya existe", 201);
                }
            } else {
                return $this->errorResponse("Almacen ingresado no existe", 201);
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        }

        //return response(null, 202);
    }

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

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

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

            return $this->successResponse($id, "Almacen eliminado correctamente", 201);    
        } else {
            return $this->errorResponse("Almacen ingresado no existe", 201);
        }

        //return response(null, 202);
    }    
}
