<?php

namespace Yalogica\NinjaDraw\Rest\Controllers;

defined("ABSPATH") || exit;

use Yalogica\NinjaDraw\Models\AccessModel;
use Yalogica\NinjaDraw\Models\SettingsModel;

class SettingsController
{
  public function registerRestRoutes()
  {
    register_rest_route(
      NINJADRAW_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(
      NINJADRAW_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);
  }
}
