<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Validator;

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

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

    public function getDocumentByOrder($order, $line) {

        try {
            $orderNumber = $this->encController->decrypt($order);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_REG001: Ocurrió un error al desencriptar los datos.", [], 401);
        }

        try {
            $arrDocuments = DB::table('S002V01TDOOR')
                ->where('DOOR_NUOR', '=', $orderNumber)
                ->where('DOOR_NULI', '=', $line)
                ->join('S002V01TTIDO', 'TIDO_ACRO', '=', 'DOOR_TIPO')
                ->get([
                    'DOOR_IDDO', // Identificador del documento
                    'DOOR_NUOR', // Número de la orden
                    'DOOR_CODO', // Código del documento
                    'DOOR_DESC', // Descripción del documento
                    'DOOR_TIPO', // Tipo del documento
                    'TIDO_TIPO', // Nombre del tipo
                    'DOOR_ESTA', // Estado del documento
                    'DOOR_USRE', // Usuario registra
                    'DOOR_FERE', // Fecha registra
                    'DOOR_USMO', // Usuario modifica
                    'DOOR_FEMO', // Fecha modifica
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_GET000: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrDocuments);
    }

    public function registerDocumentOrder(Request $request) {
        $valitador = Validator::make($request->all(), [
            'ORDEN' => 'required|string|max:10',
            'NAME_DOCUMENT' => 'required|string|max:100',
            'DESCRIPCION' => 'required|string|max:50',
            'TIPO' => 'required|string|max:2',
            'DOCUMENTO' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
            'USUARIO' => 'required|string'
        ]);
        if ($valitador->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_DOCUMENT_ORDER_REG000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($valitador->errors()->messages()),
                401
            );
        }
        DB::beginTransaction();
        $responseData = $request->all();
        try {
            $user = $this->encController->decrypt($responseData['USUARIO']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_REG001: Ocurrió un error al desencriptar los datos.", [], 401);
        }

        $documentName = $this->resourcesController->nameFormatDocument($responseData['NAME_DOCUMENT']);
        $arrResponseDocument =  $this->resourcesController->saveDocument( $responseData['DOCUMENTO'], 'GEAD', $documentName, $responseData['TIPO'], $responseData['NUMERO_LINEA']  );
        if ( $arrResponseDocument['error'] ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, $arrResponseDocument['msg'], $arrResponseDocument['response'], 500);
        }
        $documentCode = $arrResponseDocument['response'];

        $arrInsert = [
            'DOOR_NUOR' => $responseData['ORDEN'],
            'DOOR_CODO' => $documentCode,
            'DOOR_DESC' => $responseData['DESCRIPCION'],
            'DOOR_TIPO' => $responseData['TIPO'],
            'DOOR_NULI' => $responseData['NUMERO_LINEA'],
            'DOOR_USRE' => $user,
            'DOOR_FERE' => Carbon::now()->timezone('America/Mazatlan')->toDateTimeString(),
            'DOOR_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];

        try {
            $validateInsert = DB::table('S002V01TDOOR')->insert($arrInsert);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_REG002: Ocurrió un error al ingresar los registros.", [], 401);
        }

        if ( !$validateInsert ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_REG003: Ocurrió un error al ingresar los registros.", [], 401);
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Registro de Documento Exitoso");
    }

    public function updateDocumentOrder(Request $request) {
        $valitador = Validator::make($request->all(), [
            'ID_DOCUMENT' => 'required|integer',
            'CODE_DOCUMENT' => 'required|string',
            'ORDEN' => 'required|string|max:10',
            'NAME_DOCUMENT' => 'required|string|max:100',
            'DESCRIPCION' => 'required|string|max:50',
            'TIPO' => 'required|string|max:2',
            'DOCUMENTO' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
            'USUARIO' => 'required|string'
        ]);
        if ($valitador->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_DOCUMENT_ORDER_UPD000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($valitador->errors()->messages()),
                401
            );
        }

        DB::beginTransaction();
        $responseData = $request->all();

        // Se obtiene el identificador del usuario
        try {
            $user = $this->encController->decrypt($responseData['USUARIO']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_UPD001: Ocurrió un error al desencriptar los datos.", [], 401);
        }

        // Nombre del código del docuento
        $documentCode = '';

        // Se verifica si hubo una modificación en el documento
        if ( $responseData['DOCUMENTO'] !== 'unmodified' ) {
            // Se da formato al nombre del documento
            $documentName = $this->resourcesController->nameFormatDocument($responseData['NAME_DOCUMENT']);

            // Se registra el nuevo documento con diferente versión
            $arrResponseDocument = $this->resourcesController->updateDocument( $responseData['CODE_DOCUMENT'], $responseData['DOCUMENTO'], 'GEAD',
                $documentName, $responseData['TIPO'], $responseData['NUMERO_LINEA'] );
            if ( $arrResponseDocument['error'] ) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, $arrResponseDocument['msg'], $arrResponseDocument['response'], 500);
            }
            $documentCode = $arrResponseDocument['response'];
        } else {
            $documentCode = $responseData['CODE_DOCUMENT'];
        }

        try {
            $validateUpdate = DB::table('S002V01TDOOR')
                ->where('DOOR_IDDO', '=', $responseData['ID_DOCUMENT'])
                ->where('DOOR_NULI', '=', $responseData['NUMERO_LINEA'])
                ->where('DOOR_NUOR', '=', $responseData['ORDEN'])
                ->update([
                    'DOOR_CODO' => $documentCode,
                    'DOOR_DESC' => $responseData['DESCRIPCION'],
                    'DOOR_TIPO' => $responseData['TIPO'],
                    'DOOR_USMO' => $user,
                    'DOOR_FEMO' => Carbon::now()->timezone('America/Mazatlan')->toDateTimeString(),
                    'DOOR_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_UPD002: Ocurrió un error al ingresar los registros.", [], 401);
        }

        if ( !$validateUpdate ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_UPD003: No se pudo ingresar los registros.", [], 401);
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Registro de Documento Exitoso");
    }

    public function deleteDocumentOrder(Request $request) {
        $valitador = Validator::make($request->all(), [
            'ID_DOCUMENTO' => 'required|integer',
            'NUMERO_LINEA' => 'required|string',
            'USUARIO' => 'required|string'
        ]);
        if ($valitador->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_DOCUMENT_ORDER_DEL000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($valitador->errors()->messages()),
                401
            );
        }
        DB::beginTransaction();
        $responseData = $request->all();
        try {
            $user = $this->encController->decrypt($responseData['USUARIO']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_DEL001: Ocurrió un error al desencriptar los datos.", [], 401);
        }

        $arrDelete = [
            'DOOR_ESTA' => 'Eliminado',
            'DOOR_USMO' => $user,
            'DOOR_FEMO' => Carbon::now()->timezone('America/Mazatlan')->toDateTimeString(),
            'DOOR_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];

        try {
            $validateDelete = DB::table('S002V01TDOOR')
                ->where('DOOR_IDDO', '=', $responseData['ID_DOCUMENTO'])
                ->where('DOOR_NULI', '=', $responseData['NUMERO_LINEA'])
                ->update($arrDelete);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_DEL002: Ocurrió un error al modificar los registros.", [], 401);
        }

        if ( !$validateDelete ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_DEL003: No se pudo modificar los registros.", [], 401);
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Eliminación de Documento Exitoso");
    }
}
