<?php
namespace Avirtum\GutenDraw\Rest\Controllers;

defined( 'ABSPATH' ) || exit;

use Avirtum\GutenDraw\Models\AccessModel;
use Avirtum\GutenDraw\Models\SettingsModel;

class SettingsController {
    public function registerRestRoutes() {
        register_rest_route(
            GUTENDRAW_PLUGIN_REST_URL,
            '/settings',
            [
                [
                    'methods' => \WP_REST_Server::READABLE,
                    'callback' => [ $this, 'getSettings' ],
                    'permission_callback' => [ $this, 'canManageOptions' ]
                ],
                [
                    'methods' => \WP_REST_Server::EDITABLE,
                    'callback' => [ $this, 'setSettings' ],
                    'permission_callback' => [ $this, 'canManageOptions' ],
                ]
            ]
        );

        register_rest_route(
            GUTENDRAW_PLUGIN_REST_URL,
            '/permission-types',
            [
                [
                    'methods' => \WP_REST_Server::READABLE,
                    'callback' => [ $this, 'getPermissionTypes' ],
                    'permission_callback' => [ $this, 'canManageOptions' ]
                ]
            ]
        );
    }

    public function canManageOptions() {
        return current_user_can( 'manage_options' );
    }

    public function getSettings( \WP_REST_Request $request ) {
        $response = [
            'success' => true,
            'data' => SettingsModel::get()
        ];

        return new \WP_REST_Response( $response );
    }

    public function setSettings( \WP_REST_Request $request ) {
        $response = [
            'success' => SettingsModel::set( $request->get_json_params() )
        ];

        return new \WP_REST_Response( $response );
    }

    public function getPermissionTypes( \WP_REST_Request $request ) {
        $response = [
            'success' => true,
            'data' => AccessModel::getPermissionTypes()
        ];

        return new \WP_REST_Response( $response );
    }
}