<?php

namespace App\Http\Controllers;

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

class SystemAdministratorController 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 getLastConnections($idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

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

        $lastConnections = DB::table('S002V01TUSUA')->leftJoin('S002V01TBIAC', 'USUA_ULCO', '=', 'BIAC_IDCO')->select(
            'USUA_IDUS AS IDUSUARIO',
            'BIAC_FECO AS ULCON'
        )->get()->all();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

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

    public function setLastConnection(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id' => 'required|string',
            'linea' => 'required|integer',
            'lugarConexion' => 'required|json'
        ]);

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

        $user = $request->all();

        $idUser = $this->encryptionController->decrypt($user['id']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "La ID del usuario no está encriptado correctamente.", [], 400);
        }

        $now = Carbon::now('America/Mexico_city');
        $nowStr = $now->toDateTimeString();
        $ipv = $request->ip();

        
        $idLastConn = DB::table('S002V01TBIAC')->insertGetId([
            'BIAC_NULI' => $user['linea'],
            'BIAC_IDUS' => $user['linea'],
            'BIAC_DIIP' => $ipv,
            'BIAC_LUCO' => $user['lugarConexion'],
            'BIAC_FECO' => $nowStr
        ]);

        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->update(['USUA_ULCO' => $idLastConn]);

        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $user['linea']);
        return $this->responseController->makeResponse(false, "EXITO: Actualización correcta.");
    }

    public function getCatalogues($idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

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

        $catalogues = DB::table('S002V01TCATA')->select(
            'CATA_IDCA AS IDCATALOGO',
            'CATA_NOCA AS NOMBRECATALOGO',
            'CATA_VERS AS VERSION'
        )->get()->all();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

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

    //Pendiente
    public function registerCatalogue(Request $request){
        if(!$request->hasFile('xls')){
            return $this->responseController->makeResponse(true, "No se envió ningún archivo.", [], 400);
        }

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

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

        $form = $request->all();
        $allowedFiles = ["Colonias", "Códigos postales", "Estados", "Localidades", "Municipios"];
        if(!in_array($form['type'], $allowedFiles)){
            return $this->responseController->makeResponse(true, "El tipo de catálogo no está soportado.", [], 400);
        }

        $file = $request->file('xls');
        $ext = $request->file('xls')->getClientOriginalName();
        $extArr = explode(".", $ext);
        $extStr = end($extArr);

        if(!($extStr == "xls" || $extStr == "xlsx")){
            return $this->responseController->makeResponse(true, "La extensión del archivo no está soportada.", [], 400);
        }

        require '../../../spreadsheet/vendor/autoload.php';
        var_dump($extStr);
    }

    public function getUserConnections($id, $idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

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

        $id = $this->encryptionController->decrypt($id);
        if(!$id){
            return $this->responseController->makeResponse(true, "El id del usuario que desea consultar no está encriptado correctamente.", [], 400);
        }

        $userInfo = DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $id)->get()->first();
        if(is_null($userInfo)){
            return $this->responseController->makeResponse(true, "El usuario que desea consultaro no existe.", [], 404);
        }

        $connections = DB::table('S002V01TBIAC')->select(
            'BIAC_DIIP AS IP',
            'BIAC_LUCO AS LUGAR',
            'BIAC_FECO AS FECHA'
        )->where('BIAC_IDUS', '=', $id)->orderBy('BIAC_FECO', 'desc')->get()->all();

        $responseArr = [
            'NOMBRE' => $userInfo->USUA_NOMB,
            'APPAT' => $userInfo->USUA_APPA,
            'APMAT' => $userInfo->USUA_APMA,
            'ULTCON' => $userInfo->USUA_ULCO,
            'HISTORIAL' => $connections
        ];

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeResponse(false, "EXITO", $responseArr);
    }

    public function getLastActions($idUser, $line){
        $idUser = $this->encryptionController->decrypt($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El ID el usuario que realizó la petición no está encriptado correctamente.", [], 400);
        }

        $tiposAcciones = ['READ' => 'Lectura de datos', 'UPDATE' => 'Actualización de datos', 'CREATE' => 'Registro de información', 'DELETE' => 'Eliminación de datos'];
        $lastActions = DB::table('S002V01TUSUA')->leftJoin('S002V01TACCI', 'USUA_ULAC', '=', 'ACCI_IDAC')->select(
            'USUA_IDUS AS IDUSUARIO',
            'ACCI_TIAC AS TIPOACCION',
            'ACCI_FEAC AS FECHA'
        )->get()->all();

        foreach($lastActions as $action){
            if(is_null($action->TIPOACCION)){
                $action->TIPOACCION = '-';
            }else{
                $action->TIPOACCION = $tiposAcciones[$action->TIPOACCION];
            }
        }

        return $this->responseController->makeResponse(false, 'EXITO', $lastActions);
    }

    public function getUserActions($id, $idUser, $line){
        $id = $this->encryptionController->decrypt($id);
        if(!$id){
            return $this->responseController->makeResponse(true, 'El ID del usuario que desea consultar no está encriptado correctamente.', [], 400);
        }

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

        $userInfo = DB::table('S002V01TUSUA')->select(
            'USUA_IDUS AS IDUSUARIO',
            'USUA_NOMB AS NOMBRE',
            'USUA_APPA AS APEPAT',
            'USUA_APMA AS APEMAT'
        )->where('USUA_IDUS', '=', $id)->get()->first();

        if(is_null($userInfo)){
            return $this->responseController->makeResponse(true, 'El usuario solicitado no existe.', [], 404);
        }

        $actions = DB::table('S002V01TACCI')->select(
            'ACCI_COAC AS CODIGO',
            'ACCI_TIAC AS TIPOACCION',
            'ACCI_QUER AS SCRIPT',
            'ACCI_PARA AS PARAMETROS',
            'ACCI_FEAC AS FECHA'
        )->where('ACCI_IDUS', '=', $id)->get()->all();

        $actionTypes = ['READ' => 'Lectura de datos', 'UPDATE' => 'Actualización de datos', 'CREATE' => 'Registro de información', 'DELETE' => 'Eliminación de datos'];
        foreach($actions as $action){
            $action->TIPOACCION = $actionTypes[$action->TIPOACCION];
        }

        $userInfo->HISTORIAL = $actions;
        
        return $this->responseController->makeResponse(false, 'EXITO', $userInfo);
    }
}