<?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\Legacy\Api\Utils;

use Buttonizer\Utils\PermissionCheck;

/**
 * Revert API
 *
 * @endpoint /wp-json/buttonizer/revert
 * @methods POST
 */
class ApiRevert
{
    /**
     * Register route
     */
    public function registerRoute()
    {
        register_rest_route('buttonizer', '/revert', [
            [
                'methods'  => ['POST'],
                'args' => [
                    'nonce' => [
                        'validate_callback' => function ($value) {
                            return wp_verify_nonce($value, 'wp_rest');
                        },
                        'required' => true
                    ],
                ],
                'callback' => [$this, 'revert'],
                'permission_callback' => function () {
                    return PermissionCheck::hasPermission();
                }
            ]
        ]);
    }

    /**
     * Publish buttons
     */
    public function revert()
    {
        // Register settings
        register_setting('buttonizer', 'buttonizer_buttons', [
            'type' => 'array',
            'sanitize_callback' => function ($value) {
                return is_array($value) ? $value : [];
            }
        ]);
        register_setting('buttonizer', 'buttonizer_rules', [
            'type' => 'array',
            'sanitize_callback' => function ($value) {
                return is_array($value) ? $value : [];
            }
        ]);
        register_setting('buttonizer', 'buttonizer_schedules', [
            'type' => 'array',
            'sanitize_callback' => function ($value) {
                return is_array($value) ? $value : [];
            }
        ]);
        register_setting('buttonizer', 'buttonizer_has_changes', [
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);

        // Revert data
        update_option('buttonizer_buttons', get_option('buttonizer_buttons_published'));
        update_option('buttonizer_rules', get_option('buttonizer_rules_published'));
        update_option('buttonizer_schedules', get_option('buttonizer_schedules_published'));
        update_option('buttonizer_has_changes', false);

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