<?php

namespace App\Utilities;

use Illuminate\Support\Facades\Http;
use App\Utilities\SocialMediaPost;
use Carbon\Carbon;

class SocialMedia
{
    public static function load() 
    {
        return cache()->tags(['social-media'])->remember('social_media_feed', env('production') ? 180 : 10, function() {
            return collect(
                (new SocialMedia)->instagram()
               // use array if u use facebook (new SocialMedia)->facebook(),
            )
            //->flatten()
            ->sortByDesc(function($post) {
                return $post->date;
            })
            ->values();
        });
    }

public function instagram()
{
    $token = env('INSTAGRAM_TOKEN');
    $igBusinessId = env('IG_BUSINESS_ID');
    $oEmbedToken = env('FB_IG_APP_TOKEN');

    $response = Http::get("https://graph.facebook.com/v19.0/{$igBusinessId}/media?fields=id,caption,media_type,media_url,thumbnail_url,permalink,timestamp&access_token={$token}&limit=50");

    if (!$response->ok()) {
        $response->throw();
    }

    return collect($response->object()->data)->take(25)->map(function ($post) use ($oEmbedToken, $token) {
        $embedHtml = null;
        $mediaUrl = $post->media_url ?? '';

        // Retry if video and no media_url
       // if ($post->media_type === 'VIDEO' && empty($mediaUrl)) {
         //   $mediaUrl = $this->retryFetchMediaUrl($post->id, $token);
       // }

        // Only do oEmbed for non-video
        if (in_array($post->media_type, ['IMAGE', 'CAROUSEL_ALBUM'])) {
            $oEmbedResponse = Http::get('https://graph.facebook.com/v19.0/instagram_oembed', [
                'url' => $post->permalink,
                'access_token' => $oEmbedToken,
            ]);

            if ($oEmbedResponse->ok() && isset($oEmbedResponse['html'])) {
                $embedHtml = $oEmbedResponse['html'];
            }
        }

        return new SocialMediaPost(
            $post->id,
            'instagram',
            $post->permalink,
            Carbon::parse($post->timestamp),
            $post->caption ?? '',
            $mediaUrl,
            $post->media_type ?? '',
	    $embedHtml,
	    $post->thumbnail_url ?? null
        );
    })
    ->filter(function ($post) {
        // Remove posts with blank media URLs (especially videos)
        return !empty($post->image);
    })
    ->values();
}


//private function retryFetchMediaUrl($postId, $token, $retries = 3, $delay = 1)
//{
//    for ($i = 0; $i < $retries; $i++) {
//        $retryResponse = Http::get("https://graph.facebook.com/v19.0/{$postId}?fields=media_url&access_token={$token}");
//
  //      if ($retryResponse->ok() && !empty($retryResponse['media_url'])) {
    //        return $retryResponse['media_url'];
      //  }

        //sleep($delay); // Wait before retrying
   // }
//
 //   return ''; // Fallback if retries fail
//}




    public function facebook() 
    {
        $page_token = cache()->tags(['tokens'])->rememberForever('facebook_page_token', function() {
            return collect(Http::get('https://graph.facebook.com/me/accounts?access_token='.env('FACEBOOK_TOKEN'))->object()->data)->firstWhere('name', 'Brentwood College School')->access_token;
        });
        
        $response = Http::get('https://graph.facebook.com/'.env('FACEBOOK_PAGE_ID').'/feed?fields=full_picture,message,published,created_time,permalink_url&access_token='.$page_token);

        if ($response->ok()) {
            return collect($response->object()->data)->map(function($post) {
                return new SocialMediaPost(
                    $post->id,
                    'facebook',
                    $post->permalink_url,
                    Carbon::parse($post->created_time),
                    property_exists($post, 'message') ? $post->message : null,
                    property_exists($post, 'full_picture') ? $post->full_picture : null,
                );
            });
        } else  {
            $response->throw();
        }
    }
}
