<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Coming_Soon
{
    private static $instance = null;

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }

return self::$instance;
    }

    public function __construct()
    {
        add_action('template_redirect', array($this, 'intercept'), 0);
        add_action('rest_api_init', array($this, 'register_rest_routes'));
    }

    public function get_status()
    {
        return array('enabled' => (bool) get_option('puffergo_coming_soon', false), 'brandName' => sanitize_text_field(get_option('puffergo_coming_soon_brand', '')), 'description' => sanitize_text_field(get_option('puffergo_coming_soon_description', '')), 'label' => sanitize_text_field(get_option('puffergo_coming_soon_label', '')), );
    }

    public function register_rest_routes()
    {
        register_rest_route('puffergo/v1', '/coming-soon', array('methods' => 'GET', 'callback' => array($this, 'rest_get_status'), 'permission_callback' => array($this, 'can_manage_options'), ));
        register_rest_route('puffergo/v1', '/coming-soon', array('methods' => 'POST', 'callback' => array($this, 'rest_update'), 'permission_callback' => array($this, 'can_manage_options'), ));
    }

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

    public function rest_get_status()
    {
        return rest_ensure_response(array('success' => true, 'data' => $this->get_status(), ));
    }

    public function rest_update(WP_REST_Request $request)
    {
        $enabled = (bool) $request->get_param('enabled');
        update_option('puffergo_coming_soon', $enabled);

        if ($request->has_param('brandName')) {
            update_option('puffergo_coming_soon_brand', sanitize_text_field($request->get_param('brandName')));
        }

if ($request->has_param('description')) {
            update_option('puffergo_coming_soon_description', sanitize_text_field($request->get_param('description')));
        }

if ($request->has_param('label')) {
            update_option('puffergo_coming_soon_label', sanitize_text_field($request->get_param('label')));
        }

return rest_ensure_response(array('success' => true, 'data' => $this->get_status(), ));
    }

    public function intercept()
    {
        if (is_admin()) {
            return;
        }

if (! get_option('puffergo_coming_soon', false)) {
            return;
        }

if (current_user_can('manage_options')) {
            return;
        }

if (defined('REST_REQUEST') && REST_REQUEST) {
            return;
        }

if (wp_doing_ajax()) {
            return;
        } $this->render_coming_soon_page();
        exit;
    }

    private function render_coming_soon_page()
    {
        $template = PUFFERGO_PLUGIN_DIR . '/templates/coming-soon.php';

        if (file_exists($template)) {
            include $template;
        }
    }
}
