<?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 prayersController extends Controller
{
    //LISTE DES CATEGORIES
    
    public function categorie_prayers()
    {
        $prayer_categories= DB::select('select ebm_prayer_categories.* from ebm_prayer_categories');
        $prayercategories = [
            'success' => 'true',
            'prayercategories' => array_values($prayer_categories),  
        ];
        return response()->json($prayercategories);
        
    }
    
    //API POUR ENREGISTRER DES PRAYERS
    
    public function save_prayers(Request $request)
    {
        global $fileName,$namecategory;
        $user_id=$request->input('id_user');
        $category_id=$request->input('category_id');
        $title=$request->input('title');
        $content=$request->input('content');
        
        $audioDuration = 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("fichiers/$user_id");
        
        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);
            }
            
            // Analyse de la durée avec getID3
            $getID3 = new getID3;
            $fileInfo = $getID3->analyze($filePath);
            if (isset($fileInfo['playtime_seconds'])) {
                //$audioDuration = round($fileInfo['playtime_seconds'], 2); // En secondes avec 2 décimales
                $audioDuration = gmdate("i:s", (int) $fileInfo['playtime_seconds']); // ex: "02:45"
            }
        }
        
        if($base64Audio == ''){$urlfilestore=null;}else{$urlfilestore='https://touszone.com/mobileappebm/public/fichiers/lfGKzI/'.''.$fileName;} 
        */
        //  ebm_prayers
        
        DB::table('ebm_events_home_screen')->insert(
            [
                'id_user' => $user_id,
                'id_prayer_cat' => $category_id,
                'titre' => $title, 
                'description' => $content, 
                'type' => 'prière',
                'type_users' => 'Usager',
                //'audio_url' => $urlfilestore,  
                //'audio_duration' => $audioDuration,
                'created_at' => DB::raw('NOW()'), 
                'updated_at' => date('Y-m-d H:i:s')
            ]
        );
        
        $category = DB::table('ebm_prayer_categories')->where('id_prayer_cat', $category_id)->first();
        if(isset($category->id_prayer_cat) and $category->id_prayer_cat >0){$namecategory =$category->name;}
        
        $datanotify = 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('ebm_users.id_user', '!=', $user_id)
        //->orderBy('id', 'desc')
        ->get();
        
        $firebase = (new Factory)->withServiceAccount(base_path('ebmmission-1b301-firebase-adminsdk-fbsvc-639a650b4d.json'));   
        
        foreach ($datanotify as $rowdatanotify) 
        {
            $varemail= $rowdatanotify->email; 
            $varfcmtoken= $rowdatanotify->fcm_token;
            //$senderName=$rowdatanotify->nom.' '.$rowdatanotify->prenom;
            
            $subject="Nouveau message prière de $namecategory $title";
            //$html = "Votre hébergement vient d'être réservé par $valnameusersx ,nombre de chambre réservé : $valnbofroom";
            $html = "$senderName : $content";
            
            if($rowdatanotify->community_prayers==1 and $rowdatanotify->notifypush==1)
            {
                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);
    }
    
    //-------------------------------------------------------------------------- API POUR LISTER TOUTES LES PRAYERS --------------------------------------------------------------------------------
    
    public function all_prayers()
    {
        //$user_id=$request->input('id_user');
        
        $allprayersData = [];
        //$allprayer= DB::select('select ebm_prayers.*,name from ebm_prayers,ebm_prayer_categories where ebm_prayers.id_prayer_cat=ebm_prayer_categories.id_prayer_cat order by created_at desc');
        $allprayer= DB::select('select ebm_events_home_screen.*,name from ebm_events_home_screen,ebm_prayer_categories where ebm_events_home_screen.id_prayer_cat=ebm_prayer_categories.id_prayer_cat 
        and type=? order by created_at desc',['prière']);
        foreach ($allprayer as $rowsallprayer)
        {
            $prayersId=$rowsallprayer->idevents;
            /*
            $postlikes = DB::table('ebm_events_favoris_prieres')
            ->where('id_user', $user_id)
            ->where('idevents', $prayersId)
            ->first();
            if(isset($postlikes->id_favoris_prieres) and $postlikes->id_favoris_prieres >0){$isLiked=true;}else{$isLiked=false;}
            */
            
            $allprayersData[$prayersId]=[
                'id' =>$rowsallprayer->idevents,
                'title' => $rowsallprayer->titre,
                'content' => $rowsallprayer->description,
                'categorie' => $rowsallprayer->name,
                'audio_url' => $rowsallprayer->audio_url,
                'audio_duration' => $rowsallprayer->duree_minutes,
                'favories' =>[],
                //'isLikedByCurrentUser' => $isLiked,
            ];
            
            
            $dataviewfavories= DB::select('select * from ebm_events_favoris_prieres where idevents=?',[$rowsallprayer->idevents]); 
            foreach ($dataviewfavories as $rowviewfavories)
            {
                $allprayersData[$prayersId]['favories'][] = [
                    'idfavorites' => $rowviewfavories->id_favoris_prieres,
                    'iduser' =>   $rowviewfavories->id_user,
                    'created_at' =>   $rowviewfavories->created_at,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
        }
    
        $resultprayerall = [
            'status' => 'true',
            'alldataprayers' => array_values($allprayersData),  
        ];
        return response()->json($resultprayerall);
        
    }
    
    //-------------------------------------------------------------------------- API POUR AJOUTER OU RETIRER FAVORIES PRAYERS --------------------------------------------------------------------------------
    
    public function save_retrait_favorie_prayers(Request $request)
    {
        
        $idprayers=$request->input('idprayers');
        $userid=$request->input('id_user');
        
        
        $favoriedb = DB::table('ebm_events_favoris_prieres')
        ->where('idevents', $idprayers)
        ->where('id_user', $userid) 
        ->first();
        
        if(isset($favoriedb->id_favoris_prieres) and $favoriedb->id_favoris_prieres >0)
        {
            $deletedfavorieprayers = DB::delete('delete from ebm_events_favoris_prieres where id_user=? and idevents=?',[$userid,$idprayers]);
            
            return response()->json([
                'success' => 'true',
                'action' => 'removed',
                'message' => 'Favori supprimé'
            ]);
        } 
        else
        {
            DB::table('ebm_events_favoris_prieres')->insert(
                [
                    'idevents' => $idprayers,
                    'id_user' => $userid,
                    'created_at' => date('Y-m-d H:i:s')
                ]
            );
            
            return response()->json([
                'success' => 'true',
                'action' => 'added',
                'message' => 'Favori ajouté'
            ]);
        } 
        
    }
    
    //-------------------------------------------------------------------------- API POUR LISTE DES PRAYERS FAVORITES USER CONNECT --------------------------------------------------------------------------------
    
    public function favorite_user_prayers(Request $request)
    {
        $userid=$request->input('id_user');
        
        $allprayersData = [];
        
        /*
        $allprayer= DB::select('select ebm_prayers.*,name from ebm_prayers,ebm_prayer_categories,ebm_prayer_favorites 
        where ebm_prayers.id_prayer_cat=ebm_prayer_categories.id_prayer_cat 
        and ebm_prayers.idprayers=ebm_prayer_favorites.idprayers 
        and ebm_prayer_favorites.id_user=? order by created_at desc',[$userid]);
        */
        
        $allprayer= DB::select('select ebm_events_home_screen.*,name from ebm_events_home_screen,ebm_prayer_categories,ebm_events_favoris_prieres 
        where ebm_events_home_screen.idevents=ebm_events_favoris_prieres.idevents 
        and ebm_events_home_screen.idevents=ebm_events_favoris_prieres.idevents 
        and ebm_events_favoris_prieres.id_user=? and type=? order by created_at desc',[$userid,'prière']);
        
        foreach ($allprayer as $rowsallprayer)
        {
            $prayersId=$rowsallprayer->idevents;
            
            $allprayersData[$prayersId]=[
                'id' =>$rowsallprayer->idevents,
                'title' => $rowsallprayer->titre,
                'content' => $rowsallprayer->description,
                'categorie' => $rowsallprayer->name,
                'audio_url' => $rowsallprayer->audio_url,
                'audio_duration' => $rowsallprayer->duree_minutes,
                'favories' =>[],
            ];
            
            
            $dataviewfavories= DB::select('select * from ebm_events_favoris_prieres where idevents=?',[$rowsallprayer->idevents]); 
            foreach ($dataviewfavories as $rowviewfavories)
            {
                $allprayersData[$prayersId]['favories'][] = [
                    'idfavorites' => $rowviewfavories->id_favoris_prieres,
                    'iduser' =>   $rowviewfavories->id_user,
                    'created_at' =>   $rowviewfavories->created_at,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
        }
    
        $resultprayerall = [
            'status' => 'true',
            'alldataprayers' => array_values($allprayersData),  
        ];
        return response()->json($resultprayerall);
        
    }
    
    //-------------------------------------------------------------------------- API POUR LISTE DES PRAYERS PAR CATEGORIE(Louanges,intercession,remerciement,delivrance) --------------------------------------------------------------------------------
    
    public function prayers_by_category(Request $request)
    {
        $idcatprayers=$request->input('id_catprayers');
        
        $allprayersData = [];
        
        /*
        $allprayer= DB::select('select ebm_prayers.*,name from ebm_prayers,ebm_prayer_categories where ebm_prayers.id_prayer_cat=ebm_prayer_categories.id_prayer_cat 
        and ebm_prayer_categories.id_prayer_cat=? order by created_at desc',[$idcatprayers]);
        */
        
        $allprayer= DB::select('select ebm_events_home_screen.*,name from ebm_events_home_screen,ebm_prayer_categories where ebm_events_home_screen.id_prayer_cat=ebm_prayer_categories.id_prayer_cat 
        and ebm_prayer_categories.id_prayer_cat=? and type=? order by created_at desc',[$idcatprayers,'prière']);
        
        foreach ($allprayer as $rowsallprayer)
        {
            $prayersId=$rowsallprayer->idevents;
            
            $allprayersData[$prayersId]=[
                'id' =>$rowsallprayer->idevents,
                'title' => $rowsallprayer->titre,
                'content' => $rowsallprayer->description,
                'categorie' => $rowsallprayer->name,
                'audio_url' => $rowsallprayer->audio_url,
                'audio_duration' => $rowsallprayer->duree_minutes,
                'favories' =>[],
            ];
            
            
            $dataviewfavories= DB::select('select * from ebm_events_favoris_prieres where idevents=?',[$rowsallprayer->idevents]); 
            foreach ($dataviewfavories as $rowviewfavories)
            {
                $allprayersData[$prayersId]['favories'][] = [
                    'idfavorites' => $rowviewfavories->id_favoris_prieres,
                    'iduser' =>   $rowviewfavories->id_user,
                    'created_at' =>   $rowviewfavories->created_at,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
        }
    
        $resultprayerall = [
            'status' => 'true',
            'alldataprayers' => array_values($allprayersData),  
        ];
        return response()->json($resultprayerall);
        
    }


}