<?php

namespace Itmar\SNS\Instagram;

use WP_Error;
use Itmar\SNS\Tool\HttpTool;

class ApiHelper
{
    private $pages;
    private $selected_page_id;
    private $access_token;
    private $ig_user_id;

    public function __construct()
    {
        // facebookページ関連の情報をセット
        $this->pages = get_option('itmar_facebook_pages', []);
        $sel_num = (int)get_option('itmar_facebook_selected_page_id', '');
        $this->selected_page_id = isset($this->pages[$sel_num]['id']) ? $this->pages[$sel_num]['id'] : null;
        $this->access_token = $this->pages[$sel_num]['access_token'] ?? null;

        if ($this->access_token && $this->selected_page_id) {
            $res = wp_remote_get("https://graph.facebook.com/v20.0/{$this->selected_page_id}?fields=instagram_business_account&access_token=" . urlencode($this->access_token));
            if (!is_wp_error($res)) {
                $body = json_decode(wp_remote_retrieve_body($res), true);
                $this->ig_user_id = $body['instagram_business_account']['id'] ?? null;
            }
        }
    }

    public function get_user_info()
    {
        if (!$this->ig_user_id || !$this->access_token) return null;

        $fields = [
            'id',
            'name',
            'username',
            'profile_picture_url',
            'followers_count',
            'media_count',
            'biography',
            'website'
        ];

        $url = "https://graph.facebook.com/v20.0/{$this->ig_user_id}?" .
            "fields=" . implode(',', $fields) .
            "&access_token=" . urlencode($this->access_token);

        $res = wp_remote_get($url);
        if (is_wp_error($res)) return null;

        $body = json_decode(wp_remote_retrieve_body($res), true);
        if (isset($body['id'])) {
            return [
                'id'               => $body['id'],
                'name'             => $body['name'] ?? '',
                'username'         => $body['username'] ?? '',
                'avatar_url'       => $body['profile_picture_url'] ?? '',
                'followers_count'  => $body['followers_count'] ?? null,
                'media_count'      => $body['media_count'] ?? null,
                'biography'        => $body['biography'] ?? '',
                'website'          => $body['website'] ?? '',
            ];
        }

        return null;
    }


    public function create_post($id, $caption, $media_arr = [])
    {
        if (!$this->ig_user_id || !$this->access_token) {
            return new WP_Error('Error', 'Instagramアカウントまたはトークンが見つかりません。');
        }

        $video = null;
        $images = [];

        foreach ($media_arr as $item) {
            if ($item['type'] === 'video') {
                if ($video) return new WP_Error('Error', '動画は1件のみ許可されます');
                $video = $item['url'];
            } elseif ($item['type'] === 'img') {
                $images[] = $item['url'];
            }
        }

        if ($video && count($images) > 0) {
            return new WP_Error('Error', '画像と動画を同時に投稿することはできません');
        }

        // 動画投稿（REELS）
        if ($video) {
            //AWS S3 署名付き put_urlを要求
            $post_data = [
                'id' => $id,
                'caption' => $caption,
                'media_type' => 'REELS',
                'access_token' => $this->access_token,
                'ig_user_id' => $this->ig_user_id
            ];
            $result = HttpTool::upload_to_s3($video, $post_data);
            //ここでは要求するだけで終了
            if (!$result) {
                return new WP_Error('Error', '動画の生成の要求に失敗しました');
            } else {
                update_option('itmar_wait_video', $id);
                return 'WAIT,動画の生成中。しばらくお待ちください。';
            }
        }
        // カルーセル投稿
        elseif (count($images) > 1) {
            $children = [];

            foreach ($images as $img_url) {
                //awsサーバーに保存して署名付きのURLを取得
                $get = HttpTool::upload_to_s3($img_url, $this->access_token);
                if (!is_wp_error($get)) {
                    $res = wp_remote_post("https://graph.facebook.com/v20.0/{$this->ig_user_id}/media", [
                        'body' => [
                            'image_url' => $get['get_url'],
                            'is_carousel_item' => 'true',
                            'access_token' => $this->access_token,
                        ],
                        'timeout' => 15,
                    ]);

                    //アップロード画像を削除指示
                    $api_base = rtrim(ITMAR_AWS_BASE_URL, '/');
                    wp_remote_request($api_base . '/upload?media_path=' . $get['key'], [
                        'method'  => 'DELETE',
                        'timeout' => 10,
                    ]);

                    if (is_wp_error($res)) return $res;
                    $body = json_decode(wp_remote_retrieve_body($res), true);
                    if (empty($body['id'])) {
                        return new WP_Error('Error', 'カルーセル画像の作成に失敗しました');
                    }
                    $children[] = $body['id'];
                } else {
                    return $get; //エラーを返す
                }
            }

            $res = wp_remote_post("https://graph.facebook.com/v20.0/{$this->ig_user_id}/media", [
                'body' => [
                    'caption' => $caption,
                    'media_type' => 'CAROUSEL',
                    'children' => implode(',', $children),
                    'access_token' => $this->access_token,
                ],
                'timeout' => 15,
            ]);

            if (is_wp_error($res)) return $res;
            $body = json_decode(wp_remote_retrieve_body($res), true);
            if (empty($body['id'])) {
                return new WP_Error('Error', 'カルーセルコンテナの作成に失敗しました');
            }

            $container_id = $body['id'];
        }
        // 単一画像投稿
        elseif (count($images) === 1) {
            $img_url = $images[0];


            //awsサーバーに保存して署名付きのURLを取得
            $get = HttpTool::upload_to_s3($img_url, $this->access_token);

            if (!is_wp_error($get)) {
                $res = wp_remote_post("https://graph.facebook.com/v20.0/{$this->ig_user_id}/media", [
                    'body' => [
                        'image_url' => $get['get_url'],
                        'caption' => $caption,
                        'access_token' => $this->access_token,
                    ],
                    'timeout' => 15,
                ]);

                //アップロード画像を削除指示
                $api_base = rtrim(ITMAR_AWS_BASE_URL, '/');
                wp_remote_request($api_base . '/upload?media_path=' . rawurlencode($get['key']), [
                    'method'  => 'DELETE',
                    'timeout' => 10,
                ]);

                if (is_wp_error($res)) return $res;
                $body = json_decode(wp_remote_retrieve_body($res), true);
                if (empty($body['id'])) {
                    return new WP_Error('Error', '画像コンテナの作成に失敗しました');
                }

                $container_id = $body['id'];
            } else {
                return $get;
            }
        }
        // 共通：メディアを公開
        $publish = wp_remote_post("https://graph.facebook.com/v20.0/{$this->ig_user_id}/media_publish", [
            'body' => [
                'creation_id' => $container_id,
                'access_token' => $this->access_token,
            ],
            'timeout' => 15,
        ]);

        if (is_wp_error($publish)) return $publish;
        $result = json_decode(wp_remote_retrieve_body($publish), true);

        return $result['id'] ?? new WP_Error('Error', 'Instagram投稿に失敗しました');
    }

    //Instagram投稿を取得（limit件ごと、afterによるページネーション）
    public function get_post($limit = 10, $after_cursor = null)
    {
        if (!$this->access_token || !$this->ig_user_id) {
            return null;
        }

        $endpoint = "https://graph.facebook.com/v20.0/{$this->ig_user_id}/media";

        $fields = [
            'id',
            'caption',
            'media_type',
            'media_url',
            'permalink',
            'timestamp',
            'thumbnail_url',
            'like_count',
            'comments_count',
            'children{media_type,media_url}'
        ];

        $args = [
            'access_token' => $this->access_token,
            'limit'        => $limit,
            'fields'       => implode(',', $fields),
        ];

        if ($after_cursor) {
            $args['after'] = $after_cursor;
        }

        $url = $endpoint . '?' . http_build_query($args);

        $response = wp_remote_get($url);

        if (is_wp_error($response)) {
            //error_log('[IG API] 投稿取得エラー: ' . $response->get_error_message());
            return null;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (!isset($body['data'])) {
            //error_log('[IG API] 投稿データが取得できませんでした');
            return null;
        }

        return [
            'data'   => $body['data'],
            'paging' => $body['paging']['cursors']['after'] ?? null,
        ];
    }
}
