<?php

namespace App\Http\Controllers;

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

class WorkTeamController extends Controller{
    private $responseController;
    private $encryptionController;
    private $documentManagementController;
    private $functionsController;

    public function __construct(){
        $this->responseController = new ResponseController();
        $this->encryptionController = new EncryptionController();
        $this->documentManagementController = new DocumentManagementController();
        $this->functionsController = new FunctionsController();
    }

    public function storeWorkteam(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'NAME' => 'required|string|max:100',
            'SPECIALITY' => 'required|string|max:100',
        ]);

        if($validator->fails()){
            return $this->responseController->makeResponse(
                TRUE,
                'ERR_PERSONAL_REG001: Uno o más errores encontrados',
                $this->responseController->makeErrors($validator->errors()->messages()),
                400
            );
        }

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $team = DB::table('S002V01TEQMA')->where([
            ['EQMA_NOMB', '=', $form['NAME']],
            ['EQMA_NULI', '=', $form['linea']],
            ['EQMA_ESTA', '=', 'Activo'],
        ])->get()->all();

        if(count($team) > 0){
            return $this->responseController->makeResponse(true, "El nombre $form[NAME] ya fue tomado", [], 401);
        }

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        DB::table('S002V01TEQMA')->insert([
            "EQMA_NULI" => $form['linea'],
            "EQMA_NOMB" => $form['NAME'],
            "EQMA_ESPE" => $form['SPECIALITY'],
            "EQMA_USRE" => $idUser,
            "EQMA_FERE" => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M11GPRS',
            'S002V01F01AETR',
            'S002V01P02REET',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró el equipo de trabajo $form[NAME].",
            $idUser,
            $nowStr,
            'S002V01S04GETR'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
        return $this->responseController->makeResponse(false, 'EXITO.');
    }

    public function getConsultOfWorkteams($idUser, $line) {
        DB::enableQueryLog();

        $idUser = $this->encryptionController->decrypt($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $line],
            ['USUA_IDUS', '=', $idUser],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $workteams = DB::table('S002V01TEQMA')->select([
            'EQMA_IDEQ as WORKTEAM_ID',
            'EQMA_NOMB as NAME',
            'EQMA_ESPE as SPECIALITY',
            'EQMA_ESTA as STATUS'
        ])->where('EQMA_NULI', '=', $line)->get()->all();

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M11GPRS',
            'S002V01F01AETR',
            'S002V01P01CETR',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipos de trabajo registrados.",
            $idUser,
            $nowStr,
            'S002V01S04GETR'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO.', $workteams);
    }
    
    public function getWorkteamById($workteam, $idUser, $line) {
        DB::enableQueryLog();

        $idUser = $this->encryptionController->decrypt($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $line],
            ['USUA_IDUS', '=', $idUser],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $workteam = $this->encryptionController->decrypt($workteam);
        if(!$workteam){
            return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
        }

        $team = DB::table('S002V01TEQMA')->select([
            'EQMA_IDEQ as WORKTEAM_ID',
            'EQMA_NOMB as NAME',
            'EQMA_ESPE as SPECIALITY',
            'EQMA_ESTA as STATUS'
        ])->where([
            ['EQMA_IDEQ', '=', $workteam],
            ['EQMA_NULI', '=', $line],
        ])->first();

        if(is_null($team)){
            return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
        }

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M11GPRS',
            'S002V01F01AETR',
            'S002V01P03DETR',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los detalles del equipo de trabajo " . $team->NAME . ".",
            $idUser,
            $nowStr,
            'S002V01S04GETR'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO.', $team);
    }

    public function getMembersOfWorkteamById($workteam, $idUser, $line) {
        DB::enableQueryLog();

        $idUser = $this->encryptionController->decrypt($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $line],
            ['USUA_IDUS', '=', $idUser],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $workteam = $this->encryptionController->decrypt($workteam);
        if(!$workteam){
            return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
        }

        $team = DB::table('S002V01TEQMA')->where([
            ['EQMA_IDEQ', '=', $workteam],
            ['EQMA_NULI', '=', $line],
        ])->first();

        if(is_null($team)){
            return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
        }

        $members = DB::table('S002V01TPERS')->select([
            DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
            'PERS_IDPE AS IDEMPLEADO',
            'PERS_IDUS AS IDUSUARIO'
        ])->where([
            ['EQMA_IDEQ', '=', $workteam],
            ['EQMA_NULI', '=', $line],
            ['PERS_ESTA', '=', 'Activo'],
        ])->join(
            'S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS'
        )->join(
            'S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ'
        )->get()->all();

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M11GPRS',
            'S002V01F01AETR',
            'S002V01P03DETR',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los integrantes del equipo de trabajo " . $team->EQMA_NOMB . ".",
            $idUser,
            $nowStr,
            'S002V01S04GETR'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO.', $members);
    }

    public function updateWorkteam(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'WORKTEAM_ID' =>'required|string',
            'NAME' => 'required|string|max:100',
            'SPECIALITY' => 'required|string|max:100',
        ]);

        if($validator->fails()) {
            return $this->responseController->makeResponse(
                TRUE,
                'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
                $this->responseController->makeErrors($validator->errors()->messages()),
                400
            );
        }

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $workteam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
        if(!$workteam){
            return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
        }

        $team = DB::table('S002V01TEQMA')->where([
            ['EQMA_IDEQ', '=', $workteam],
            ['EQMA_NULI', '=', $form['linea']],
        ])->first();

        if(is_null($team)){
            return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
        }

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

        DB::table('S002V01TEQMA')->where([
            ["EQMA_IDEQ", '=', $workteam],
            ['EQMA_NULI', '=', $form['linea']]
        ])->update([
            "EQMA_NOMB" => $form['NAME'],
            "EQMA_ESPE" => $form['SPECIALITY'],
            "EQMA_USMO" => $idUser,
            "EQMA_FEMO" => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M11GPRS',
            'S002V01F01AETR',
            'S002V01P02REET',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el equipo de trabajo #$workteam.",
            $idUser,
            $nowStr,
            'S002V01S04GETR'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
        return $this->responseController->makeResponse(false, 'EXITO.');
    }

    public function updateToInactiveStatus(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'WORKTEAM_ID' =>'required|string',
        ]);

        if($validator->fails()) {
            return $this->responseController->makeResponse(
                TRUE,
                'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
                $this->responseController->makeErrors($validator->errors()->messages()),
                400
            );
        }

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $workteam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
        if(!$workteam){
            return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
        }

        $team = DB::table('S002V01TEQMA')->where([
            ['EQMA_IDEQ', '=', $workteam],
            ['EQMA_NULI', '=', $form['linea']],
        ])->first();

        if(is_null($team)){
            return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
        }

        $members = DB::table('S002V01TPERS')->select([
            DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
            'PERS_IDPE AS IDEMPLEADO',
            'PERS_IDUS AS IDUSUARIO'
        ])->where([
            ['EQMA_IDEQ', '=', $workteam],
            ['EQMA_NULI', '=', $form['linea']],
            ['PERS_ESTA', '=', 'Activo'],
        ])->join(
            'S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS'
        )->join(
            'S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ'
        )->get()->all();

        if(count($members) > 0){
            return $this->responseController->makeResponse(true, 'El equipo de trabajo que desea eliminar tiene usuarios relacionados.', [], 401);
        }

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

        DB::table('S002V01TEQMA')->where([
            ["EQMA_IDEQ", '=', $workteam],
            ['EQMA_NULI', '=', $form['linea']]
        ])->update([
            "EQMA_ESTA" => 'Eliminado',
            "EQMA_USMO" => $idUser,
            "EQMA_FEMO" => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M11GPRS',
            'S002V01F01AETR',
            'S002V01P01CETR',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el equipo de trabajo #$workteam.",
            $idUser,
            $nowStr,
            'S002V01S04GETR'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
        return $this->responseController->makeResponse(false, 'EXITO.');
    }
}