<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\EncController;

class MCOMBAController extends Controller{
    public function getLogs($inicio, $numRegs, $rfce, $nonce){
        $pdo = DB::connection()->getPdo();
        $encController = new EncController();
        $rfce = $encController->desencriptar(base64_encode($rfce . "|" . $nonce));
        $qry  = 'SELECT BIAC_IDBI AS IDBITACORA, USUA_IDUS AS IDUSUARIO, CONCAT(USUA_NOMB, " ", USUA_APPA, " ", IF(ISNULL(USUA_APMA), "", USUA_APMA)) AS NOMBRE, 
        USUA_RFCU AS RFCUSUARIO, USUA_COEL AS EMAIL, BIAC_IPUS AS IPACCESO, BIAC_FEAR AS FECHAACCESO FROM S001V01TBIAC INNER JOIN S001V01TUSUA ON BIAC_IDUS = USUA_IDUS  
        WHERE BIAC_RFCE = :rfce ORDER BY BIAC_IDBI LIMIT :inicio, :numRegs';
        $gst = $pdo->prepare($qry);

        $gst->bindParam(":rfce", $rfce);
        $gst->bindParam(":inicio", $inicio);
        $gst->bindParam(":numRegs", $numRegs);
        
        if (!$gst->execute()) {
            return $this->makeResponse(true, "ERR_MCOMBA_SER_GLO000: No se ejecutó la consulta de los accesos.", [], 500);
        }

        $accesos = $gst->fetchAll($pdo::FETCH_ASSOC);
        $accesosF = array();
        foreach($accesos as $acceso){
            if(str_contains($acceso['NOMBRE'], "-")){
                $acceso['NOMBRE'] = str_replace("-", "", $acceso['NOMBRE']);
            }
            $acceso['NOMBRE'] = trim($acceso['NOMBRE']);
            $accesosF[] = $acceso;
        }
        
        return $this->makeResponse(false, "EXITO", $accesosF);
    }

    public function getNumLogs($rfce, $nonce){
        $pdo = DB::connection()->getPdo();
        $encController = new EncController();
        $rfce = $encController->desencriptar(base64_encode($rfce . "|" . $nonce));
        $qry = "SELECT COUNT(BIAC_IDBI) AS NUMEROREGISTROS FROM S001V01TBIAC INNER JOIN S001V01TUSUA ON BIAC_IDUS = USUA_IDUS WHERE BIAC_RFCE = :rfce ORDER BY BIAC_IDBI";
        $gst = $pdo->prepare($qry);
        $gst->bindParam(":rfce", $rfce);

        if (!$gst->execute()) {
            return $this->makeResponse(true, "ERR_MCOMBA_SER_GNL000: No se ejecutó la consulta del número de accesos.", [], 500);
        }

        $numAccesos = $gst->fetchObject();
        return $this->makeResponse(false, "EXITO", $numAccesos);
    }

    private function makeResponse($error, $msg, $response = [], $code = 200){
        $respuesta = json_encode([
            "error" => $error,
            "msg" => $msg,
            "response" => $response
        ]);

        return response($respuesta, $code)->header('Content-Type', 'application/json');
    }

}

//SELECT USUA_IDUS AS IDUSUARIO, CONCAT(USUA_NOMB, " ", USUA_APPA, " ", IF(ISNULL(USUA_APMA), "", USUA_APMA)) AS NOMBRE, USUA_RFCU AS RFCUSUARIO, USUA_COEL AS EMAIL, BIAC_IPUS AS IPACCESO, BIAC_FEAR AS FECHAACCESO FROM S001V01TBIAC INNER JOIN S001V01TUSUA ON BIAC_IDUS = USUA_IDUS ORDER BY BIAC_IDBI
