<?php
/*
Nombre del programador:         Cordourier Rojas Mathew
Ultima fecha de modificación:   [ 03 / Marzo / 2023 ]
Descripción:                    Controlador del submodulo Intervenciones. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
*/

namespace App\Http\Controllers;

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

class InterventionController extends Controller
{

    private $response_controller;
    private $encrypt_controller;
    private $resources_controller;
    private $documents_controller;
    public function __construct()
    {
        $this->response_controller = new ResponseController();
        $this->encrypt_controller = new EncryptionController();
        $this->resources_controller = new ResourcesController();
        $this->documents_controller = new DocumentsController();
    }

    // Metodo para consultar de las intervenciones
    public function getConsultOfInterventions($line_number)
    {
        try {
            $interventions = DB::table('S002V01TINTE_P')
                ->select(
                    'INTE_IDIN as INTERVENTION_ID',
                    'INTE_FECS as START_DATE',
                    'INTE_FESD as END_DATE'
                )
                ->where('INTE_ESTA', '=', 'Activo')
                ->where('INTE_NULI', '=', $line_number)
                ->get();

            // Verifica si el objeto esta vacio
            if (!isset($interventions[0]) && empty($interventions[0])) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG001: No se encontraron datos', $interventions, 500);
            }

            // Obtiene los datos de la tabla intermediaria entre intervenciones y equipos de mantenimiento
            $equipment_by_intervention = DB::table('S002V01TINMA')
                ->select(
                    'INMA_IDMA as EQUIPMENT_ID',
                    'INMA_IDIN as INTERVENTION_ID'
                )
                ->where('INMA_NULI', '=', $line_number)
                ->get();

            // Cambia el formato de las fechas y el equipamiento que se utilizó por intervención
            foreach ($interventions as $intervention) {
                $intervention->START_DATE = Carbon::create($intervention->START_DATE)->format("d-m-Y h:i:s A");
                $intervention->END_DATE = Carbon::create($intervention->END_DATE)->format("d-m-Y h:i:s A");
                foreach ($equipment_by_intervention as $equipment) {
                    if ($equipment->INTERVENTION_ID == $intervention->INTERVENTION_ID) {
                        $intervention->EQUIPMENTS_ID[] = $equipment->EQUIPMENT_ID;
                    }
                }
            }

            return $this->response_controller
                ->makeResponse(FALSE, 'Consulta exitosa', $interventions);

        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }

    // Metodo para obtener los detalles de una intervención
    public function getDetailsOfInterventionsById($id_intervention, $line_number)
    {
        try {

            $intervention_details = DB::table('S002V01TINTE_P')
                ->select(
                    'INTE_IDIN as INTERVENTION_ID',
                    'INTE_FECS as START_DATE',
                    'INTE_FESD as END_DATE',
                    'INTE_DEFA as FAILURES_INTERVENTION',
                    'INTE_DEAC as ACTIVITIES_INTERVENTION'
                )
                ->where('INTE_IDIN', '=', $id_intervention)
                ->where('INTE_NULI', '=', $line_number)
                ->first();

            // Verifica si el objeto esta vacio
            if (!isset($intervention_details) && empty($intervention_details)) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG001: No se encontró la intervención', $intervention_details, 500);
            }

            $images_failures = DB::table('S002V01TIMAG_P')
                ->select(
                    'IMAG_LIIM as FAILURES_IMAGE_INTERVENTION'
                )
                ->where('IMAG_IDIN', '=', $id_intervention)
                ->where('IMAG_TIIM', '=', 'Falla')
                ->where('IMAG_ESTA', '=', 'Activo')
                ->where('IMAG_NULI', '=', $line_number)
                ->get();

            $images_activities = DB::table('S002V01TIMAG_P')
                ->select(
                    'IMAG_LIIM as ACTIVITIES_IMAGE_INTERVENTION'
                )
                ->where('IMAG_IDIN', '=', $id_intervention)
                ->where('IMAG_TIIM', '=', 'Actividad')
                ->where('IMAG_ESTA', '=', 'Activo')
                ->where('IMAG_NULI', '=', $line_number)
                ->get();

            // Obtiene los equipos que estuvieron presentes en la intervención
            $workteams_on_intervention = DB::table('S002V01TEQMA')
                ->select('S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME', 'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID')
                ->where('S002V01TEMIN.EMIN_IDIN', '=', $id_intervention)
                ->where('S002V01TEMIN.EMIN_NULI', '=', $line_number)
                ->join('S002V01TEMIN', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TEMIN.EMIN_IDEM')
                ->get();

            // Obtiene los equipamientos que se utilizaron para la intervención
            $equipment_on_intervention = DB::table('S002V01TMATE_P')
                ->select('S002V01TMATE_P.MATE_NOMB as NAME', 'S002V01TMATE_P.MATE_LIIM as IMAGE')
                ->where('S002V01TINMA.INMA_IDIN', '=', $id_intervention)
                ->where('S002V01TINMA.INMA_NULI', '=', $line_number)
                ->join('S002V01TINMA', 'S002V01TMATE_P.MATE_IDMA', '=', 'S002V01TINMA.INMA_IDMA')
                ->get();

            // Verifica si el objeto esta vacio
            if (!isset($workteams_on_intervention[0]) && empty($workteams_on_intervention[0])) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_EQUIPO_INTERVENCIÓN_REG002: No se encontraron datos', $intervention_details, 500);
            }

            // Obtiene a los empleados con su nombre
            $employees_workteam = DB::table('S002V01TPEEM')
                ->select(
                    DB::raw('CONCAT(S002V01TUSUA_P.USUA_NOMB, " " , S002V01TUSUA_P.USUA_APPA, " ",  S002V01TUSUA_P.USUA_APMA) as NAME'),
                    'S002V01TPEEM.PEEM_IDEM as WORKTEAM_ID'
                )
                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
                ->where('S002V01TUSUA_P.USUA_NULI', '=', $line_number)
                ->join('S002V01TPERS', 'S002V01TPEEM.PEEM_IDPE', '=', 'S002V01TPERS.PERS_IDPE')
                ->join('S002V01TUSUA_P', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA_P.USUA_IDUS')
                ->get();

            // Verifica si el objeto esta vacio
            if (!isset($employees_workteam[0]) && empty($employees_workteam[0])) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_PERSONAL_EQUIPO_REG003: No se encontraron datos', $intervention_details, 500);
            }

            // Introduce el equipamiento utilizado, si es que hubo
            if (!isset($equipment_on_intervention[0]) && empty($equipment_on_intervention[0])) {
                $intervention_details->EQUIPMENT = "-";
            } else {
                $intervention_details->EQUIPMENT = $equipment_on_intervention;
            }

            // Introduce los empleados en su equipo de trabajo 
            foreach ($workteams_on_intervention as $workteam) {
                foreach ($employees_workteam as $employee) {
                    if ($workteam->WORKTEAM_ID == $employee->WORKTEAM_ID) {
                        $workteam->MEMBERS[] = $employee->NAME;
                    }
                }
            }

            $intervention_details->WORKTEAMS = $workteams_on_intervention;

            // Verifica si el objeto esta vacio
            if (!isset($images_activities[0]) && empty($images_activities[0])) {
                $intervention_details->ACTIVITIES_IMAGE_INTERVENTION = "-";
            } else {
                foreach ($images_activities as $image) {
                    $intervention_details->ACTIVITIES_IMAGE_INTERVENTION[] = $image->ACTIVITIES_IMAGE_INTERVENTION;
                }
            }

            // Verifica si el objeto esta vacio
            if (!isset($images_failures[0]) && empty($images_failures[0])) {
                $intervention_details->FAILURES_IMAGE_INTERVENTION = "-";
            } else {
                foreach ($images_failures as $image) {
                    $intervention_details->FAILURES_IMAGE_INTERVENTION[] = $image->FAILURES_IMAGE_INTERVENTION;
                }
            }

            $intervention_details->START_DATE = Carbon::create($intervention_details->START_DATE)->format("d-m-Y h:i:s A");
            $intervention_details->END_DATE = Carbon::create($intervention_details->END_DATE)->format("d-m-Y h:i:s A");

            return $this->response_controller
                ->makeResponse(FALSE, 'Consulta exitosa', $intervention_details);

        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG004: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }

    // Metodo para obtener datos de los contratos
    public function getConsultOfContracts($line_number)
    {
        try {

            $contracts = DB::table('S002V01TCONT')
                ->select(
                    'CONT_IDCO as CONTRACT_ID',
                    'CONT_TIPO as CONTRACT_TYPE',
                    'CONT_FEIN as START_DATE',
                    'CONT_FEFI as END_DATE',
                    'CONT_COST as CONTRACT_COST',
                    'CONT_FERE as REGISTER_DATE',
                    'CONT_USRE as REGISTERED_BY'
                )
                ->where('CONT_NULI', '=', $line_number)
                ->get();

            // Verifica si el objeto esta vacio
            if (!isset($contracts[0]) && empty($contracts[0])) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG001: No se encontraron datos', $contracts, 500);
            }

            $users = DB::table('S002V01TUSUA_P')
                ->select(
                    'USUA_IDUS as USER_ID',
                    DB::raw('CONCAT(USUA_NOMB, " " , USUA_APPA, " ",  USUA_APMA) as NAME')
                )
                ->where('USUA_NULI', '=', $line_number)
                ->get();

            // Verifica si el objeto esta vacio
            if (!isset($users[0]) && empty($users[0])) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_USUARIO_REG002: No se encontraron datos', $users, 500);
            }

            $employees = DB::table('S002V01TPERS')
                ->select(
                    'S002V01TPESU.PESU_RASO AS SUBCONTRATIST',
                    DB::raw('CONCAT(S002V01TUSUA_P.USUA_NOMB, " " , S002V01TUSUA_P.USUA_APPA, " ",  S002V01TUSUA_P.USUA_APMA) as EMPLOYEE'),
                    'S002V01TPERS.PERS_IDPS as TYPE_EMPLOYEE',
                    'S002V01TPECO.PECO_IDCO as CONTRACT_ID'
                )
                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
                ->where('S002V01TPESU.PESU_NULI', '=', $line_number)
                ->where('S002V01TUSUA_P.USUA_NULI', '=', $line_number)
                ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
                ->leftJoin('S002V01TPESU', 'S002V01TPERS.PERS_IDPS', '=', 'S002V01TPESU.PESU_IDPS')
                ->join('S002V01TUSUA_P', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA_P.USUA_IDUS')
                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
                ->get();

            // Verifica si el objeto esta vacio
            if (!isset($employees[0]) && empty($employees[0])) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: No se encontraron datos', $employees, 500);
            }

            // Itera los contratos para agregar a los dueños de los mismos y su duración
            foreach ($contracts as $contract) {
                $contract->DENOMINATION = [];
                $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y");
                $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y");
                $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);

                // Para establecer la duracion del contrato
                $duration = Carbon::create($contract->START_DATE)->diff($contract->END_DATE);
                $contract->DURATION = $this->resources_controller->durationDate($duration);

                $contract->REGISTER_DATE = Carbon::create($contract->REGISTER_DATE)->format("d-m-Y h:i:s A");

                foreach ($users as $user) {
                    if ($contract->REGISTERED_BY == $user->USER_ID) {
                        $contract->REGISTERED_BY = $user->NAME;
                    }
                }

                // Ingresa el nombre del propietario del contrato, si fue por medio de un subcontratista, se coloca el nombre de este
                foreach ($employees as $employee) {
                    if ($employee->CONTRACT_ID == $contract->CONTRACT_ID) {
                        if ($contract->CONTRACT_TYPE == "Subcontratista") {

                            // Evita duplicados de subcontratista
                            if (!in_array(trim($employee->SUBCONTRATIST), $contract->DENOMINATION)) {
                                $contract->DENOMINATION[] = trim($employee->SUBCONTRATIST);
                            }
                        } else {
                            $contract->DENOMINATION[] = $employee->EMPLOYEE;
                        }
                    }
                }

            }

            return $this->response_controller
                ->makeResponse(FALSE, 'Consulta exitosa', $contracts);

        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG004: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }

    // Metodo para obtener un contrato por el ID
    public function getContractById($id_contract, $line_number)
    {
        try {
            $contract = DB::table('S002V01TCONT')
                ->select(
                    'CONT_IDCO as CONTRACT_ID',
                    'CONT_TIPO as CONTRACT_TYPE',
                    'CONT_FEIN as START_DATE',
                    'CONT_FEFI as END_DATE',
                    'CONT_COST as CONTRACT_COST',
                    'CONT_LIDO as CONTRACT_DOCUMENT',
                    'CONT_FERE as REGISTER_DATE',
                    'CONT_USRE as REGISTERED_BY'
                )
                ->where('CONT_IDCO', '=', $id_contract)
                ->where('CONT_NULI', '=', $line_number)
                ->first();

            // Verifica si el objeto esta vacio
            if (!isset($contract) && empty($contract)) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG001: No se encontró el contrato', $contract, 500);
            }

            $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y h:i:s A");
            $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y h:i:s A");
            $contract->REGISTER_DATE = Carbon::create($contract->REGISTER_DATE)->format("d-m-Y h:i:s A");
            $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);
            $contract->CONTRACT_DOCUMENT = $this->encrypt_controller->encrypt($contract->CONTRACT_DOCUMENT);

            return $this->response_controller
                ->makeResponse(FALSE, 'Consulta exitosa', $contract);

        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }

    // Metodo para guardar un contrato
    public function storeContract(Request $request)
    {
        try {
            $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
            $request['CONTRACT_COST'] = $this->encrypt_controller->decrypt($request->CONTRACT_COST);

            $validator = Validator::make($request->all(), [
                "CONTRACT_TYPE" => ['required'],
                "DENOMINATION" => ['required', 'size:10'],
                "START_DATE" => ['required', 'date'],
                "END_DATE" => ['required', 'date'],
                "CONTRACT_COST" => ['required'],
                "DOCUMENT" => ['required'],
                "REGISTERED_BY_USER" => ['required', 'digits:10'],
                "LINE_NUMBER" => ['required', 'digits:1']
            ]);

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

            $user_register = DB::table('S002V01TUSUA_P')
                ->select('USUA_IDUS as ID_USER')
                ->where('USUA_IDUS', '=', $request->REGISTERED_BY_USER)
                    // ->where('USUA_NULI', '=', '01')
                ->first();

            // Verifica si el objeto esta vacio
            if (!isset($user_register) && empty($user_register)) {
                return $this->response_controller
                    ->makeResponse(TRUE, "ERR_USUARIO_REG002: Tu usuario no es válido para registrar contratos", [], 500);
            }

            DB::beginTransaction(); # Para impedir que las actualizaciones queden a incompletas

            // Busca si el empleado existe en la base de datos
            $employee_exist = DB::table('S002V01TPERS')
                ->select("PERS_IDPE")
                ->where('PERS_IDPE', '=', $request->DENOMINATION)
                    // ->where('PERS_NULI', '=', '01')
                ->first();

            // Verifica si el objeto esta vacio
            if (!isset($employee_exist) && empty($employee_exist)) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: No se encontró al empleado', [], 500);
            }

            // Para la creación del contrato y guardar su enlace
            $doc = $request->DOCUMENT;

            //$doc = $this->encrypt_controller->decrypt($request->DOCUMENT); #Para cuando este en producción, desencriptar
            // Se obtiene el nombre del archivo con su extensión
            $completeFileName = $doc->getClientOriginalName();

            // Se obtiene únicamente el nombre
            $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);

            // Se obtiene la extensión del archivo
            $extension = $doc->getClientOriginalExtension();

            // Se quitan los espacios y se concatena datos para ser guardado
            $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;

            // Se agrega la fecha actual con el formato de la nomenclatura de documentos
            $DATE_TO_DOCUMENT = Carbon::now()->timezone('America/Mexico_City')->format("ymd");

            // Verifica que el nombre del documento no sea el mismo de la generada automaticamente
            if (substr($final_part_name_document, 0, 8) == ('01-GPRS-') && strlen($final_part_name_document) > 28) {
                $final_part_name_document = substr($final_part_name_document, 28);
            }

            // Se crea el nombre del documento
            $name_document = '01-GPRS-CO-' . $DATE_TO_DOCUMENT . '-000001' . '=01=' . $final_part_name_document;

            // Verifica si el nombre de documento no existe aun
            $repeated_names = $this->documents_controller->getDocumentsWithSameCodificationStructureName($name_document, 'pdf');
            if ($repeated_names != null) {
                if ($this->documents_controller->sameDocumentsPdfOnRequest($doc, $repeated_names) != null) {
                    return $this->response_controller
                        ->makeResponse(TRUE, 'ERR_CONTRATO_REG004: Este contrato ya ha sido registrado', [], 500);
                }

                foreach ($repeated_names as $name) {
                    if ($name == $name_document) {
                        return $this->response_controller
                            ->makeResponse(TRUE, 'ERR_CONTRATO_REG005: Este nombre ya ha sido ocupado el dia de hoy', [], 500);
                    }
                }
            }

            // El contrato es guardado en el storage
            $doc->storeAs('public/pdf_documents', $name_document);

            $insert_contract = DB::table('S002V01TCONT')
                ->insert([
                    "CONT_TIPO" => $request->CONTRACT_TYPE,
                    "CONT_FEIN" => Carbon::create($request->START_DATE)->format('Y-m-d H:i:s'),
                    "CONT_FEFI" => Carbon::create($request->END_DATE)->format('Y-m-d H:i:s'),
                    "CONT_COST" => $request->CONTRACT_COST,
                    "CONT_NULI" => $request->LINE_NUMBER,
                    "CONT_LIDO" => $name_document,
                    "CONT_USRE" => $request->REGISTERED_BY_USER,
                    "CONT_FERE" => $REGISTER_DATE,
                    "CONT_FEAR" => DB::raw('CURRENT_TIMESTAMP')
                ]);


            if (!$insert_contract) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG006: Algo salió mal, error registrando el contrato', [], 500);
            }

            // Busca el id del contrato insertado
            $contract_id = DB::table('S002V01TCONT')
                ->select("CONT_IDCO as CONTRACT_ID")
                ->where("CONT_TIPO", '=', $request->CONTRACT_TYPE)
                ->where("CONT_FERE", '=', $REGISTER_DATE)
                ->where("CONT_COST", '=', $request->CONTRACT_COST)
                ->where("CONT_USRE", '=', $request->REGISTERED_BY_USER)
                ->where("CONT_LIDO", '=', $name_document)
                ->where('CONT_NULI', '=', $request->LINE_NUMBER)
                ->first();
            $contract_id = $contract_id->CONTRACT_ID;

            // Verifica si el objeto esta vacio
            if (!isset($contract_id) && empty($contract_id)) {
                DB::rollBack(); # Si no se logra insertar el contrato con empleado, se revierten los cambios previos
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG007: Algo salió mal, error buscando el contrato registrado', [], 500);
            }

            $insert_contract_with_employee = DB::table('S002V01TPECO')
                ->insert([
                    "PECO_IDPE" => $request->DENOMINATION,
                    "PECO_IDCO" => $contract_id,
                    "PECO_USRE" => $request->REGISTERED_BY_USER,
                    "PECO_NULI" => $request->LINE_NUMBER,
                    "PECO_FERE" => $REGISTER_DATE,
                    "PECO_FEAR" => DB::raw('CURRENT_TIMESTAMP')
                ]);

            if (!$insert_contract_with_employee) {
                DB::rollBack(); # Si no se logra insertar el contrato con empleado, se revierten los cambios previos
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_CONTRATO_PERSONAL_REG008: Algo salió mal, error registrando el contrato con el empleado', [], 500);
            }

            DB::commit(); # Para guardar los cambios en la base de datos
            return $this->response_controller->makeResponse(FALSE, 'Registro exitoso', 200);


        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_CONTRATO_REG009: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }

    // Metodo para obtener un contrato por el ID
    public function getAllContracts($line_number)
    {
        try {
            $contracts = DB::table('S002V01TCONT')
                ->select(
                    'CONT_IDCO as CONTRACT_ID',
                    'CONT_TIPO as CONTRACT_TYPE',
                    'CONT_FEIN as START_DATE',
                    'CONT_FEFI as END_DATE',
                    'CONT_COST as CONTRACT_COST',
                    'CONT_LIDO as CONTRACT_DOCUMENT',
                    'CONT_FERE as REGISTER_DATE',
                    'CONT_USRE as REGISTERED_BY'
                )
                ->where('CONT_NULI', '=', $line_number)
                ->get();

            // Verifica si el objeto esta vacio
            if (!isset($contracts[0]) && empty($contracts[0])) {
                return $this->response_controller
                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG001: No se encontró el contrato', $contracts, 500);
            }

            foreach ($contracts as $contract) {
                $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y h:i:s A");
                $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y h:i:s A");
                $contract->REGISTER_DATE = Carbon::create($contract->REGISTER_DATE)->format("d-m-Y h:i:s A");
                $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);
                $contract->CONTRACT_DOCUMENT = $this->encrypt_controller->encrypt($contract->CONTRACT_DOCUMENT);
            }

            return $this->response_controller
                ->makeResponse(FALSE, 'Consulta exitosa', $contracts);

        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }

}

