<?php

namespace Itmar\SNS\Facebook;

use WP_REST_Request;
use WP_Error;


class TokenReceiver
{
    const OPTION_SECRET = 'itmar_sns_rest_secret';

    public function __construct()
    {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes()
    {
        register_rest_route('itmar-sns/v1', '/receive_facebook_token', [
            'methods' => 'POST',
            'callback' => [$this, 'handle_token'],
            'permission_callback' => [$this, 'permission_check'],

        ]);
    }

    /**
     * 権限チェック
     */
    public function permission_check(WP_REST_Request $request)
    {
        $secret   = "itmaroon_sns_rest_key";
        $received = $request->get_header('x-itmar-sns-secret');

        if (empty($secret) || ! is_string($received) || ! hash_equals($secret, $received)) {
            return new WP_Error(
                'rest_forbidden',
                __('Invalid signature.', 'itmaroon-social-post-sync'),
                ['status' => 403]
            );
        }

        return true;
    }

    public function handle_token($request)
    {
        $access_token = sanitize_text_field($request->get_param('access_token'));
        $expires_in   = intval($request->get_param('expires_in'));
        $granted_raw = wp_unslash($request->get_param('granted'));

        //JSONじゃなかったら空扱い
        $granted_array = json_decode($granted_raw, true);
        if (! is_array($granted_array)) {
            $granted_array = [];
        }

        // ここで「許可してもいい権限」だけにホワイトリストします
        $allowed_scopes = [
            'public_profile',
            'email',
            'pages_show_list',
            'pages_read_engagement',
            'business_management',
            'pages_manage_posts',
            'instagram_basic',
            'instagram_content_publish',
            'instagram_manage_comments',
        ];

        $granted_sanitized = array_values(array_intersect($granted_array, $allowed_scopes));

        if (!$access_token) {
            return new \WP_Error('missing_token', 'Access token is required', ['status' => 400]);
        }

        update_option('itmar_facebook_access_token', $access_token);
        update_option('itmar_facebook_expires_at', time() + $expires_in);
        update_option('itmar_facebook_granted', $granted_sanitized);

        $warnings = [];

        $user = $this->fetch_facebook_user($access_token);
        if (!empty($user)) {
            update_option('itmar_facebook_user', $user);

            $pages = $this->fetch_facebook_pages($access_token);
            if (!empty($pages)) {
                update_option('itmar_facebook_pages', $pages);
            } else {
                //Facebookページがない場合
                update_option('itmar_facebook_pages', []);
                delete_option('itmar_facebook_selected_page_id');
            }
        } else {
            delete_option('itmar_facebook_pages');
            $warnings[] = 'Failed to fetch Facebook user info. Page access disabled.';
        }

        return rest_ensure_response([
            'status' => 'success',
            'message' => 'Facebook token received and processed.',
            'warnings' => $warnings,
        ]);
    }

    private function fetch_facebook_user($access_token)
    {
        $res = wp_remote_get('https://graph.facebook.com/v21.0/me?fields=id,name,picture.width(200)&access_token=' . urlencode($access_token));
        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'] ?? '',
                'avatar_url' => $body['picture']['data']['url'] ?? '',
            ];
        }
        return null;
    }

    private function fetch_facebook_pages($access_token)
    {
        $response = wp_remote_get('https://graph.facebook.com/v21.0/me/accounts?limit=100&access_token=' . urlencode($access_token));
        if (is_wp_error($response)) return [];

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $data = $body['data'] ?? [];

        $pages = [];
        foreach ($data as $page) {
            $page_id = $page['id'];
            $name = $page['name'];
            $picture_url = "https://graph.facebook.com/{$page_id}/picture?redirect=false&type=normal";
            $picture_response = wp_remote_get($picture_url);
            $icon_url = '';
            if (!is_wp_error($picture_response)) {
                $picture_data = json_decode(wp_remote_retrieve_body($picture_response), true);
                if (isset($picture_data['data']['url'])) {
                    $icon_url = $picture_data['data']['url'];
                }
            }
            $pages[] = [
                'id' => $page_id,
                'name' => $name,
                'access_token' => $page['access_token'],
                'icon_url' => $icon_url,
            ];
        }

        return $pages;
    }
}
