<?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\Settings;

use Buttonizer\Utils\PermissionCheck;

/**
 * Settings API
 *
 * @endpoint /wp-json/buttonizer/settings
 * @methods GET POST
 */
class ApiSettings
{
    /**
     * Register route
     */
    public function registerRoute()
    {
        register_rest_route('buttonizer', '/settings', [
            [
                'methods'  => ['GET'],
                'args' => [
                    'nonce' => [
                        'validate_callback' => function ($value) {
                            return wp_verify_nonce($value, 'wp_rest');
                        },
                        'required' => true
                    ]
                ],
                'callback' => [$this, 'get'],
                'permission_callback' => function () {
                    return PermissionCheck::hasPermission();
                }
            ],
            [
                'methods'  => ['POST'],
                'args' => [
                    'data' => [
                        'required' => true,
                        'type' => "object"
                    ],
                    'nonce' => [
                        'validate_callback' => function ($value) {
                            return wp_verify_nonce($value, 'wp_rest');
                        },
                        'required' => true
                    ],
                ],
                'callback' => [$this, 'post'],
                'permission_callback' => function () {
                    return PermissionCheck::hasPermission();
                }
            ]
        ]);
    }

    /**
     * Get settings
     */
    public function get()
    {
        return [
            'data' => get_option('buttonizer_settings')
        ];
    }
    /**
     * Save settings
     */
    public function post($request)
    {
        register_setting('buttonizer', 'buttonizer_settings', [
            'type' => 'array',
            'sanitize_callback' => function ($value) {
                return is_array($value) ? $value : [];
            }
        ]);
        register_setting('buttonizer', 'buttonizer_has_changes', [
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);

        update_option('buttonizer_settings', array_merge(get_option('buttonizer_settings'), $request->get_param('data')));

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