<?php

namespace App\Http\Controllers;

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

use App\Http\Controllers\EncController;

class MCOMAPController extends Controller{
    public function create(Request $request){
        $validator = Validator::make($request->all(), [
            'rfc_empresa' => 'required|string',
            'tipo_perfil' => 'required|string|max:50',
            'id_usuario_registra' => 'required|string|max:50',
        ]);

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

        $perfil = $request->all();

        $encController = new EncController();
        $rfce = $encController->desencriptar($perfil['rfc_empresa']);
        $hoy = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();

        $pdo = DB::connection()->getPdo();
        $qryIns = "INSERT INTO S001V01TPERF (PERF_RFCE, PERF_TIPE, PERF_USRE, PERF_FERE, PERF_FEAR) VALUES(:rfce, :tipe, :usre, :fere, CURRENT_TIMESTAMP)";
        $gstIns = $pdo->prepare($qryIns);
    
        $gstIns->bindParam(":rfce", $rfce);
        $gstIns->bindParam(":tipe", $perfil['tipo_perfil']);
        $gstIns->bindParam(":usre", $perfil['id_usuario_registra']);
        $gstIns->bindParam(":fere", $hoy);

        if(!$gstIns->execute()){
            return $this->makeResponse(true, "ERR_MCOMAP_SER_CRE001: No se pudo realizar la inserción del perfil a la base", [], 500);
        }

        return $this->makeResponse(false, "EXITO: Perfil creado");
    }

    public function update(Request $request){
        $validator = Validator::make($request->all(), [
            'id_perfil' => 'required|string',
            'tipo_perfil' => 'required|string|max:50',
            'id_usuario_modifica' => 'required|string|max:50',
        ]);

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

        $perfil = $request->all();
        $hoy = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();

        $pdo = DB::connection()->getPdo();
        $qryRFCE = "SELECT USUA_RFCE FROM S001V01TUSUA WHERE USUA_IDUS = :idus";
        $gstRFCE = $pdo->prepare($qryRFCE);
        $gstRFCE->bindParam(":idus",$perfil['id_usuario_modifica']);

        $gstRFCE->execute();
        $rfce = $gstRFCE->fetchObject()->USUA_RFCE;

        $qryIns = "UPDATE S001V01TPERF SET PERF_TIPE = :tipe, PERF_USMO = :usmo, PERF_FEMO = :femo, PERF_FEAR = CURRENT_TIMESTAMP 
        WHERE PERF_IDPE = :idpe AND PERF_RFCE = :rfce";
        $gstIns = $pdo->prepare($qryIns);
    
        $gstIns->bindParam(":tipe", $perfil['tipo_perfil']);
        $gstIns->bindParam(":usmo", $perfil['id_usuario_modifica']);
        $gstIns->bindParam(":femo", $hoy);
        $gstIns->bindParam(":idpe", $perfil['id_perfil']);
        $gstIns->bindParam(":rfce", $rfce);

        if(!$gstIns->execute()){
            return $this->makeResponse(true, "ERR_MCOMAP_SER_UPD001: No se pudo realizar la modificación del perfil a la base", [], 500);
        }

        return $this->makeResponse(false, "EXITO: Perfil modificado");
    }

    public function delete(Request $request){
        $validator = Validator::make($request->all(), [
            'id_perfil' => 'required|string',
            'id_usuario_elimina' => 'required|string|max:50',
        ]);

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

        $perfil = $request->all();
        $hoy = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();

        $pdo = DB::connection()->getPdo();
        $qryRFCE = "SELECT USUA_RFCE FROM S001V01TUSUA WHERE USUA_IDUS = :idus";
        $gstRFCE = $pdo->prepare($qryRFCE);
        $gstRFCE->bindParam(":idus",$perfil['id_usuario_elimina']);
        $gstRFCE->execute();
        $rfce = $gstRFCE->fetchObject()->USUA_RFCE;

        $qryIns = "UPDATE S001V01TPERF SET PERF_ESTA = 'Eliminado', PERF_USMO = :usmo, PERF_FEMO = :femo, PERF_FEAR = CURRENT_TIMESTAMP WHERE 
        PERF_IDPE = :idpe AND PERF_RFCE = :rfce";
        $gstIns = $pdo->prepare($qryIns);
    
        $gstIns->bindParam(":usmo", $perfil['id_usuario_elimina']);
        $gstIns->bindParam(":femo", $hoy);
        $gstIns->bindParam(":idpe", $perfil['id_perfil']);
        $gstIns->bindParam(":rfce", $rfce);

        if(!$gstIns->execute()){
            return $this->makeResponse(true, "ERR_MCOMAP_SER_DEL001: No se pudo realizar la eliminación del perfil a la base", [], 500);
        }

        return $this->makeResponse(false, "EXITO: Perfil eliminado");
    }

    public function getPerfiles($rfce, $nonce){
        $pdo = DB::connection()->getPdo();
        $encController = new EncController();
        $rfce = $encController->desencriptar(base64_encode($rfce . "|" . $nonce));

        $qry = "SELECT PERF_IDPE, PERF_TIPE FROM S001V01TPERF WHERE PERF_ESTA = 'Activo' AND PERF_RFCE = :rfce";
        $gst = $pdo->prepare($qry);
        $gst->bindParam(":rfce", $rfce);
        
        if(!$gst->execute()){
            return $this->makeResponse(true, "ERR_MCOMAP_SER_GPS000: No se pudo realizar la consulta a la base", [], 500);
        }

        $perfiles = $gst->fetchAll($pdo::FETCH_ASSOC);
        $perfilesF = array();

        foreach($perfiles as $perfil){
            $perfilesF[] = [
                "id" => $perfil['PERF_IDPE'],
                "perfil" => $perfil['PERF_TIPE'],
            ];
        }
        
        return $this->makeResponse(true, "EXITO", $perfilesF);
    }

    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');
    }

    private function makeErrors($erroresObj){
        $erroresArr = array();

        foreach ($erroresObj as $key => $value) {
            foreach ($value as $key0 => $value0) {
                if(array_key_exists($key, $erroresArr)){
                    $val = $erroresArr[$key] . "|" . $value0;
                    $erroresArr[$key] = $val;
                }else{
                    $erroresArr[$key] = $value0;
                }
            }
        }

        return $erroresArr;
    }
}