<?php

namespace App\Livewire\Pengaturan;

use Livewire\Component;
use App\Models\Instagram as PM;
use Livewire\Attributes\On;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class Instagram extends Component
{
    public $nama, $aksi, $selectedId;
    protected $messages = [
        '*.required' => 'Tidak Boleh Kosong',
        '*.unique' => 'Data Sudah Ada'
    ];

    public function mount()
    {
        $this->aksi = "store";
    }

    public function store()
    {
        $this->validate(['nama' => 'required|unique:instagram_profile,username,NULL,id']);
        try {
            PM::create(['username' => $this->nama]);
            $this->reset_fields();
            $this->success();
        } catch (\Throwable $th) {
            $this->error();
        }
    }

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

        return $response->json();
    }

    public function refresh_feeds($id)
    {
        try {
            $profil = PM::find($id);
            $token = $profil->to_access_token->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);
            }
            $this->success();
        } catch (\Throwable $th) {
            $this->error('Gagal Refresh Feeds Instagram');
        }
    }

    public function refresh_token($id)
    {
        try {
            $profil = PM::find($id);
            $response = Http::accept('application/json')->get('https://graph.instagram.com/refresh_access_token', [
                'grant_type' => 'ig_refresh_token',
                'access_token' => $profil->to_access_token->access_token,
            ]);

            $newToken = $response->json();
            $profil->to_access_token()->updateOrCreate(['profile_id' => $id], [
                'profile_id' => $id,
                'access_token' => $newToken['access_token']
            ]);
            $this->success();
        } catch (\Throwable $th) {
            $this->error('Gagal Refresh Token Instagram');
        }
    }

    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();
    }

    #[On('destroy')]
    public function destroy($id)
    {
        try {
            PM::find($id)->delete();
            $this->reset_fields();
            $this->success();
        } catch (\Throwable $th) {
            $this->error();
        }
    }

    public function reset_fields()
    {
        $this->reset(['nama', 'selectedId']);
        $this->resetValidation();
        $this->aksi = "store";
    }

    public function success()
    {
        $this->dispatch('swal:modal', [
            'type' => 'success',
            'message' => 'Berhasil Simpan Data!',
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function error($msg = null)
    {
        $this->dispatch('swal:modal', [
            'type' => 'error',
            'message' => 'Operasi Gagal! ' . $msg,
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function confirm($id)
    {
        $this->dispatch('swal:confirm', [
            'type' => 'warning',
            'message' => 'Hapus Data?',
            'text' => 'Data Tidak Dapat Dikembalikan!',
            'id' => $id
        ]);
    }

    public function remove()
    {
        $this->dispatch('swal:modal', [
            'type' => 'success',
            'message' => 'Data Berhasil Dihapus!',
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function render()
    {
        $data = PM::withCount('to_access_token')->get();
        return view('livewire.pengaturan.instagram', compact('data'));
    }
}
