<?php

namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Carbon\Carbon;
use getID3;
use DB;

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;

class GroupeController extends Controller
{
    
    public function viewsoneinfogrouge(Request $request)
    {
        global $nbrmenbre;
        $infogroupeData=[];
        
         
        $idgroupe=$request->get('id_groupe');
        $idusers=$request->get('iud');
        
        $datapartenirgroupe = DB::table('ebm_groupe')
        ->join('ebm_rejoindre_groupe', 'ebm_groupe.id_groupe', '=', 'ebm_rejoindre_groupe.id_groupe')
        ->select('ebm_groupe.*') 
        ->where('id_user', $idusers)
        ->first();
        
        if(isset($datapartenirgroupe->id_groupe) and $datapartenirgroupe->id_groupe >0)
        {
        
            if($idgroupe>0)
            {
                $datagroupe = DB::table('ebm_groupe')
                ->where('id_groupe', $idgroupe)
                ->first();
                
                if(isset($datagroupe->id_groupe))
                {
                    $id_groupe=$datagroupe->id_groupe;
                    $titregroupe=$datagroupe->titregroupe;
                    $createdat=$datagroupe->created_at;
                }
                
                $nbrmenbregroup= DB::select('select count(id_rejdrgrpe) as nbrmenbre from ebm_rejoindre_groupe where id_groupe=?',[$id_groupe]); 
                foreach ($nbrmenbregroup as $rownbrmenbregroup){$nbrmenbre =$rownbrmenbregroup->nbrmenbre;}
                
                $nbrmessgroup= DB::select('select count(id_groupepost) as nbrmsggroup from ebm_groupe_posts where id_groupe=?',[$id_groupe]); 
                foreach ($nbrmessgroup as $rownbrmessgroup)
                {
                    $nbrsmessagegroups =$rownbrmessgroup->nbrmsggroup;
                }
                
            }
            else
            {
                $datagroupe = DB::table('ebm_groupe')
                //->where('preference', 1)
                ->where('id_groupe', $datapartenirgroupe->id_groupe)
                ->first();
                
                if(isset($datagroupe->id_groupe) and $datagroupe->id_groupe >0)
                {
                    $id_groupe=$datagroupe->id_groupe;
                    $titregroupe=$datagroupe->titregroupe;
                    $createdat=$datagroupe->created_at;
                }
                
                $nbrmenbregroup= DB::select('select count(id_rejdrgrpe) as nbrmenbre from ebm_rejoindre_groupe where id_groupe=?',[$id_groupe]); 
                foreach ($nbrmenbregroup as $rownbrmenbregroup){$nbrmenbre =$rownbrmenbregroup->nbrmenbre;}
                
                $nbrmessgroup= DB::select('select count(id_groupepost) as nbrmsggroup from ebm_groupe_posts where id_groupe=?',[$id_groupe]); 
                foreach ($nbrmessgroup as $rownbrmessgroup)
                {
                    $nbrsmessagegroups =$rownbrmessgroup->nbrmsggroup;
                }
            }
            
            $infogroupeData[] = [
                'id' => $id_groupe,
                'titregroupe' => $titregroupe,
                'nbrmenbre' => $nbrmenbre,
                'datecreatedat' => $createdat,
                'nbrsmessagegroups' => $nbrsmessagegroups,
                // Ajoutez d'autres attributs d'image ici
            ];
            
            
            $resultgrpeData = [
                'status' => 'true',
                'dataoneinfogrouge' => array_values($infogroupeData),  
            ];
            return response()->json($resultgrpeData);
        }
        else
        {
            $resultgrpeData = [
                'status' => 'false',
                'dataoneinfogrouge' => $idusers,  
            ];
            return response()->json($resultgrpeData);
        }
    }
    
    public function viewsallgrouge(Request $request)
    {
        $allgroupData=[];
        $idusers=$request->get('iud');
        
        if($idusers!='')
        {
            $allgroupe= DB::select('SELECT ebm_groupe.* FROM ebm_groupe,ebm_rejoindre_groupe WHERE ebm_groupe.id_groupe=ebm_rejoindre_groupe.id_groupe and id_user=?',[$idusers]);
        }
        else
        {
            $allgroupe= DB::select('SELECT ebm_groupe.* FROM ebm_groupe,ebm_rejoindre_groupe WHERE ebm_groupe.id_groupe=ebm_rejoindre_groupe.id_groupe');
        }
        
        foreach ($allgroupe as $rowsallgroupe)
        {
            $groupeId=$rowsallgroupe->id_groupe;
            
            $allgroupData[$groupeId]=[
                'id' =>$rowsallgroupe->id_groupe,  
                'titregroupe' => $rowsallgroupe->titregroupe,
            ];
        }
        
        $resultallgroupe = [
            'status' => 'true',
            'datagroupall' => array_values($allgroupData),  
        ];
        return response()->json($resultallgroupe);
    }
    
    
    public function viewsgrougetype()
    {
        $alltypegroupData=[];
        $alltypegroupe= DB::select('select ebm_groupe.* from ebm_groupe');
        foreach ($alltypegroupe as $rowsalltypegroupe)
        {
            $groupeId=$rowsalltypegroupe->id_groupe;
            $est_actif=$rowsalltypegroupe->est_actif;
            if($est_actif==1){$est_actif="Actif";}else{$est_actif="Inactif";}
            
            $nbrmenbregroup= DB::select('select count(id_rejdrgrpe) as nbrmenbre from ebm_rejoindre_groupe where id_groupe=?',[$groupeId]); 
            foreach ($nbrmenbregroup as $rownbrmenbregroup){$nbrmenbre =$rownbrmenbregroup->nbrmenbre;}
            
            $alltypegroupData[$groupeId]=[
                'id' =>$rowsalltypegroupe->id_groupe,  
                'titregroupe' => $rowsalltypegroupe->titregroupe,
                'prochainesession' => $rowsalltypegroupe->prochaine_session,
                'typegroupe' => $rowsalltypegroupe->typegroupe,
                'actif' => $est_actif,
                'nbrmenbre' => $nbrmenbre,
            ];
        }
        
        $resultalltypegroupe = [
            'status' => 'true',
            'alldatatypegroupe' => array_values($alltypegroupData),  
        ];
        return response()->json($resultalltypegroupe);
    }
    
    
    public function rejoindregroupe(Request $request)
    {
        $idgroupe=$request->get('id_groupe');
        $iduser=$request->get('iduser');
        
        $usersdata = DB::table('ebm_users')->where('id_user', $iduser)->first();
        if(isset($usersdata->id_user)){$senderName=$usersdata->nom.' '.$usersdata->prenom;}
        
        if($idgroupe>0)
        {
            $datarejoindregroupe = DB::table('ebm_rejoindre_groupe')
            ->where('id_user', $iduser)
            ->first();
            
            if(isset($datarejoindregroupe->id_rejdrgrpe) and $datarejoindregroupe->id_rejdrgrpe >0)
            {
                return response()->json([
                    'success' => 'true',
                    'action' => 'uid existe dejà',
                ]);
            }
            else
            {
                $countgroupe = DB::table('ebm_rejoindre_groupe')
                ->where('id_groupe', '=', $idgroupe) 
                ->count();
        
                DB::table('ebm_rejoindre_groupe')->insert(
                    [
                        'id_groupe' => $idgroupe,
                        'id_user' => $iduser,
                        'fonction' => 'membre',
                        'created_at' => DB::raw('NOW()')
                    ]
                );
                
                if($countgroupe>0){}
                else
                {
                    DB::table('ebm_rejoindre_groupe')
                    ->where('id_groupe', $idgroupe)
                    ->where('id_user', $iduser)
                    ->update([
                        'fonction' => 'admin',
                    ]);
                }
                
                
                $datanotifygroupe = DB::table('ebm_rejoindre_groupe') 
                ->join('ebm_users', 'ebm_rejoindre_groupe.id_user', '=', 'ebm_users.id_user')
                ->join('ebm_groupe', 'ebm_rejoindre_groupe.id_groupe', '=', 'ebm_groupe.id_groupe')
                ->select('ebm_rejoindre_groupe.*','titregroupe','email','fcm_token','nom','prenom') 
                ->where('ebm_rejoindre_groupe.id_groupe', '=', $idgroupe)
                ->where('ebm_users.id_user', '!=', $iduser)
                //->orderBy('id', 'desc')
                ->get();
                
                $firebase = (new Factory)->withServiceAccount(base_path('ebmmission-1b301-firebase-adminsdk-fbsvc-639a650b4d.json'));   
                
                foreach ($datanotifygroupe as $rowdatanotifygroupe) 
                {
                    //--------------------------------------------------- NOUVEAU CONTENUS -----------------------------------------------------------
                    
                    $varemail= $rowdatanotifygroupe->email; 
                    $varfcmtoken= $rowdatanotifygroupe->fcm_token;
                    //$senderName=$rowdatanotifygroupe->nom.' '.$rowdatanotifygroupe->prenom;
                    $groupName= $rowdatanotifygroupe->titregroupe;
                    
                    $subject="Nouveau message dans $groupName";
                    //$html = "Votre hébergement vient d'être réservé par $valnameusersx ,nombre de chambre réservé : $valnbofroom";
                    $html = "Bonjour $senderName, vous avez rejoint $groupName avec succès. Partagez vos idées et profitez de la richesse des échanges.";
                    
                    if($rowdatanotifygroupe->notif_arrivant_push==1)
                    {
                        try
                        {
                            $messaging = $firebase->createMessaging();     
                            $message = CloudMessage::fromArray([ 
                                'token' => $varfcmtoken,
                                'notification' => [
                                    'title' => $subject,
                                    'body' => $html
                                ],
                                //'topic' => 'global'
                            ]);
                            $messaging->send($message);
                            
                        }catch(\Exception $ex){}
                        
                    }
                    if($rowdatanotifygroupe->notif_arrivant_email==1)
                    {
                        
                        
                    }
                }
                
                return response()->json([
                    'success' => 'true',
                    'action' => 'uid ajouter avec succès',
                ]);
            }
        }
    }
    
    //---------------------------------------------------------- api pour enregistrer les messages du groupe ---------------------------------------------------------------
    
    public function postgroupmsg(Request $request)
    {
        global $fileName,$varemail,$varfcmtoken,$groupName,$senderName;
        
        $id_groupe=$request->input('id_groupe');
        $user_id=$request->input('id_user');
        $content=$request->input('content');
        
        $audioPath = null;
        
        $usersdata = DB::table('ebm_users')->where('id_user', $user_id)->first();
        if(isset($usersdata->id_user)){$senderName=$usersdata->nom.' '.$usersdata->prenom;}
        
        /*
        // Exemple : $request->input('audio') = 'data:audio/mp3;base64,//...'
        $base64Audio = $request->input('audio_url');
        $folderPath = public_path("audiosforums");
        
        if($base64Audio!='')
        {
            // Créer le dossier s’il n’existe pas
            if (!File::isDirectory($folderPath)) {
                File::makeDirectory($folderPath, 0755, true);
            }
        
            // Extraction des métadonnées et du contenu base64
            $parts = explode(";base64,", $base64Audio);
            if (count($parts) !== 2) {
                return response()->json(['error' => 'Format audio invalide.'], 400);
            }
        
            $metaData = $parts[0]; // exemple: data:audio/mp3
            $audioData = base64_decode($parts[1]);
        
            // Extraire le type de fichier (mp3, wav, etc.)
            if (preg_match('/^data:audio\/(\w+)$/', $metaData, $matches)) {
                $audioType = strtolower($matches[1]);
            } else {
                return response()->json(['error' => 'Type audio non reconnu.'], 400);
            }
            
            // Types autorisés
            $allowedTypes = ['mp3', 'wav', 'ogg', 'mpeg', 'mp4'];
            if (!in_array($audioType, $allowedTypes)) {
                return response()->json(['error' => 'Type de fichier audio non autorisé.'], 400);
            }
        
            // Nom unique pour le fichier
            $fileName = Str::uuid() . '.' . $audioType;
            $filePath = $folderPath . '/' . $fileName;
        
            // Sauvegarde du fichier
            if (file_put_contents($filePath, $audioData) === false) {
                return response()->json(['error' => 'Échec de l\'enregistrement du fichier audio.'], 500);
            }
        }
        
        $urlfilestore='https://touszone.com/mobileappebm/public/audiosforums/'.''.$fileName;
        */
        
        DB::table('ebm_groupe_posts')->insert(
            [
                'id_groupe' => $id_groupe,
                'id_user' => $user_id,
                'content' => $content, 
                //'audio_url' => $urlfilestore,  
                'date_publication' => DB::raw('NOW()')
            ]
        );
        
        
        $datanotifygroupe = DB::table('ebm_rejoindre_groupe') 
        ->join('ebm_users', 'ebm_rejoindre_groupe.id_user', '=', 'ebm_users.id_user')
        ->join('ebm_groupe', 'ebm_rejoindre_groupe.id_groupe', '=', 'ebm_groupe.id_groupe')
        ->select('ebm_rejoindre_groupe.*','titregroupe','email','fcm_token','nom','prenom') 
        ->where('ebm_rejoindre_groupe.id_groupe', '=', $id_groupe)
        ->where('ebm_users.id_user', '!=', $user_id)
        //->orderBy('id', 'desc')
        ->get();
        
        $firebase = (new Factory)->withServiceAccount(base_path('ebmmission-1b301-firebase-adminsdk-fbsvc-639a650b4d.json'));   
        
        foreach ($datanotifygroupe as $rowdatanotifygroupe) 
        {
            //--------------------------------------------------- NOUVEAU CONTENUS -----------------------------------------------------------
            
            $varemail= $rowdatanotifygroupe->email; 
            $varfcmtoken= $rowdatanotifygroupe->fcm_token;
            //$senderName=$rowdatanotifygroupe->nom.' '.$rowdatanotifygroupe->prenom;
            $groupName= $rowdatanotifygroupe->titregroupe;
            
            $subject="Nouveau message dans $groupName";
            //$html = "Votre hébergement vient d'être réservé par $valnameusersx ,nombre de chambre réservé : $valnbofroom";
            $html = "$senderName : $content";
            
            if($rowdatanotifygroupe->notifymsgpush==1)
            {
                try
                {
                    $messaging = $firebase->createMessaging();     
                    $message = CloudMessage::fromArray([ 
                        'token' => $varfcmtoken,
                        'notification' => [
                            'title' => $subject,
                            'body' => $html
                        ],
                        //'topic' => 'global'
                    ]);
                    $messaging->send($message);
                    
                }catch(\Exception $ex){}
                
            }
            if($rowdatanotifygroupe->notifymsgemail==1)
            {
                
                
            }
        }
        
        return response()->json(['success' => true], 200);
    }
    
    //---------------------------------------------------------- api pour afficher les messages du groupe ---------------------------------------------------------------
    
    public function groupeallmsg(Request $request)
    {
        $idgroupe=$request->get('id_groupe');
        $user_id=$request->get('id_user');
    
        $allforumsData = [];
        
        $allforums= DB::select('select ebm_groupe_posts.* from ebm_groupe_posts where id_groupe=? order by date_publication desc',[$idgroupe]);
        foreach ($allforums as $rowsallforums)
        {
            $forumsId=$rowsallforums->id_groupepost;
            
            $postlikes = DB::table('ebm_groupe_posts_likes')
            ->where('id_user', $user_id)
            ->where('id_groupepost', $forumsId)
            ->first();
            if(isset($postlikes->id_likes_groupe_posts) and $postlikes->id_likes_groupe_posts >0){$isLiked=true;}else{$isLiked=false;}
            
            /*
            $reactions = DB::table('ebm_forum_reactions')
            ->where('id_user', $user_id)
            ->where('id_post', $forumsId)
            ->first();
            if(isset($reactions->id_reactions) and $reactions->id_reactions >0){$isPrayed=true;}else{$isPrayed=false;}
            
            $partage = DB::table('ebm_forum_partage')
            ->where('id_user', $user_id)
            ->where('id_post', $forumsId)
            ->first();
            if(isset($partage->id_partage) and $partage->id_partage >0){$isShared=true;}else{$isShared=false;}
            */
            
            $allforumsData[$forumsId]=[
                'id' =>$rowsallforums->id_groupe,  
                'id_user' => $rowsallforums->id_user,
                'content' => $rowsallforums->content,
                //'audio_url' => $rowsallforums->audio_url,
                'date_publication' => $rowsallforums->date_publication,
                'avatar' =>[],
                'nbrlikegroup' =>[],
                /*
                'nbrsoutienpriere' =>[],
                'nbrpartageforums' =>[],
                'nbrreponses' =>[],
                'nbrvues' =>$rowsallforums->vues,
                */
                'isLikedByCurrentUser' => $isLiked,
                /*
                'isPrayedByCurrentUser' => $isPrayed,
                'isSharedByCurrentUser' => $isShared,
                */
            ];
            
            
            $nbrlikeforums= DB::select('select count(id_likes_groupe_posts) as nbrslikeforums from ebm_groupe_posts_likes where id_groupepost=?',[$rowsallforums->id_groupepost]); 
            foreach ($nbrlikeforums as $rownbrlikeforums)
            {
                $allforumsData[$forumsId]['nbrlikegroup'][] = [
                    'likegroupe' => $rownbrlikeforums->nbrslikeforums,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
            /*
            $nbrsoutienpriereforums= DB::select('select count(id_reactions) as soutienprieres from ebm_forum_reactions where id_post=?',[$rowsallforums->id_post]); 
            foreach ($nbrsoutienpriereforums as $rowsoutienpriereforums)
            {
                $allforumsData[$forumsId]['nbrsoutienpriere'][] = [
                    'soutienpriere' => $rowsoutienpriereforums->soutienprieres,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
            $nbrpartagesforums= DB::select('select count(id_partage) as partage from ebm_forum_partage where id_post=?',[$rowsallforums->id_post]); 
            foreach ($nbrpartagesforums as $rownbrpartageforums)
            {
                $allforumsData[$forumsId]['nbrpartageforums'][] = [
                    'partageforums' => $rownbrpartageforums->partage,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
            $nbrrepforums= DB::select('select count(id_reponses) as repnbrforums from ebm_forum_reponses where id_post=?',[$rowsallforums->id_post]); 
            foreach ($nbrrepforums as $rownbrnbrrepforums)
            {
                $allforumsData[$forumsId]['nbrreponses'][] = [
                    'reponsesforums' => $rownbrnbrrepforums->repnbrforums,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            */
            
            $avatarforums= DB::select('select * from ebm_users where id_user=?',[$rowsallforums->id_user]); 
            foreach ($avatarforums as $rowavatarforums)
            {
                $allforumsData[$forumsId]['avatar'][] = [
                    'urlavatar' => $rowavatarforums->avatar,
                    'nameavatar' => $rowavatarforums->nom.' '.$rowavatarforums->prenom,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
        }
    
        $resultgroupDatabig = [
            'status' => 'true',
            'allbigdatagroup' => array_values($allforumsData),  
        ];
        return response()->json($resultgroupDatabig);
        
    }
    
    
    public function detail_msg_group(Request $request)
    {
        global $nbrdereponses;
        $user_id=$request->input('id_user');
        $idmsgforums=$request->input('id_groupepost');
        $detailforumsData = [];
        
        // Incrémenter le nombre de vues
        DB::table('ebm_groupe_posts')->where('id_groupepost', $idmsgforums)->increment('vues');
        
        $allforums= DB::select('select ebm_groupe_posts.* from ebm_groupe_posts where id_groupepost=?',[$idmsgforums]);
        foreach ($allforums as $rowsallforums)
        {
            $forumsId=$rowsallforums->id_groupepost;
            
            $postlikes = DB::table('ebm_groupe_posts_likes')
            ->where('id_user', $user_id)
            ->where('id_groupepost', $forumsId)
            ->first();
            if(isset($postlikes->id_likes_groupe_posts) and $postlikes->id_likes_groupe_posts >0){$isLiked=true;}else{$isLiked=false;}
            
            /*
            
            $reactions = DB::table('ebm_forum_reactions')
            ->where('id_user', $user_id)
            ->where('id_post', $forumsId)
            ->first();
            if(isset($reactions->id_reactions) and $reactions->id_reactions >0){$isPrayed=true;}else{$isPrayed=false;}
            
            $partage = DB::table('ebm_forum_partage')
            ->where('id_user', $user_id)
            ->where('id_post', $forumsId)
            ->first();
            if(isset($partage->id_partage) and $partage->id_partage >0){$isShared=true;}else{$isShared=false;}
            */
            
            $detailforumsData[$forumsId]=[
                'id' =>$rowsallforums->id_groupepost,  
                'id_user' => $rowsallforums->id_user,
                'content' => $rowsallforums->content,
                //'audio_url' => $rowsallforums->audio_url,
                'date_post' => $rowsallforums->date_publication,
                'avatar' =>[],
                'nbrlikeforums' =>[],
                /*
                'nbrsoutienpriere' =>[],
                'nbrpartageforums' =>[],
                */
                'nbrreponses' =>[],
                'nbrvues' =>$rowsallforums->vues,
                'isLikedByCurrentUser' => $isLiked,
                /*
                'isPrayedByCurrentUser' => $isPrayed,
                'isSharedByCurrentUser' => $isShared,
                */
                'reponses' =>[],
            ];
            
            
            $nbrlikeforums= DB::select('select count(id_likes_groupe_posts) as nbrslikeforums from ebm_groupe_posts_likes where id_groupepost=?',[$rowsallforums->id_groupepost]); 
            foreach ($nbrlikeforums as $rownbrlikeforums)
            {
                $detailforumsData[$forumsId]['nbrlikeforums'][] = [
                    'likeforums' => $rownbrlikeforums->nbrslikeforums,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
            /*
            $nbrsoutienpriereforums= DB::select('select count(id_reactions) as soutienprieres from ebm_forum_reactions where id_post=?',[$rowsallforums->id_post]); 
            foreach ($nbrsoutienpriereforums as $rowsoutienpriereforums)
            {
                $detailforumsData[$forumsId]['nbrsoutienpriere'][] = [
                    'soutienpriere' => $rowsoutienpriereforums->soutienprieres,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
            $nbrpartagesforums= DB::select('select count(id_partage) as partage from ebm_forum_partage where id_post=?',[$rowsallforums->id_post]); 
            foreach ($nbrpartagesforums as $rownbrpartageforums)
            {
                $detailforumsData[$forumsId]['nbrpartageforums'][] = [
                    'partageforums' => $rownbrpartageforums->partage,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            */
            
            $nbrrepforums= DB::select('select count(id_reponses) as repnbrforums from ebm_groupe_posts_reponses where id_groupepost=?',[$rowsallforums->id_groupepost]); 
            foreach ($nbrrepforums as $rownbrnbrrepforums)
            {
                $detailforumsData[$forumsId]['nbrreponses'][] = [
                    'reponsesforums' => $rownbrnbrrepforums->repnbrforums,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
            $avatarforums= DB::select('select * from ebm_users where id_user=?',[$rowsallforums->id_user]); 
            foreach ($avatarforums as $rowavatarforums)
            {
                $detailforumsData[$forumsId]['avatar'][] = [
                    'urlavatar' => $rowavatarforums->avatar,
                    'nameavatar' => $rowavatarforums->nom.' '.$rowavatarforums->prenom,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
            $reponsesforums= DB::select('select * from ebm_groupe_posts_reponses where id_groupepost=?',[$rowsallforums->id_groupepost]); 
            foreach ($reponsesforums as $rowreponsesforums)
            {
                $nbrdereponses=$nbrdereponses+1;
                $datarepavatar= DB::select('select * from ebm_users where id_user=?',[$rowreponsesforums->id_user]);
                foreach ($datarepavatar as $rowrepavatar)
                {
                    $urlavatar =$rowrepavatar->avatar;
                    $nameavatar = $rowrepavatar->nom.' '.$rowrepavatar->prenom;
                }
                
                $nbrlikerep= DB::select('select count(id_likes_reponses) as nbrslikerep from ebm_groupe_posts_reponses_likes where id_reponses=?',[$rowreponsesforums->id_reponses]);
                foreach ($nbrlikerep as $rowrepavatar)
                {
                    $nbrslikerep =$rowrepavatar->nbrslikerep;
                }
                
                $postlikesrep = DB::table('ebm_groupe_posts_reponses_likes')
                ->where('id_user', $user_id)
                ->where('id_reponses', $rowreponsesforums->id_reponses)
                ->first();
                if(isset($postlikesrep->id_likes_reponses) and $postlikesrep->id_likes_reponses >0){$isLiked=true;}else{$isLiked=false;}
                
                $detailforumsData[$forumsId]['reponses'][] = [
                    'id_post' => $rowreponsesforums->id_groupepost,
                    'reponseavatar' => [
                        'urlavatar' => $urlavatar,
                        'nameavatar' => $nameavatar,
                    ],
                    'content' => $rowreponsesforums->content,
                    'date_reponse' => $rowreponsesforums->date_reponse,
                    'likeCount' => $nbrslikerep,
                    'isLikedByCurrentUser' => $isLiked,
                    'reponsesforums' => $nbrdereponses,
                    // Ajoutez d'autres attributs d'image ici
                ];
                
                
            }
            
        }
    
        $resultforumsData = [
            'status' => 'true',
            'alldetailgroup' => array_values($detailforumsData),  
        ];
        return response()->json($resultforumsData);
    }
    
    public function savereponsepostgroupe(Request $request)
    {
        global $fileName;
        $user_id=$request->input('id_user');
        $id_groupepost=$request->input('id_groupepost');
        $content=$request->input('content');
        
        DB::table('ebm_groupe_posts_reponses')->insert(
            [
                'id_groupepost' => $id_groupepost,
                'id_user' => $user_id, 
                'content' => $content,  
                //'input_type' => $input_type,
                'date_reponse' => DB::raw('NOW()')
            ]
        );
        
        return response()->json(['success' => true], 200);
    }
    
    public function save_delete_favoriegroup_reponse(Request $request)
    {
        $idusers = $request->input('userId'); 
        $idreponses = $request->input('id_reponses'); 
        
        $dblikefavorie = DB::table('ebm_groupe_posts_reponses_likes')
        ->where('id_user', $idusers)
        ->where('id_reponses', $idreponses)
        ->first();
        
        if(isset($dblikefavorie->id_likes_reponses) and $dblikefavorie->id_likes_reponses >0)
        {
            $deletedfavorie = DB::delete('delete from ebm_groupe_posts_reponses_likes where id_user=? and id_reponses=?',[$idusers,$idreponses]);
            
            return response()->json([
                'success' => 'true',
                'action' => 'removed',
                'message' => 'Favori supprimé'
            ]);
        }
        else
        {
            DB::table('ebm_groupe_posts_reponses_likes')->insert(
                [
                    'id_user' => $idusers,
                    'id_reponses' => $idreponses,
                    'created_at' => date('Y-m-d H:i:s')
                ]
            );
            
            return response()->json([
                'success' => 'true',
                'action' => 'added',
                'message' => 'Favori ajouté'
            ]);
        }  
    }
    
    
    //-------------------------------------------------------------------------- API POUR SAVE/DELETE FAVORIE IN GROUPE --------------------------------------------------------------------------------
    
    public function save_delete_favoriegroup(Request $request)
    {
        $idusers = $request->input('userId'); 
        $idgroupe = $request->input('id_groupe'); 
        
        $dblikefavorie = DB::table('ebm_groupe_posts_likes')
        ->where('id_user', $idusers)
        ->where('id_groupepost', $idgroupe)
        ->first();
        
        if(isset($dblikefavorie->id_likes_groupe_posts) and $dblikefavorie->id_likes_groupe_posts >0)
        {
            $deletedfavorie = DB::delete('delete from ebm_groupe_posts_likes where id_user=? and id_groupepost=?',[$idusers,$idgroupe]);
            
            return response()->json([
                'success' => 'true',
                'action' => 'removed',
                'message' => 'Favori supprimé'
            ]);
        }
        else
        {
            DB::table('ebm_groupe_posts_likes')->insert(
                [
                    'id_user' => $idusers,
                    'id_groupepost' => $idgroupe,
                    'viewed_at' => date('Y-m-d H:i:s')
                ]
            );
            
            return response()->json([
                'success' => 'true',
                'action' => 'added',
                'message' => 'Favori ajouté'
            ]);
        }  
    }
    
    //-------------------------------------------------------------------------- API POUR AFFICHER MENBRE ET ADMINISTRATEUR IN GROUPE --------------------------------------------------------------------------------
    
    public function menbre_admin_group(Request $request)
    {
        $adminmenbregrp=[];
        $idgroupe=$request->get('idgroupe');
        
        $messagegroupe= DB::select('SELECT ebm_groupe.* FROM ebm_groupe WHERE ebm_groupe.id_groupe=?',[$idgroupe]);
        foreach ($messagegroupe as $rowmessagegroupe)
        {
            $nbrmenbregroup= DB::select('select count(id_rejdrgrpe) as nbrmenbre from ebm_rejoindre_groupe where id_groupe=?',[$idgroupe]); 
            foreach ($nbrmenbregroup as $rownbrmenbregroup){$nbrmenbre =$rownbrmenbregroup->nbrmenbre;}
            
            $adminmenbregrp[$idgroupe]=[
                'id' =>$rowmessagegroupe->id_groupe,  
                'titregroupe' => $rowmessagegroupe->titregroupe,
                'nbrparticipant' => $nbrmenbre,
                'menbreadmin' => [],
                
            ];
            
            $dtmenbreadmin= DB::select('select ebm_users.*,fonction from ebm_users,ebm_rejoindre_groupe where ebm_users.id_user=ebm_rejoindre_groupe.id_user and id_groupe=?',[$rowmessagegroupe->id_groupe]); 
            foreach ($dtmenbreadmin as $rowdtmenbreadmin)
            {
                $adminmenbregrp[$idgroupe]['menbreadmin'][] = [
                    'iduser' =>$rowdtmenbreadmin->id_user, 
                    'role' => $rowdtmenbreadmin->fonction,
                    'urlavatar' => $rowdtmenbreadmin->avatar,
                    'nameavatar' => $rowdtmenbreadmin->nom.' '.$rowdtmenbreadmin->prenom,
                ];
            }
            
        }
        
        $resultadminmenbregrp = [
            'status' => 'true',
            'menbradmingroup' => array_values($adminmenbregrp),  
        ];
        return response()->json($resultadminmenbregrp);
    }
    
    //--------------------------------------------------------------------------  API POUR RETIRER UN MENBRE IN GROUPE  -----------------------------------------------------------------------
    
    public function retirer_menbre_group(Request $request)
    {
        $idgroupe=$request->get('idgroupe');
        $iduser=$request->get('iduser');
        
        $deletedfavorie = DB::delete('delete from ebm_rejoindre_groupe where id_groupe=? and id_user=?',[$idgroupe,$iduser]);
        
        return response()->json([
            'success' => 'true',
            'action' => 'removed',
            'message' => 'supprimé'
        ]);
    }
    
    
    public function savenotifyparamgroup(Request $request)
    {
        $idgroupe=$request->get('group_id');
        $iduser=$request->get('user_id');
        
        $push=$request->input('notif_content_push');
        $email=$request->input('notif_content_email');
        
        $notif_arrivant_push=$request->input('notif_arrivant_push');
        $notif_arrivant_email=$request->input('notif_arrivant_email');
        
        DB::table('ebm_rejoindre_groupe')
        ->where('id_groupe', $idgroupe)
        ->where('id_user', $iduser)
        ->update([
            'notifymsgpush' => $push,
            'notifymsgemail' => $email,
            'notif_arrivant_push' => $notif_arrivant_push,
            'notif_arrivant_email' => $notif_arrivant_email,
        ]);
        
          
        return response()->json([
            'success' => 'true'
        ]);
    }
    
    public function recupnotifyparamgroup(Request $request)
    {
        $idgroupe=$request->get('group_id');
        $iduser=$request->get('user_id');
        
        
        $afichnotify = DB::table('ebm_rejoindre_groupe')
        ->where('id_groupe', $idgroupe)
        ->where('id_user', $iduser)
        ->first();
        
        if(isset($afichnotify->id_rejdrgrpe) and $afichnotify->id_rejdrgrpe >0)
        {
            return response()->json([
                'success' => 'true',
                'notif_content_push' => $afichnotify->notifymsgpush,
                'notif_content_email' => $afichnotify->notifymsgemail,
                'notif_arrivant_push' => $afichnotify->notif_arrivant_push,
                'notif_arrivant_email' => $afichnotify->notif_arrivant_email
            ]);
        }
    
    }
    
    //-------------------------------------------------------------------------- API POUR RECUPERER LE TOKEN USERS A CONNEXION REUSSIR --------------------------------------------------------------------------------
    
    public function recuperertoken(Request $request)
    {
        $idusers=$request->get('iud');
        $token=$request->get('token');
        
        DB::table('ebm_users')
        ->where('id_user', $idusers)
        ->update([
            'tokenuser' => $token,
            'last_active' => DB::raw('NOW()')
        ]);
        
        return response()->json([
            'statusCode' => 200
        ]);
    }
    
    
    
    
    
    public function testnotify(Request $request)
    {
        global $fileName,$varemail,$varfcmtoken,$groupName,$senderName;
        
        
        $user_id=$request->get('id_user');
        
        $sqluserprotoken = DB::table('ebm_users')
        ->where('id_user', $user_id)
        ->first();
        
        if(isset($sqluserprotoken->id_user))
        {
            $varemail= $sqluserprotoken->email; 
            $varfcmtoken= $sqluserprotoken->fcm_token;
            $senderName=$sqluserprotoken->nom.' '.$sqluserprotoken->prenom;
        }
        
        $groupName="prière a la maison";
        $content="Bienvenus dans le groupe";
        
        $subject="Nouveau message dans $groupName";
        //$html = "Votre hébergement vient d'être réservé par $valnameusersx ,nombre de chambre réservé : $valnbofroom";
        $html = "$senderName : $content";


        $firebase = (new Factory)->withServiceAccount(base_path('ebmmission-1b301-firebase-adminsdk-fbsvc-639a650b4d.json'));   
                
        try
        {
            $messaging = $firebase->createMessaging();     
            $message = CloudMessage::fromArray([ 
                'token' => $varfcmtoken,
                'notification' => [
                    'title' => $subject,
                    'body' => $html
                ],
                //'topic' => 'global'
            ]);
            $messaging->send($message);
            
        }catch(\Exception $ex){}
        
        return response()->json(['success' => true], 200);
    }
    
    
    public function testnotify2()
    {
        global $fileName,$varemail,$varfcmtoken,$groupName,$senderName;
        
        
        $datanotifypreference = DB::table('ebm_user_notify_preferences')
        ->join('ebm_users', 'ebm_user_notify_preferences.id_user', '=', 'ebm_users.id_user')
        ->select('ebm_user_notify_preferences.*','email','fcm_token','nom','prenom')
        ->where(function($query) {
            $query->where('new_content', 1)
            ->orWhere('live_broadcasts', 1)
            ->orWhere('community_prayers', 1);
        })
        ->get();
        
        $firebase = (new Factory)->withServiceAccount(base_path('ebmmission-1b301-firebase-adminsdk-fbsvc-639a650b4d.json'));   
            
        foreach ($datanotifypreference as $rowdatanotify) 
        {
            $senderName=$rowdatanotify->nom.' '.$rowdatanotify->prenom;
            $varemail= $rowdatanotify->email; 
            $varfcmtoken= $rowdatanotify->fcm_token;
            
            $subject="Nouvel Événement : Prière du matin";
            //$html = "Votre hébergement vient d'être réservé par $valnameusersx ,nombre de chambre réservé : $valnbofroom";
            $html = "Bonjour $senderName, un nouveau événement vient d’être publié sur EMB-Mission. Consultez-le dès maintenant !";
            
            try
            {
                $messaging = $firebase->createMessaging();     
                $message = CloudMessage::fromArray([ 
                    'token' => $varfcmtoken,
                    'notification' => [
                        'title' => $subject,
                        'body' => $html
                    ],
                    //'topic' => 'global'
                ]);
                $messaging->send($message);
                
            }catch(\Exception $ex){}
        }
    
        return response()->json(['success' => true], 200);
    }
    
    
}
