<?php

namespace App\Http\Controllers;

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

class CountersActivatorsController extends Controller{
    private $responseController;
    private $encryptionController;
    private $functionsController;

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición 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);
        }
        
        $activators = DB::table('S002V01TACTI')->select([
            'ACTI_IDCO AS IDCONTADOR',
            'ACTI_PRIO AS PRIORIDAD',
            'ACTI_TIAC AS TIPOACTIVACION',
            'ACTI_COAC AS CONDICIONES'
        ])->where([
            ['ACTI_NULI', '=', $line],
            ['ACTI_TIAC', '=', $type]
        ])->get()->all();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M06COAC',
            'S002V01F01GEAC',
            'S002V01P01COAC',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contadores de tipo $type.",
            $idUser,
            $nowStr,
            'S002V01S02ACTI'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeresponse(false, "EXITO", $activators);
    }

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

        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'priority' => 'required|string|in:1,2,3,4',
            'type' => 'required|string|in:CA,SI,ME,VA',
            'condition' => 'required|json',
        ]);

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

        //$priorities = ['MA' => '1', 'AL' => '2', 'ME' => '3', 'BA' => '4'];
        $types = ['CA' => 'Calendario', 'SI' => 'Sintoma', 'ME' => 'Medida', 'VA' => 'Valor'];
        $form = $request->all();

        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición 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);
        }

        $priority = $form['priority'];
        $type = $types[$form['type']];
        
        $nowStr = Carbon::now('America/Guatemala')->toDateTimeString();
        $idCont = DB::table('S002V01TACTI')->insertGetId([
            'ACTI_NULI' => $form['linea'],
            'ACTI_PRIO' => $priority,
            'ACTI_TIAC' => $type,
            'ACTI_COAC' => $form['condition'],
            'ACTI_USRE' => $idUser,
            'ACTI_FERE' => $nowStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M06COAC',
            'S002V01F01GEAC',
            'S002V01P02REAC',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró el contador #$idCont.",
            $idUser,
            $nowStr,
            'S002V01S02ACTI'
        );

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición 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);
        }
        
        $idActivator = $this->encryptionController->shortDec($idActivator);
        if(!$idActivator){
            return $this->responseController->makeResponse(true, 'El ID del activador solicitado no está encriptado correctamente.', [], 400);
        }
        
        $activator = DB::table('S002V01TACTI')->select([
            'ACTI_IDCO AS IDACTIVADOR',
            'ACTI_PRIO AS PRIORIDAD',
            'ACTI_TIAC AS TIPOACTIVADOR',
            'ACTI_COAC AS CONDICIONES',
            'ACTI_USRE AS USRREG',
            'ACTI_FERE AS FECREG',
            'ACTI_USMO AS USRMOD',
            'ACTI_FEMO AS FECMOD',
        ])->where([
            ['ACTI_IDCO', '=', $idActivator],
            ['ACTI_NULI', '=', $line],
        ])->first();

        if(is_null($activator)){
            return $this->responseController->makeResponse(true, 'El activador solicitado 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,
            'S002V01M06COAC',
            'S002V01F01GEAC',
            'S002V01P01COAC',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la información del activador #$idActivator",
            $idUser,
            $nowStr,
            'S002V01S02ACTI'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeresponse(false, "EXITO", $activator);
    }
}