<?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 ContenusController extends Controller
{
    public function viewsectioncategorie()
    {
        global $catcontentsId,$nbrenseignement,$nbrpodcasts,$nbrreplays;
        
        $nbrenseignement=0;
        $nbrpodcasts=0;
        $nbrreplays=0;
        
        $contentcat = [];
        $datacontentcat= DB::select('select * from ebm_contents_categories');
        foreach ($datacontentcat as $rowcontentcat)
        {
            $catcontentsId=$rowcontentcat->idcatcontents;
            
            /*
            $countenseignement= DB::select('select count(idcontents) as nbrcontents from ebm_contents where idcatcontents=?',[$rowcontentcat->idcatcontents]);
            foreach ($countenseignement as $rowenseignement)
            {
                if($rowcontentcat->idcatcontents==1)
                {
                    $nbrenseignement = $rowenseignement->nbrcontents;
                }
                elseif($rowcontentcat->idcatcontents==2)
                {
                    $nbrpodcasts = $rowenseignement->nbrcontents;
                }
                else
                {
                    $nbrreplays = $rowenseignement->nbrcontents;
                }
            }
            */
            
            // Compter le nombre de contenus liés à cette catégorie
            $count = DB::table('ebm_contents')
            ->where('idcatcontents', $rowcontentcat->idcatcontents)
            ->count();
            
            $contentcat[$catcontentsId]= [
                'id' => $rowcontentcat->idcatcontents,
                'name' => $rowcontentcat->name,
                'count' => $count,
                /*
                'nbrenseignement' => $nbrenseignement,
                'nbrpodcasts' => $nbrpodcasts,
                'nbrreplays' => $nbrreplays,
                */
                'created_at' => $rowcontentcat->created_at,
            ];
        }
        
        $resultcontentcat = [
            'statDatacontentcat' => 'success',
            'datacontentcat' => array_values($contentcat),  
        ];
        return response()->json($resultcontentcat);
    }
    
    public function viewcontentscategorie(Request $request)
    {
        global $contentsId,$varposition;
        
        $idcategorie=$request->get('id_categorie');
        $userId=$request->get('userId');
        
        $content = [];
        $datacontent= DB::select('select * from ebm_contents where idcatcontents=? order by created_at DESC LIMIT 10',[$idcategorie]);
        foreach ($datacontent as $rowcontent)
        {
            $contentsId=$rowcontent->idcontents;
            
            $favories = DB::table('ebm_contents_user_favorites')
            ->where('id_user', $userId)
            ->where('idcontents', $contentsId)
            ->first();
            if(isset($favories->idfavorites) and $favories->idfavorites >0){$isLiked=true;}else{$isLiked=false;}
            
            $position = DB::table('ebm_contents_user_listens')
            ->where('id_user', $userId)
            ->where('idcontents', $contentsId)
            ->first();
            if(isset($position->idlistens) and $position->idlistens >0){$varposition=$position->position;}
            
            $content[$contentsId]= [
                'id' => $rowcontent->idcontents,
                'title' => $rowcontent->title,
                'file_url' => $rowcontent->file_url,
                'duration' => $rowcontent->duration,
                'release_date' => $rowcontent->release_date, 
                'speaker_name' => $rowcontent->speaker_name,
                'created_at' => $rowcontent->created_at,
                'isLikedByCurrentUser' => $isLiked,
                'position' => $varposition,
            ];
        }
        
        $resultcontent = [
            'statDatacontent' => 'success',
            'datacontent' => array_values($content),  
        ];
        return response()->json($resultcontent);
    }
    
    public function viewallcontents(Request $request)
    {
        global $contentsId;
        
        $idcategorie=$request->get('id_categorie');
        $userId=$request->get('userId');
        
        $allcontent = [];
        $datacontentall= DB::select('select * from ebm_contents where idcatcontents=? order by created_at DESC',[$idcategorie]);
        foreach ($datacontentall as $rowcontentall)
        {
            $contentsId=$rowcontentall->idcontents;
            
            $favories = DB::table('ebm_contents_user_favorites')
            ->where('id_user', $userId)
            ->where('idcontents', $contentsId)
            ->first();
            if(isset($favories->idfavorites) and $favories->idfavorites >0){$isLiked=true;}else{$isLiked=false;}
            
            $allcontent[$contentsId]= [
                'id' => $rowcontentall->idcontents,
                'title' => $rowcontentall->title,
                'file_url' => $rowcontentall->file_url,
                'duration' => $rowcontentall->duration,
                'release_date' => $rowcontentall->release_date, 
                'speaker_name' => $rowcontentall->speaker_name,
                'created_at' => $rowcontentall->created_at,
                'isLikedByCurrentUser' => $isLiked,
            ];
        }
        
        $resultcontentall = [
            'statallcontent' => 'success',
            'alldatacontent' => array_values($allcontent),  
        ];
        return response()->json($resultcontentall);
    }
    
    //-------------------------------------------------------------------------- API POUR SAVE/DELETE FAVORIE IN CONTENTS --------------------------------------------------------------------------------
    
    public function save_delete_favorie_contents(Request $request)
    {
        $userId=$request->get('userId');
        $idcontents=$request->get('idcontents');
        $duration=$request->get('duration');
        
        $dblikefavorie = DB::table('ebm_contents_user_favorites')
        ->where('id_user', $userId)
        ->where('idcontents', $idcontents)
        ->first();
        
        if(isset($dblikefavorie->idfavorites) and $dblikefavorie->idfavorites >0)
        {
            $deletedfavorie = DB::delete('delete from ebm_contents_user_favorites where id_user=? and idcontents=?',[$userId,$idcontents]);
            
            return response()->json([
                'success' => 'true',
                'action' => 'removed',
                'message' => 'Favori supprimé'
            ]);
        }
        else
        {
            DB::table('ebm_contents_user_favorites')->insert(
                [
                    'id_user' => $userId,
                    'idcontents' => $idcontents,
                    'created_at' => date('Y-m-d H:i:s')
                ]
            );
            
            return response()->json([
                'success' => 'true',
                'action' => 'added',
                'message' => 'Favori ajouté'
            ]);
        }  
    }
    
    
    //-------------------------------------------------------------------------- API POUR SAVE LA PROGRESSION D'ECOUTE IN CONTENTS --------------------------------------------------------------------------------
    
    public function save_listens_contents(Request $request) 
    {
        global $duration,$progress;
        
        $userId=$request->get('userId');
        $idcontents=$request->get('contentId');
        $position=$request->get('position');
        $duration=$request->get('duration');
        
        $durerlistens = DB::table('ebm_contents')
        ->where('idcontents', $idcontents)
        ->first();
        
        if(isset($durerlistens->idcontents) and $durerlistens->idcontents >0)
        {
            $duration=$durerlistens->duration;
        }
        
        
        if ($duration > 0 && $position >= 0) {$progress = min(100, round(($position / $duration) * 100));}else{$progress = 0;}
        
        
        $dblistens = DB::table('ebm_contents_user_listens')
        ->where('id_user', $userId)
        ->where('idcontents', $idcontents)
        ->first();
        
        if(isset($dblistens->idlistens) and $dblistens->idlistens >0)
        {
            DB::table('ebm_contents_user_listens')
            ->where('id_user', $userId)
            ->where('idcontents', $idcontents)
            ->update([
                'position' => $position,
                'progress' => $progress,
                'created_at' => date('Y-m-d H:i:s')
            ]);
        }
        else  
        {
            DB::table('ebm_contents_user_listens')->insert(
                [
                    'id_user' => $userId,
                    'idcontents' => $idcontents,
                    'position' => $position,
                    'progress' => $progress,
                    'created_at' => date('Y-m-d H:i:s')
                ]
            );
        }
        
        DB::table('ebm_contents_user_listen_stats')->insert(
            [
                'id_user' => $userId,
                'idcontents' => $idcontents,
                'position' => $position,
                'progress' => $progress,
                'listened_at' => DB::raw('NOW()')
            ]
        );
        
        return response()->json([
            'success' => 'true',
        ]);
        
    }
    
    
    //-------------------------------------------------------------------------- API POUR VOIR LA LISTE DES PROGRESSIONS D'ECOUTE IN CONTENTS D'UN USER --------------------------------------------------------------------------------
    
    public function listening_contents(Request $request) 
    {
        global $contentsId;
        
        $idcategorie=$request->get('categoryId');
        $userId=$request->get('userId');
        
        $contentlistening = [];
        $datacontent= DB::select('select ebm_contents_user_listens.*,title,file_url,duration,release_date,speaker_name,idcatcontents from ebm_contents,ebm_contents_user_listens 
        where ebm_contents.idcontents=ebm_contents_user_listens.idcontents   
        and ebm_contents.idcatcontents=? and ebm_contents_user_listens.id_user=? order by ebm_contents_user_listens.created_at DESC',[$idcategorie,$userId]);
        foreach ($datacontent as $rowcontent)
        {
            $contentsId=$rowcontent->idcontents;
            
            
            $contentlistening[$contentsId]= [
                'id' => $rowcontent->idcontents,
                'title' => $rowcontent->title,
                'file_url' => $rowcontent->file_url,
                'duration' => $rowcontent->duration,
                'position' => $rowcontent->position, 
                'speaker_name' => $rowcontent->speaker_name,
                'categoryId' => $rowcontent->idcatcontents,
            ];
        }
        
        $resultlistening = [
            'statDatalistening' => 'success',
            'datalistening' => array_values($contentlistening),  
        ];
        return response()->json($resultlistening);
        
    }
}


