<?php
/*
    Desarrollador: Ing. Jean Jairo Benitez Meza
    Ultima Modificación: 11/04/2023
    Módulo: Gestión de Inventario y/o Stock
*/
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ResourcesController;
use App\Http\Controllers\ResponseController;
use App\Http\Controllers\EncryptionController;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class StockController extends Controller
{
    private $responseController;
    private $encController;
    private $resourcesController;

    public function __construct(){
        $this->responseController = new ResponseController();
        $this->encController = new EncryptionController();
        $this->resourcesController = new ResourcesController();
    }

    // Crear Artículo en Stock
    public function createArtitleWithoutOrder(Request $request) {
        $validator = Validator::make($request->all(), [
            'ARTICULO' => 'required',
            'MODELO' => 'required',
            'CODIGO_MODELO' => 'required',
            'FAMILIA' => 'required',
            'SUBFAMILIA' => 'required',
            'UNIDAD' => 'required',
            'CODIGO_BARRAS' => 'required',
            'CANTIDAD' => 'required',
            'STOCK_MINIMO' => 'required',
            'STOCK_MAXIMO' => 'required',
            'REPARACION' => 'required|boolean',
            'CONSUMIBLE' => 'required|boolean',
            'PELIGROSO' => 'required|boolean',
            // 'FECHA_VENCIMIENTO' => '',
            'PROVEEDOR' => 'required',
            'IMAGEN' => 'required',
            'NUMERO_LINEA' => 'required',
            'USUARIO' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_STOCK_REG000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($validator->errors()->messages()),
                401
            );
        }

        $requestData = $request->all();

        try {
            $user = $this->encController->decrypt($requestData['USUARIO']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG001: Ocurrió un error al obtener el usuario.", $th->getMessage(), 500);
        }

        try {
            $validateFamily = DB::table('S002V01TFAMI')
                ->where('FAMI_IDFA','=', $requestData['FAMILIA'])
                ->where('FAMI_NULI','=', $requestData['NUMERO_LINEA'])
                ->where('FAMI_ESTA','=','Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG002: Ocurrió un error al validar la familia.", $th->getMessage(), 500);
        }
        if (!$validateFamily) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG003: La familia no existe.", [], 500);
        }

        try {
            $validateSubfamily = DB::table('S002V01TSUBF')
                ->where('SUBF_IDSU','=', $requestData['SUBFAMILIA'])
                ->where('SUBF_NULI','=', $requestData['NUMERO_LINEA'])
                ->where('SUBF_ESTA','=','Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG004: Ocurrió un error al validar la subfamilia.", $th->getMessage(), 500);
        }
        if (!$validateSubfamily) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG005: La subfamilia no existe.", [], 500);
        }
        
        try {
            $validateUnit = DB::table('S002V01TUNID')
                ->where('UNID_IDUN','=', $requestData['UNIDAD'])
                ->where('UNID_NULI','=', $requestData['NUMERO_LINEA'])
                ->where('UNID_ESTA','=','Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG006: Ocurrió un error al validar la unidad.", $th->getMessage(), 500);
        }
        if (!$validateUnit) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG007: La unidad no existe.", [], 500);
        }

        try {
            $validateUnit = DB::table('S002V01TPROV')
                ->where('PROV_NUPR','=', $requestData['PROVEEDOR'])
                ->where('PROV_NULI','=', $requestData['NUMERO_LINEA'])
                ->where('PROV_ESTA','=','Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG008: Ocurrió un error al validar el proveedor.", $th->getMessage(), 500);
        }
        if (!$validateUnit) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG009: El proveedor no existe.", [], 500);
        }
        $jsonCodeImages = array();
        foreach ($requestData['IMAGEN'] as $imagen) {

            $arrResponseDocument = $this->resourcesController->saveDocument($imagen['base64File'],'GEAD',$imagen['nameFile'],'FO',$requestData['NUMERO_LINEA']);
            if ($arrResponseDocument['error']) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, 'ERR_STOCK_REG010:'.$arrResponseDocument['msg'], $arrResponseDocument['response'], 500);
            }

            $jsonCodeImages[] = $arrResponseDocument['response'];
        }

        try {
            $validateRegister = DB::table('S002V01TSTAR')->insert([
                // 'STAR_CODI' => $requestData['CODIGO_STOCK'],
                'STAR_ARTI' => $requestData['ARTICULO'],
                'STAR_MODE' => $requestData['MODELO'],
                'STAR_COMO' => $requestData['CODIGO_MODELO'],
                'STAR_IDFA' => $requestData['FAMILIA'],
                'STAR_IDSU' => $requestData['SUBFAMILIA'],
                'STAR_NUPR' => $requestData['PROVEEDOR'],
                'STAR_IDUN' => $requestData['UNIDAD'],
                'STAR_COBA' => $requestData['CODIGO_BARRAS'],
                'STAR_CANT' => $requestData['CANTIDAD'],
                'STAR_STMI' => $requestData['STOCK_MINIMO'],
                'STAR_STMA' => $requestData['STOCK_MAXIMO'],
                'STAR_REPA' => $requestData['REPARACION'],
                'STAR_CONS' => $requestData['CONSUMIBLE'],
                'STAR_PELI' => $requestData['PELIGROSO'],
                'STAR_FEVE' => $requestData['FECHA_VENCIMIENTO'],
                'STAR_IMAG' => json_encode($jsonCodeImages),
                'STAR_TIAD' => 'Sin Pedido',
                'STAR_NULI' => $requestData['NUMERO_LINEA'],
                'STAR_USRE' => $user,
                'STAR_FERE' => Carbon::now()->timezone('America/Mazatlan')->toDateTimeString(),
                'STAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
            ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG011: Ocurrió un error al registrar el artículo.", $th->getMessage(), 500);
        }

        if (!$validateRegister) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_STOCK_REG012: No se pudo registrar el artículo.", [], 500);
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "EXITO: Registro Exitoso");
    }
}
