<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\InstagramAccessToken;
use App\Models\InstagramFeeds;
use App\Models\Instagram as PM;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class RefreshFeed extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'instagram:refresh-feed';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Refresh Instagram Feeds';

    /**
     * Execute the console command.
     */
    public function handle()
    {

        try {
            $allTokens = InstagramAccessToken::all();
            foreach ($allTokens as $pr) {
                $profil = PM::find($pr->profile_id);
                $token = $pr->access_token;
                $media = $this->ambil_media($token);
                $data = collect($media['data']);
                $nextUrl = $media['paging']['next'] ?? null;
                $this->store_feed($data, $profil);
                while ($nextUrl) {
                    $next = $this->fetch_paging($nextUrl);
                    $nextData = collect($next['data']);
                    $nextUrl = $next['paging']['next'] ?? null;
                    $this->store_feed($nextData, $profil);
                }
            }
            Log::info('Berhasil Refresh Feeds');
            $this->info('Berhasil Refresh Feeds');
        } catch (\Throwable $th) {
            Log::error($th->getMessage());
            $this->error('Gagal Refresh Feeds');
        }
    }

    public function ambil_media($token)
    {
        $response = Http::accept('application/json')->get('https://graph.instagram.com/me/media', [
            'fields' => 'caption,id,media_type,media_url,thumbnail_url,permalink,children{media_type,media_url},timestamp',
            'access_token' => $token,
            'limit' => 100
        ]);

        return $response->json();
    }

    public function store_feed($data, $profil)
    {
        $data->map(function ($item) use ($profil) {
            // if (!empty($item['caption']) && Str::contains($item['caption'], ['stunting'])) {
                $profil->to_media()->updateOrCreate(['media_id' => $item['id']], [
                    'media_id' => $item['id'],
                    'media_type' => $item['media_type'],
                    'media_url' => $item['media_url'],
                    'caption' => $item['caption'] ?? null,
                    'thumbnail_url' => $item['thumbnail_url'] ?? null,
                    'permalink' => $item['permalink'],
                    'children' => !empty($item['children']) ? $item['children']['data'] : null,
                    'timestamp' => $item['timestamp']
                ]);
            // }
        });
    }

    public function fetch_paging($url)
    {
        $response = Http::accept('application/json')->get($url);
        return $response->json();
    }
}
