<?php
namespace Wpupgrader\WordPress\Plugins\GdprConsentLite\Hooks\Actions;

use Wpupgrader\Libraries\WordPress\Plugins\Core\Hooks\AbstractAction;

class save_post extends AbstractAction
{
    /**
     * This method is invoked by Wordpress
     *
     * @param int $post_id
     * @param \WP_Post $post
     */
    static public function invoke($post_id, $post)
    {
        static::saveDisallowedPluginsMetaBox($post_id, $post);
    }

    /**
     * @param int $post_id
     * @param \WP_Post $post
     */
    static protected function saveDisallowedPluginsMetaBox($post_id, $post)
    {
        // Add nonce for security and authentication.
        $nonce_name = isset($_POST['gdprc_disallowed_plugins_nonce']) ? \sanitize_text_field($_POST['gdprc_disallowed_plugins_nonce']) : '';
        $nonce_action = 'gdprc_disallowed_plugins_nonce_action';

        // Check if nonce is set.
        if (!isset($nonce_name)) {
            return;
        }

        // Check if nonce is valid.
        if (!\wp_verify_nonce($nonce_name, $nonce_action)) {
            return;
        }

        // Check if user has permissions to save data.
        if (!\current_user_can('edit_post', $post_id)) {
            return $post_id;
        }

        // Check if not an autosave.
        if (\wp_is_post_autosave($post_id)) {
            return;
        }

        // Check if not a revision.
        if (\wp_is_post_revision($post_id)) {
            return;
        }

        // Set mandatory status
        if (isset($_POST['gdprc_consent_is_required'])) {
            \update_post_meta($post_id, 'gdprc_consent_is_required', 1);
        }
        else {
            \delete_post_meta($post_id, 'gdprc_consent_is_required');
        }

        // Set sorting order
        if (isset($_POST['gdprc_consent_sortorder'])) {
            \update_post_meta($post_id, 'gdprc_consent_sortorder', \sanitize_key($_POST['gdprc_consent_sortorder']));
        }

        // Set disallowed plugins
        if (isset($_POST['gdprc_disallowed_plugins'])) {
            \update_post_meta($post_id, 'gdprc_disallowed_plugins', \array_map('sanitize_text_field', $_POST['gdprc_disallowed_plugins']));
        }
        else {
            \delete_post_meta($post_id, 'gdprc_disallowed_plugins');
        }

        // Set allowed scripts
        if (\gdprConsentPluginIsProEdition()) {
            if (isset($_POST['gdprc_allowed_scripts'])) {
                \update_post_meta($post_id, 'gdprc_allowed_scripts', \array_map('sanitize_text_field', $_POST['gdprc_allowed_scripts']));
            }
            else {
                \delete_post_meta($post_id, 'gdprc_allowed_scripts');
            }
        }

        // Set icon
        if (isset($_POST['gdprc_selected_icon'])) {
            \update_post_meta($post_id, 'gdprc_selected_icon', \sanitize_key($_POST['gdprc_selected_icon']));
        }
        else {
            \delete_post_meta($post_id, 'gdprc_selected_icon');
        }
    }
}
