<?php
/**
 * Prohibit direct script loading
 */
defined('ABSPATH') || die('No direct script access allowed!');

/**
 * Class WpmsGscAjax
 */
class WpmsGscAjax
{
    /**
     * Check if posted nonce is valid and return true if it is
     *
     * @return mixed
     */
    public static function validNonce()
    {
        $ajax_nonce   = filter_input(INPUT_POST, 'ajax_nonce');
        $verify_nonce = wp_verify_nonce($ajax_nonce, 'wpms-gsc-ajax-security');
        return $verify_nonce;
    }

    /**
     * This method will be access by an AJAX request and will mark an issue as fixed.
     * First it will do a request to the Google API
     *
     * @return void
     */
    public static function ajaxMarkAsFixed()
    {
        $valid_nonce = self::validNonce();
        if ($valid_nonce) {
            $url     = filter_input(INPUT_POST, 'url');
            $marker  = new WpmsGscMarker($url);
            $results = $marker->getResponse();
            wp_send_json($results);
        }
        wp_send_json('false');
    }

    /**
     * Handling the request to create a new redirect from the issued URL
     *
     * @return void
     */
    public static function ajaxCreateRedirect()
    {
        $valid_nonce = self::validNonce();
        if ($valid_nonce && class_exists('WpmsRedirectManager')) {
            $redirect_manager = new WpmsRedirectManager();
            $old_url          = filter_input(INPUT_POST, 'old_url');
            $new_url          = filter_input(INPUT_POST, 'new_url');
            $type             = filter_input(INPUT_POST, 'type');
            // Create redirect
            $redirect = new WpmsRedirect($old_url, $new_url, $type);

            if ($redirect_manager->createRedirect($redirect)) {
                $mark_as_fixed = filter_input(INPUT_POST, 'mark_as_fixed');
                if ($mark_as_fixed === 'true') {
                    new WpmsGscMarker($old_url);
                }
                wp_send_json('true');
            }
        }
        wp_send_json('false');
    }
}
