<?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 testimonyController extends Controller
{
    
    //LISTE DES CATEGORIES
    
    public function categorie_testimony()
    {
        $testimony_categories= DB::select('select ebm_categories.* from ebm_categories');
        $testimonycategories = [
            'success' => 'true',
            'prayercategories' => array_values($testimony_categories),  
        ];
        return response()->json($testimonycategories);
        
    }
    
    
    //Enregistre un témoignage dans la base de données
    public function storetemoignages(Request $request)
    {
        global $fileName,$namecategory,$urlfilestore;
        $user_id=$request->input('id_user');
        $category_id=$request->input('category_id');
        $name=$request->input('nom');
        $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');
        $folderPath = public_path("audiostestimony");
        
        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/audiostestimony/'.''.$fileName;
        }
        
        
        
        DB::table('ebm_temoignage')->insert(
            [
                'id_user' => $user_id,
                'id_category' => $category_id,
                'name' => $name,
                'content' => $content, 
                'audio_url' => $urlfilestore,  
                //'input_type' => $input_type,
                'created_at' => DB::raw('NOW()'), 
                'updated_at' => DB::raw('NOW()')
            ]
        );
        
        $category = DB::table('ebm_categories')->where('id_category', $category_id)->first();
        if(isset($category->id_category) and $category->id_category >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 témoignage de $namecategory $name";
            //$html = "Votre hébergement vient d'être réservé par $valnameusersx ,nombre de chambre réservé : $valnbofroom";
            if($content!='')
            {
                $html = "$senderName : $content";
            }
            else
            {
                $html = "$senderName : contenu audio";
            }
            
            if($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 TEMOIGNAGES --------------------------------------------------------------------------------
    
    public function all_testimony()
    {
        
        $alltestimonyData = [];
        
        $alltestimony= DB::select('select ebm_temoignage.*,ebm_categories.name as namecat from ebm_temoignage,ebm_categories where ebm_temoignage.id_category=ebm_categories.id_category order by created_at desc');
        foreach ($alltestimony as $rowstestimony)
        {
            $testimonyId=$rowstestimony->id_temoignage;
            
            $alltestimonyData[$testimonyId]=[
                'id' =>$rowstestimony->id_temoignage,  
                'id_user' => $rowstestimony->id_user,
                'name' => $rowstestimony->name,
                'content' => $rowstestimony->content,
                'categorie' => $rowstestimony->namecat,
                'audio_url' => $rowstestimony->audio_url,
                'created_at' => $rowstestimony->created_at,
                'favories' =>[],
            ];
            
            
            $dataviewfavories= DB::select('select * from ebm_temoignage_favorie where id_temoignage=?',[$rowstestimony->id_temoignage]); 
            foreach ($dataviewfavories as $rowviewfavories)
            {
                $alltestimonyData[$testimonyId]['favories'][] = [
                    'idfavorites' => $rowviewfavories->id_favoris_temoignage,
                    'iduser' =>   $rowviewfavories->id_user,
                    'created_at' =>   $rowviewfavories->created_at,
                    // Ajoutez d'autres attributs d'image ici
                ];
            }
            
        }
    
        $resulttestimonyall = [
            'status' => 'true',
            'alldataprayers' => array_values($alltestimonyData),  
        ];
        return response()->json($resulttestimonyall);
        
    }
    
    //-------------------------------------------------------------------------- API POUR SAVE/DELETE FAVORIE IN TEMOIGNAGE --------------------------------------------------------------------------------
    
    public function save_delete_favorietestimony(Request $request)
    {
        $idusers = $request->input('userId'); 
        $idtemoignage = $request->input('id_temoignage'); 
        
        $dbtestimonyfavorie = DB::table('ebm_temoignage_favorie')
        ->where('id_user', $idusers)
        ->where('id_temoignage', $idtemoignage)
        ->first();
        
        if(isset($dbtestimonyfavorie->id_favoris_temoignage) and $dbtestimonyfavorie->id_favoris_temoignage >0)
        {
            $deletedfavorie = DB::delete('delete from ebm_temoignage_favorie where id_user=? and id_temoignage=?',[$idusers,$idtemoignage]);
            
            return response()->json([
                'success' => 'true',
                'action' => 'removed',
                'message' => 'Favori supprimé'
            ]);
        }
        else
        {
            DB::table('ebm_temoignage_favorie')->insert(
                [
                    'id_user' => $idusers,
                    'id_temoignage' => $idtemoignage,
                    'created_at' => date('Y-m-d H:i:s')
                ]
            );
            
            return response()->json([
                'success' => 'true',
                'action' => 'added',
                'message' => 'Favori ajouté'
            ]);
        }  
    }
    
    
     
}
