<?php
/*
    Desarrollador: Ing. Jean Jairo Benitez Meza
    Ultima Modificación: 11/04/2023
    Módulo: Formularios Dinámicos
*/
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
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;
use App\Http\Controllers\FunctionsController;

class ModuleController extends Controller
{
    private $responseController;
    private $encController;
    private $functionsController;
    public function __construct(){
        $this->responseController = new ResponseController();
        $this->encController = new EncryptionController();
        $this->functionsController = new FunctionsController();
    }

    // Obtener Todos los Módulos (FUNCIONAL)
    public function getModule($user, $line){
        try {
            $resp = DB::table('S002V01TMODU')
                ->where('MODU_NULI', '=', $line)
                ->orderBy('MODU_IDMO', 'ASC')
                ->get([ 
                    'MODU_IDMO', 
                    'MODU_NOMO AS MODU_NOMB', 
                    'MODU_USMO', 
                    'MODU_FEMO', 
                    // 'MODU_ESTA'
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG000: No se pudo realizar la consulta a la base.", [], 500);
        }
        return $this->responseController->makeResponse(false, "ÉXITO", $resp);
    }

    // Obtener Todos los Módulos ACTIVOS
    public function getModuleAviable($user, $line){
        try {
            $resp = DB::table('S002V01TMODU')
                // ->where('MODU_ESTA', '=', 'Activo')
                ->where('MODU_NULI', '=', $line)
                ->orderBy('MODU_IDMO', 'ASC')
                ->get([ 'MODU_IDMO AS CODIGO_MODULO', 'MODU_NOMO AS MODULO']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG000: No se pudo realizar la consulta a la base.", [], 500);
        }
        return $this->responseController->makeResponse(false, "ÉXITO", $resp);
    }

    // Registro de Módulos (FUNCIONAL)
    public function registerModule(Request $request){
        $validator = Validator::make($request->all(), [
            'linea' => 'required|integer',
            'codigo' => 'required|string|max:10',
            'modulo' => 'required|string|max:150',
            'user' => 'required|string'
        ]);
        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_MODULE_REG000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($validator->errors()->messages()),
                401
            );
        }

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

        try {
            $valid = DB::table('S002V01TMODU')->where('MODU_IDMO', $form['codigo'])->first();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG001: No se pudo realizar la consulta a la base.", [], 500);
        }
        if (!empty($valid)) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG002: El código ".$form['codigo']." ya existe.", [], 500);
        }

        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();

        $user = $this->encController->decrypt($form['user']);
        $ins = [
            'MODU_NULI' => $form['linea'],
            'MODU_IDMO' => $form['codigo'],
            'MODU_NOMO' => $form['modulo'],
            'MODU_USRE' => $user,
            'MODU_FERE' => $currentDate,
            'MODU_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];

        try {
            $validateInsert = DB::table('S002V01TMODU')->insert($ins);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG003: Ocurrió un error al hacer la inserción en la base.", [], 500);
        }
        if (!$validateInsert) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG004: No se pudo realizar la inserción en la base.", [], 500);
        }
        DB::commit();
        return $this->responseController->makeResponse(false, "EXITO: Registro correcto");
    }

    // Modificación de Módulos (FUNCIONAL)
    public function updateModule(Request $request){
        $validator = Validator::make($request->all(), [
            'codigo' => 'required|string|max:10',
            'modulo' => 'required|string|max:150',
            'user' => 'required|string'
        ]);

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

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

        try {
            $valid = DB::table('S002V01TMODU')
                ->where('MODU_IDMO', $form['codigo'])
                ->where('MODU_ESTA', '=', 'Activo')
                ->first();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG001: No se pudo realizar la consulta a la base.", [], 500);
        }
        if (empty($valid)) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG002: El código ".$form['codigo']." no existe.", [], 500);
        }

        try {
            $user = $this->encController->decrypt($request['user']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG003: No se pudo obtener el usuario.", [], 500);
        }

        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();

        $mdf = [
            'MODU_NOMO' => $form['modulo'],
            'MODU_USMO' => $user,
            'MODU_FEMO' => $currentDate,
            'MODU_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];

        try {
            $validateUdpdate = DB::table('S002V01TMODU')->where('MODU_IDMO', $form['codigo'])->update($mdf);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG004: No se pudo realizar la modificación a la base.", [], 500);
        }
        if (!$validateUdpdate) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_REG005: No se pudo realizar la inserción en la base.", [], 500);
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "EXITO: Modificación Exitosa");
    }

    // Eliminación de Módulos (FUNCIONAL)
    public function deleteModule(Request $request){
        $validator = Validator::make($request->all(), [
            'codigo' => 'required|string|max:10',
            'user' => 'required|string'
        ]);

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

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

        try {
            $valid = DB::table('S002V01TMODU')->where('MODU_IDMO', $form['codigo'])->first();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_DEL001: No se pudo realizar la consulta a la base.", [], 500);
        }
        if (empty($valid)) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_DEL002: El código ".$form['codigo']." no existe.", [], 500);
        }
        if ( $valid->MODU_ESTA == 'Eliminado' ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_DEL003: El código ".$form['codigo']." ya está eliminado.", [], 500);
        }

        try {
            $user = $this->encController->decrypt($request['user']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_DEL004: No se pudo obtener el usuario.", [], 500);
        }

        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();

        $mdf = [
            'MODU_ESTA' => 'Eliminado',
            'MODU_USMO' => $user,
            'MODU_FEMO' => $currentDate,
            'MODU_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];

        try {
            $validateUpdate = DB::table('S002V01TMODU')->where('MODU_IDMO', $form['codigo'])->update($mdf);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_DEL005: No se pudo realizar la consulta a la base.", $th, 500);
        }

        if (!$validateUpdate) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MODULE_DEL006: No se pudo realizar la consulta a la base.", [], 500);
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "EXITO: Modificación Exitosa");
    }
}
