<?php

namespace App\Http\Controllers;

use Common\Core\BaseController;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Http;

use App\Models\Genre;
use App\Models\ProductionCountry;
use App\Models\Title;
use App\Models\Image;
use App\Models\Keyword;
use App\Models\Person;
use App\Models\Video;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Illuminate\Support\Facades\DB;

class ApiTmdbController extends BaseController
{

    protected $baseUrl = 'https://api.themoviedb.org/3';
    protected $token = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJjYTJiNzZmNDkyZWQxNGFmMmU2Njk4N2E2YmRjZDY0ZiIsIm5iZiI6MTc0OTQ2MzY4NC41NjksInN1YiI6IjY4NDZiMjg0NDQ5MDEyOGMxMzNmYzk1NiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.PXMuq0fxXaC2kR1qrd-LDeezz0HAhL8o3-4QGaik0D4";

    private array $sizes = [
        'original' => null,
        'large' => 500,
        'medium' => 300,
        'small' => 92,
    ];

    public function index()
    {
        $movieId = request('movieId');
        //$movieId =  1284120;
        
        /****************************************** */
        $responseMovie = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->token,
            'Accept' => 'application/json',
        ])->get("$this->baseUrl/movie/$movieId", [
            'language' => 'fr-FR'
        ]);

        $movie = $responseMovie->successful() ? $responseMovie->json() : [];

        
        $title = Title::create([
                    'imdb_id' => $movie['id'],
                    'backdrop' => "https://image.tmdb.org/t/p/original".$movie['backdrop_path'],
                    'poster' => "https://image.tmdb.org/t/p/original".$movie['poster_path'],
                    'name' => $movie['title'],
                    'original_title' => $movie['original_title'],
                    'language' => $movie['original_language'],
                    'is_series' => false,
                    'release_date' => $movie['release_date'],
                    'tagline' => $movie['tagline'],
                    'description' => $movie['overview'],
                    'runtime' => $movie['runtime'],
                    //////////////////'certification' => $movie[''],
                    'budget' => $movie['budget'],
                    'revenue' => $movie['revenue'],
                    'popularity' => $movie['popularity'],
                    'language' => $movie['original_language'],
                    'adult' => $movie['adult'],
                    'type' => 'movie',
                    'tmdb_vote_average' => $movie['vote_average']
                ]);

        
        $genres = $countrys = [];

        foreach($movie['production_countries'] as $country)
        {
            $productionCountry = ProductionCountry::updateOrCreate(
                ['name' => $country['iso_3166_1']],
                ['name' => $country['iso_3166_1'], 'display_name' => $country['name']
             ]);
            $countrys[] =  $productionCountry->id;
        }

        foreach($movie['genres'] as $genre)
        {
            $genre = Genre::updateOrCreate(
                ['name' => $genre['name']],
                [
                'name' => $genre['name'], 
                'display_name' => $genre['name']
            ]);
            $genres[] = $genre->id;
        }
       
        $title->productionCountries()->attach($countrys);
        $title->genres()->attach($genres);
        
        /*********************************************** */
        $responseMovieKeyword = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->token,
            'Accept' => 'application/json',
        ])->get("$this->baseUrl/movie/$movieId/keywords", [
            'language' => 'fr-FR'
        ]);

        $movieKeywords = $responseMovieKeyword->successful() ? $responseMovieKeyword->json() : [];
        
        $keywords = [];
        foreach($movieKeywords['keywords'] as $valKey)
        {
            $keyword = Keyword::updateOrCreate(
                ['name' => $valKey['name']],
                [
                'name' => $valKey['name'], 
                'display_name' => $valKey['name']
            ]);
            $keywords[] = $keyword->id;
        }
        $title->keywords()->attach($keywords);

        /************************************************/
        
        $responseMovieCredits = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->token,
            'Accept' => 'application/json',
        ])->get("$this->baseUrl/movie/$movieId/credits", [
            'language' => 'fr-FR'
        ]);

        $movieCredits = $responseMovieCredits->successful() ? $responseMovieCredits->json() : [];
        
        
        foreach($movieCredits['cast'] as $cast)
        {
            $person_id = $this->getPeopleByTMDBid($cast['id']);
            $title->createCredit([
                'person_id'=>$person_id,
                'department'=> "actors",
                'job'=>"actor",
                'order'=>$cast['order'],
                'character'=>$cast['character'],
            ]);
            
        }

        foreach($movieCredits['crew'] as $cast)
        {
            $person_id = $this->getPeopleByTMDBid($cast['id']);
            $title->createCredit([
                'person_id'=>$person_id,
                'department'=> $cast['department'],
                'job'=>$cast['job'],
            ]);
            
        }

        /********************* Videos *******************************/

        $responseMovieVideos = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->token,
            'Accept' => 'application/json',
        ])->get("$this->baseUrl/movie/$movieId/videos", [
            'language' => 'fr-FR'
        ]);

        $MovieVideos = $responseMovieVideos->successful() ? $responseMovieVideos->json() : [];
        foreach($MovieVideos['results'] as $keyV =>$video)
        {
            if( ($video['site'] == "YouTube") && ($video['type'] == "Trailer") )
            {
                Video::create([
                    'name'=>$video['name'], 
                    'src'=>"https://youtube.com/embed/".$video['key'], 
                    'type'=>'embed', 
                    'quality'=> ($video['size']==1080)? "1080p" : null, 
                    'title_id'=>$title->id, 
                    'origin'=>"local", 
                    'downvotes'=>0, 
                    'upvotes'=>0, 
                    'approved'=>1, 
                    'order'=>$keyV, 
                    'user_id'=>auth()->id(), 
                    'language'=>$video['iso_639_1'], 
                    'category'=>'trailer', 
                ]);
            }
        }

        /***********************Images***************************/    
        
        $responseMovieImages = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->token,
            'Accept' => 'application/json',
        ])->get("$this->baseUrl/movie/$movieId/images", []);
        
        $movieImages = $responseMovieImages->successful() ? $responseMovieImages->json() : [];
        for($i=0; $i<=5; $i++)
        {
            $nameFileImage = isset($movieImages['backdrops'][$i]['file_path'])? $movieImages['backdrops'][$i]['file_path'] : null;
            if($nameFileImage)
            {
                $url = $this->saveImage("https://image.tmdb.org/t/p/original$nameFileImage");
                
                Image::where('model_type', Title::MODEL_TYPE)
                    ->where('model_id', $title->id)
                    ->increment('order');

                Image::create([
                    'url' => $url,
                    'type' => 'backdrop',
                    'source' => 'local',
                    'model_type' => Title::MODEL_TYPE,
                    'model_id' => $title->id,
                    'order' => 0
                ]);
            }
        }
        
    }



    function getPeopleByTMDBid($tmdb_id)
    {
        $person = DB::table('people')->where('tmdb_id', $tmdb_id)->first();

        if(!$person)
        {
           $responsePeople = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->token,
                'Accept' => 'application/json',
            ])->get("$this->baseUrl/person/$tmdb_id", [
                'language' => 'fr-FR'
            ]);

            $people = $responsePeople->successful() ? $responsePeople->json() : [];
            $person = Person::create([
                    'tmdb_id' => $people['id'],
                    'name' => $people['name'],
                    'description'=>$people['biography'], 
                    'gender'=>$people['gender'], 
                    'birth_date'=>$people['birthday'], 
                    'birth_place'=>$people['place_of_birth'], 
                    'poster'=>"https://image.tmdb.org/t/p/w500".$people['profile_path'],
                    'imdb_id'=>$people['imdb_id'], 
                    'known_for'=>$people['known_for_department'], 
                    'popularity'=>$people['popularity'], 
                    'death_date'=>$people['deathday'], 
                    'adult'=>$people['adult'], 
                ]);
        }
        return $person->id ;
    }


    public function saveImage(string $urlImage): string
    {
        $hash = Str::random(30);
        $manager = new ImageManager(new Driver());
        
        // Télécharger l'image depuis l'URL
        $imageContent = file_get_contents($urlImage);
        $tempFile = tempnam(sys_get_temp_dir(), 'img');
        file_put_contents($tempFile, $imageContent);
        
        try {
            $img = $manager->read($tempFile);
            
            // Déterminer l'extension à partir de l'URL ou utiliser jpeg par défaut
            $pathInfo = pathinfo(parse_url($urlImage, PHP_URL_PATH));
            $extension = $pathInfo['extension'] ?? 'jpeg';
            $extension = in_array(strtolower($extension), ['jpg', 'jpeg', 'png']) ? $extension : 'jpeg';

            foreach ($this->sizes as $key => $size) {
                if ($size) {
                    $img->scale($size);
                }

                Storage::disk('public')->put(
                    "media-images/backdrops/$hash/$key.$extension",
                    $extension === 'png' ? $img->toPng() : $img->toJpeg(),
                );
            }

            $endpoint = config('common.site.file_preview_endpoint');
            $uri = "media-images/backdrops/$hash/original.$extension";
            return $endpoint
                ? "$endpoint/storage/$uri"
                : Storage::disk('public')->url($uri);
        } finally {
            // Nettoyer le fichier temporaire
            if (file_exists($tempFile)) {
                unlink($tempFile);
            }
        }
    }
}
