MINI MINI MANI MO

Path : /var/www/html/sistemas/spid/app/Http/Controllers/
File Upload :
Current File : /var/www/html/sistemas/spid/app/Http/Controllers/PlenoController.php

<?php

namespace App\Http\Controllers;

use App\Models\actaSesion;
use App\Models\asistenciaVotos;
use App\Models\AsuntosOrdenDia;
use App\Models\DatosUsers;
use App\Models\EventoVotos;
use App\Models\mensajesVotos;
use App\Models\OrdenDia;
use App\Models\temasVotos;
use App\Models\User;
use Dflydev\DotAccessData\Data;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Symfony\Component\HttpFoundation\StreamedResponse;

class PlenoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $eventoActivo = EventoVotos::where('estatus', 1)->get();
        if (count($eventoActivo)) {
            $temaVotos = temasVotos::where('status', 1)->get();
            $votacion = mensajesVotos::where('status', 1)->get();
            $favor = 0;
            $contra = 0;
            $abstencion = 0;
            $totalVotos = 0;
            $totalAsistencias = 0;
            foreach ($votacion as $voto) {
                if ($voto->mensaje == 'FAVOR') {
                    $favor = $favor + 1;
                } elseif ($voto->mensaje == 'CONTRA') {
                    $contra = $contra + 1;
                } elseif ($voto->mensaje == 'ABSTENCION') {
                    $abstencion = $abstencion + 1;
                }
                $totalVotos = $favor + $contra + $abstencion;
            }
            $asistencias = asistenciaVotos::where('status', 1)->where('randomEvento', $eventoActivo[0]->random)->orderBy('id_diputado', 'ASC')->get();

            foreach ($asistencias as $asiste) {
                if ($asiste->mensaje == 'ASISTENCIA') {
                    $totalAsistencias = $totalAsistencias + 1;
                }
            }

            //            $turnos = Turnos::where('status',1)->where('randomEvento',$eventoActivo[0]->random)->orderBy('created_at', 'ASC')->get();

            return view("sistemaVotos.sistemaPleno", compact('eventoActivo', 'votacion', 'favor', 'contra', 'abstencion', 'totalVotos', 'asistencias', 'totalAsistencias', 'temaVotos'));
        } else {
            return view('sistemaVotos.aviso');
        }
    }

    public function curul()
    {
        $eventoActivo = EventoVotos::where('estatus', 1)->get();
        $favor = 0;
        $contra = 0;
        $abstencion = 0;
        $totalVotos = 0;
        $totalAsistencias = 0;

        if (count($eventoActivo)) {
            $temaVotos = temasVotos::where('status', 1)->get();
            $votacion = mensajesVotos::where('status', 1)->get();
            foreach ($votacion as $voto) {
                if ($voto->mensaje == 'FAVOR') {
                    $favor = $favor + 1;
                } elseif ($voto->mensaje == 'CONTRA') {
                    $contra = $contra + 1;
                } elseif ($voto->mensaje == 'ABSTENCION') {
                    $abstencion = $abstencion + 1;
                }
                $totalVotos = $favor + $contra + $abstencion;
            }
            $asistencias = asistenciaVotos::where('status', 1)->where('randomEvento', $eventoActivo[0]->random)->orderBy('id_diputado', 'ASC')->get();

            foreach ($asistencias as $asiste) {
                if ($asiste->mensaje == 'ASISTENCIA') {
                    $totalAsistencias = $totalAsistencias + 1;
                }
            }

            //            $turnos = Turnos::where('status',1)->where('randomEvento',$eventoActivo[0]->random)->orderBy('created_at', 'ASC')->get();
        } else {
            $votacion = [];
            $asistencias = [];
            $temaVotos = [];
        }
        return view("sistemaVotos.sistemaPlenoV", compact('eventoActivo', 'votacion', 'favor', 'contra', 'abstencion', 'totalVotos', 'asistencias', 'totalAsistencias', 'temaVotos'));

    }

    public function getTema(){
        $tema = temasVotos::where('status', 1)->first();
        return $tema['votacion'];
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function validaEventosPleno(){
        $eventoActivo = EventoVotos::where('estatus', 1)->first();
        if(!$eventoActivo){
            $response[] = array(
                "evento"=> '0',
            );
            return json_encode($response);
        }else {
            $votacion = mensajesVotos::where('status', 1)->where('randomEvento', $eventoActivo->random)->get();
            $asistencias = asistenciaVotos::where('status', 1)->where('randomEvento', $eventoActivo->random)->get();
            if (count($votacion) > 0){
                $vot = 1;
                $asis = 0;
            }else if (count($asistencias) > 0){
                $vot = 0;
                $asis = 1;
            }else{
                $vot = 0;
                $asis = 0;
            }

            $response[] = array(
                "evento"=> '1',
                "asistencias" => $asis,
                "votacion" => $vot,
            );
//            dd($response);
            return json_encode($response);
        }
    }

    public function asistenciasPleno(){
        $evento = EventoVotos::where('estatus',1)->first();
        $votacion = DB::select("SELECT  m.id_diputado, d.nombre, d.ap_pat, d.ap_mat, m.mensaje FROM asistencia_votos AS m, datos_users AS d WHERE m.id_diputado=d.id AND m.status=1  and m.randomEvento = '".$evento['random']."' order  by d.ap_pat, d.ap_mat ASC");
        foreach($votacion as $e){
            $response[] = array(
                "id"=>$e->id_diputado,
                "name"=>$e->nombre,
                "ap_pat"=>$e->ap_pat,
                "ap_mat"=>$e->ap_mat,
                "mensaje"=>$e->mensaje,
            );
        }
        // dd(json_encode($response));
        return json_encode($response);
    }

    public function totalAsisPleno(){
        $asistenciast = asistenciaVotos::where('status',1)->where('mensaje','ASISTENCIA')->get();
        $asistenciast= count($asistenciast);
        $tiempo = asistenciaVotos::where('status',1)->first();

        $response[] = array(
            "asistenciast"=>$asistenciast,
            "tiempo"=>$tiempo->tiempoVotacion,

        );
        return json_encode($response);
    }

    public function votosPleno(){

        $votacion = DB::select("SELECT  m.id_diputado, d.nombre, d.ap_pat, d.ap_mat, m.mensaje FROM mensajes_votos AS m, datos_users AS d WHERE m.id_diputado=d.id AND m.status=1  order by ap_pat,ap_mat ASC");

        foreach($votacion as $e){
            $response[] = array(
                "id"=>$e->id_diputado,
                "name"=>$e->nombre,
                "ap_pat"=>$e->ap_pat,
                "ap_mat"=>$e->ap_mat,
                "mensaje"=>$e->mensaje,
            );
        }
        return json_encode($response);
    }

    public function totalVotosPleno(){
        $votacion= mensajesVotos::where('status',1)->get();
        $votacionFavor = 0;
        $votacionContra = 0;
        $votacionAbsten = 0;

        foreach ($votacion as $v){
            if($v->mensaje == 'FAVOR'){
                $votacionFavor = $votacionFavor +1;
            }

            if($v->mensaje == 'CONTRA'){
                $votacionContra = $votacionContra +1;
            }

            if($v->mensaje == 'ABSTENCION'){
                $votacionAbsten = $votacionAbsten +1;
            }
        }

        $totalVotos = $votacionFavor + $votacionContra + $votacionAbsten;
        $response[] = array(
            "votacionFavor"=>$votacionFavor,
            "votacionContra"=>$votacionContra,
            "votacionAbsten"=>$votacionAbsten,
            "totalVotos"=>$totalVotos,
            "tiempo" => $votacion[0]->temaVoto->tiempoVotacion,
        );
        return json_encode($response);
    }

    public function comprobarHuellaPleno(Request $request){
        if ($request->has('imagen')) {
            $imagen = $request->input('imagen');
            $imagen = str_replace('data:image/png;base64,', '', $imagen);
            $imagen = str_replace(' ', '+', $imagen);
            $imagen = base64_decode($imagen);

            $uuid = str::uuid();
            $ruta = public_path('/huellasLog/' . $uuid . '.png');
            file_put_contents($ruta, $imagen);

            $imagePath = 'huellasLog/' . $uuid . '.png';

            $client = new Client([
                'headers' => ['Content-Type' => 'application/json']
            ]);

            $data = array(
                "path" => $imagePath
            );
            try {
                $response = $client->post('http://192.168.36.56:8084/comparar', [
                    'json' => $data
                ]);
                $body = $response->getBody()->getContents();
            } catch (\GuzzleHttp\Exception\BadResponseException $e) {
                $body = $e->getResponse()->getBody()->getContents();
            }
//            $body = 2;
            if ($body == 0){
                Storage::disk('public')->delete($imagePath);
                return 0;
            }else{
                $user = User::find($body);
                $idDip = $user->DatosUsers->id;
                return $idDip;
            }
        }
    }

    public function accionHuella(Request $request){
        $datos = $request->except('_method', '_token');
        $dip = DatosUsers::find($datos['idDip']);
        if ($datos['tipoBoton'] == 'asistencia'){
            $as = asistenciaVotos::where('id_diputado', $datos['idDip'])->where('status', 1)->first();
            if ($as){
                $up['mensaje'] = 'ASISTENCIA';
                $up['usuario_registra'] = $datos['idDip'];
                $as->update($up);
                $return = 1;
            }else{
                $return = 0;
            }
        }else{
            $voto = mensajesVotos::where('id_diputado', $datos['idDip'])->where('status', 1)->first();
            if ($voto){
                if ($datos['tipoBoton'] == 'favor'){
                    $up['mensaje'] = 'FAVOR';
                    $up['usuario_registra'] = $datos['idDip'];
                    $voto->update($up);
                    $return = 2;
                }else if ($datos['tipoBoton'] == 'contra'){
                    $up['mensaje'] = 'CONTRA';
                    $up['usuario_registra'] = $datos['idDip'];
                    $voto->update($up);
                    $return = 2;
                }else if ($datos['tipoBoton'] == 'abstencion'){
                    $up['mensaje'] = 'ABSTENCION';
                    $up['usuario_registra'] = $datos['idDip'];
                    $voto->update($up);
                    $return = 2;
                }else if ($datos['tipoBoton'] == 'sinregistro'){
                    $up['mensaje'] = 'SIN REGISTRO';
                    $up['usuario_registra'] = $datos['idDip'];
                    $voto->update($up);
                    $return = 2;
                }
            }else{
                $return = 0;
            }
        }


        $response = [
            'return' => $return,
            'dip' => $dip['nombre'].' '.$dip['ap_pat'].' '.$dip['ap_mat']
        ];

        return $response;
    }

    public function getAsuntosPleno(){
        $evento = EventoVotos::where('estatus', 1)->first();
        return view('sistemaVotos.indexAsuntos', compact('evento'));
    }

    public function getAsuntoPleno(Request $request)
    {
        $id = $request['id'];
        $asunto = AsuntosOrdenDia::find($id);
        $url = $asunto->path_asuntos;
        return $url;
    }

    public function getActasPleno(){
        $evento = EventoVotos::where('estatus', 1)->first();
        $url = '';
        if ($evento){
            $acta = actaSesion::where('id_evento', $evento->id)->where('status', 1)->first();
            if ($acta){
                $url = $acta->path_acta;
            }
        }

        return view('sistemaVotos.indexActa', compact('url'));
    }

    public function getOrdenPleno(){
        $evento = EventoVotos::where('estatus', 1)->first();
        $url = '';
        if ($evento){
            $acta = OrdenDia::where('id_evento', $evento->id)->where('status', 1)->first();
            if ($acta){
                $url = $acta->path_orden;
            }
        }

        return view('sistemaVotos.indexOrden', compact('url'));
    }

    public function cronometro(Request $request){
        return view("sistemaVotos.control");
    }

    public function Createcronometro(Request $request){
        return view("cronometro.form");
    }

   public function validacionEventoStream()
    {
        return response()->stream(function () {

            @ini_set('zlib.output_compression', '0');
            @ini_set('output_buffering', '0');
            @ini_set('implicit_flush', '1');

            while (ob_get_level() > 0) { @ob_end_flush(); }
            @ob_implicit_flush(true);

            // padding inicial para abrir stream
            echo ":" . str_repeat(" ", 2048) . "\n\n";
            echo "retry: 2000\n\n";

            // evento inmediato (IMPORTANTE)
            echo "event: ready\n";
            echo "data: " . json_encode([
                "ok" => true,
                "ts" => date('c')
            ], JSON_UNESCAPED_UNICODE) . "\n\n";

            @ob_flush(); @flush();

            $lastHash = null;
            $lastPing = microtime(true);

            while (true) {
                if (connection_aborted()) break;

                $data = $this->validacionEvento();

                $hash = md5(json_encode($data));
                if ($hash !== $lastHash) {
                    $lastHash = $hash;

                    echo "event: evento\n";
                    echo "data: " . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
                    @ob_flush(); @flush();
                }

                // ping cada 15s
                if (microtime(true) - $lastPing > 15) {
                    echo "event: ping\n";
                    echo "data: {}\n\n";
                    @ob_flush(); @flush();
                    $lastPing = microtime(true);
                }

                usleep(150000); // 150 ms
            }
        }, 200, [
            'Content-Type' => 'text/event-stream; charset=UTF-8',
            'Cache-Control' => 'no-cache, no-transform',
            'Connection' => 'keep-alive',
        ]);
    }

    public function validacionEvento(){
        $evento = EventoVotos::where('estatus', 1)->first();

        if($evento){
            $asiatencia = asistenciaVotos::where('status', 1 )->where('randomEvento', $evento->random)->first();
            $voto = temasVotos::where('status', 1)->where('randomEvento', $evento->random)->first();
            if ($asiatencia){
                $response = [
                    'bandera' => 2,
                ];
            }else if ($voto){
                $response = [
                    'bandera' => 3,
                    'tema' => $voto->votacion
                ];
            }else{
                $response = [
                    'bandera' => 1,
                ];
            }
        }else{
            $response = [
                'bandera' => 0,
            ];
        }
        return $response;
    }

    public function validacionUser(Request $request){
        $datos = $request->except('_method','_token');
        $user = User::where('username', $datos['email'])->first();
        if($user){
            if (Hash::check($datos['psw'], $user->password)) {
                $response = [
                    'bandera' => 2,
                    'id_diputado' => $user->id,
                    'nombre' => $user->DatosUsers->nombre_completo
                ];
            }else{
                $response = [
                    'bandera' => 1,
                    'msj' => 'ContraseƱa incorrecta',
                ];
            }
        }else{
            $response = [
                'bandera' => 0,
                'msg' => 'El correo no existe'
            ];
        }
        return $response;
    }

    public function asistenciaDip(Request $request){
        $datos = $request->except('_method','_token');
        $user = User::find($datos['id']);
        $evento = EventoVotos::where('estatus', 1)->first();
        if ($evento){
            $asistencia = asistenciaVotos::where('randomEvento', $evento->random)->where('id_diputado', $user->DatosUsers->id)->first();
            if ($asistencia){
                $up['mensaje'] = 'ASISTENCIA';
                $up['usuario_registra'] = $user->DatosUsers->id;
                $asistencia->update($up);
                $response = [
                    'bandera' => 2,
                    'msg' => 'Asistencia registrada correctamente'
                ];
            }else{
                $response = [
                    'bandera' => 1,
                    'msg' => 'No hay asistencia activa'
                ];
            }
        }else{
            $response = [
                'bandera' => 0,
                'msg' => 'No hay evento disponible'
            ];
        }
        return $response;
    }

    public function votoDip(Request $request){
        $datos = $request->except('_method','_token');
        $user = User::find($datos['id']);
        $evento = EventoVotos::where('estatus', 1)->first();
        if ($evento){
            $tema = temasVotos::where('randomEvento', $evento->random)->where('status', 1)->first();
            if ($tema){
                $voto = mensajesVotos::where('id_votacion', $tema->id)->where('id_diputado', $user->DatosUsers->id)->first();
                $up['mensaje'] = $datos['sentido'];
                $up['usuario_registra'] = $user->DatosUsers->id;
                $voto->update($up);
                $response = [
                    'bandera' => 2,
                    'msg' => 'Voto registrado correctamente'
                ];
            }else{
                $response = [
                    'bandera' => 1,
                    'msg' => 'No hay votos activos'
                ];
            }
        }else{
            $response = [
                'bandera' => 0,
                'msg' => 'No hay evento disponible'
            ];
        }
        return $response;
    }

    public function asistenciaDipNom(Request $request){
        $datos = $request->except('_method','_token');
        $user = DatosUsers::where('nombre_db', $datos['nombre'])->first();
        $evento = EventoVotos::where('estatus', 1)->first();
        if ($evento){
            if ($user) {
                $asistencia = asistenciaVotos::where('randomEvento', $evento->random)->where('id_diputado', $user->id)->first();
                if ($asistencia) {
                    $up['mensaje'] = 'ASISTENCIA';
                    $up['usuario_registra'] = $user->DatosUsers->id;
                    $asistencia->update($up);
                    $response = [
                        'bandera' => 3,
                        'msg' => 'Asistencia registrada correctamente'
                    ];
                } else {
                    $response = [
                        'bandera' => 2,
                        'msg' => 'No hay asistencia activa'
                    ];
                }
            }else{
                $response = [
                    'bandera' => 1,
                    'msg' => 'No se encontro el diputado'
                ];
            }
        }else{
            $response = [
                'bandera' => 0,
                'msg' => 'No hay evento disponible'
            ];
        }
        return $response;
    }

    public function votoDipNom(Request $request){
        $datos = $request->except('_method','_token');
        $user = DatosUsers::where('nombre_db', $datos['nombre'])->first();
        $evento = EventoVotos::where('estatus', 1)->first();
        if ($evento){
            if ($user) {
                $asistencia = asistenciaVotos::where('randomEvento',$evento->random)->where('status', 1)->where('id_diputado', $user->id)->first();
                $tema = temasVotos::where('randomEvento', $evento->random)->where('status', 1)->first();
                if ($asistencia && !$tema){
                    $up['mensaje'] = 'ASISTENCIA';
                    $up['usuario_registra'] = 0;
                    $asistencia->update($up);
                    $response = [
                        'bandera' => 2,
                        'msg' => 'Asistencia registrada correctamente'
                    ];
                }else if ($tema && !$asistencia) {
                    $voto = mensajesVotos::where('id_votacion', $tema->id)->where('id_diputado', $user->id)->first();
                    if ($voto->usuario_registra != 0 && $voto->usuario_registra != null){
                        if ($voto->usReg->tipo_usuario == 1){
                            $update = false;
                        }else{
                            $update = true;
                        }
                    }else{
                        $update = true;
                    }

                    if ($update == true) {
                        $up['mensaje'] = $datos['sentido'];
                        $up['usuario_registra'] = 0;
                        $voto->update($up);
                    }
                    $response = [
                        'bandera' => 3,
                        'msg' => 'Voto registrado correctamente'
                    ];
                }else{
                    $response = [
                        'bandera' => 4,
                        'msg' => 'No hay voto ni asistencia'
                    ];
                }
            }else{
                $response = [
                    'bandera' => 1,
                    'msg' => 'No se encontro el diputado'
                ];
            }
        }else{
            $response = [
                'bandera' => 0,
                'msg' => 'No hay evento disponible'
            ];
        }
        return $response;
    }

}

OHA YOOOO