<?php
/*
 * SOFTWARE LICENSE INFORMATION
 *
 * Copyright (c) 2017 Buttonizer, all rights reserved.
 *
 * This file is part of Buttonizer
 *
 * For detailed information regarding to the licensing of
 * this software, please review the license.txt or visit:
 * https://buttonizer.pro/license/
 */

namespace Buttonizer\Api\Connection;

use Buttonizer\Utils\ApiRequest;
use Buttonizer\Utils\ButtonizerAccount;
use Buttonizer\Utils\PermissionCheck;
use Buttonizer\Utils\Settings;
use Buttonizer\Utils\SiblingPlugins;

/**
 * Disconnect API
 * Invalidates External Access Token and removes data
 *
 * @endpoint /wp-json/buttonizer/disconnect
 * @methods POST
 */
class Disconnect
{
    private static $continueIfStatus = ["buttonizer_token_expired",  "buttonizer_api_request_failed", "buttonizer_api_server_error", "buttonizer_api_not_reachable"];

    /**
     * Register route
     */
    public function registerRoute()
    {
        register_rest_route('buttonizer', '/disconnect', [
            [
                'methods'  => ['POST'],
                'args' => [
                    'nonce' => [
                        'validate_callback' => function ($value) {
                            return wp_verify_nonce($value, 'wp_rest');
                        },
                        'required' => true
                    ],
                ],
                'callback' => [$this, 'disconnect'],
                'permission_callback' => function () {
                    return PermissionCheck::hasPermission();
                }
            ]
        ]);
    }

    /**
     * Disconnect
     *
     * @param bool $disconnectSiblings Whether to also disconnect sibling Buttonizer plugins.
     *                                  true  = UI "Disconnect" button (explicit user action)
     *                                  false = uninstall hook (only this plugin is being removed)
     */
    public function disconnect($disconnectSiblings = true)
    {
        // Only revoke the token server-side if this is an explicit disconnect
        // or if no sibling plugin still needs the shared token.
        if ($disconnectSiblings || SiblingPlugins::findConnectedSibling() === null) {
            $result = ApiRequest::post("/disconnect");

            if (is_a($result, 'WP_Error') && !in_array($result->get_error_code(), self::$continueIfStatus)) {
                return $result;
            }
        }

        // Set last synced at
        Settings::setSetting("last_synced_at", null);
        Settings::setSetting("finished_setup", false);
        Settings::setSetting("site_id", null);

        // Save synced info
        Settings::saveUpdatedSettings();

        // Remove API token
        ApiRequest::deleteApiToken();

        // Erase account settings
        ButtonizerAccount::emptyAccountSettings();

        // Disconnect all sibling Buttonizer plugins
        if ($disconnectSiblings) {
            SiblingPlugins::disconnectAllSiblings();
        }

        return [
            'status' => 'success'
        ];
    }
}
