<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Emb3D_Model_Viewer
 * @subpackage Emb3D_Model_Viewer/admin
 * @author     Netfarm S.r.l. <info@emb3d.com>
 */
class Emb3D_Model_Viewer_Admin
{
    const EMB3D_MENU_ICON = 'data:image/svg+xml;base64, ';
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string    $plugin_name       The name of this plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct($plugin_name, $version)
    {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->add_actions();
    }

    public function admin_init()
    {
        // [opt] check here if we need to redirect to upgrade to premium page
        if (isset($_GET['page']) && $_GET['page'] == 'emv-upgrade') {
            wp_redirect(Emb3D::PREMIUM_URL . self::get_host());
            exit();
        }

        add_settings_section(
            Emb3D::REGISTRATION_SECTION,
            __('Plugin registration', 'emb3d-model-viewer'),
            '__return_false',
            Emb3D::OPTIONS
        );

        add_settings_field(
            Emb3D::REGISTRATION_KEY,
            __('Serial key', 'emb3d-model-viewer'),
            '__return_false',
            Emb3D::OPTIONS,
            Emb3D::REGISTRATION_SECTION
        );

        register_setting(Emb3D::REGISTRATION_SECTION, Emb3D::REGISTRATION_KEY);
    }

    public function meta_box_output($post)
    {
        include_once(plugin_dir_path(__FILE__) . 'partials/emb3d-model-viewer-meta-box-output.php');
    }

    public function add_meta_boxes()
    {
        add_meta_box(
            Emb3D::META_BOX_ID,
            Emb3D::PLUGIN_TITLE,
            [$this, 'meta_box_output'],
            'product',
            'side',
            'low'
        );
    }

    public function save_meta_boxes($post_id, $post)
    {
        if (empty($post_id) || empty($post)) {
            return;
        }

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

        if (wp_is_post_revision($post) || wp_is_post_autosave($post)) {
            return;
        }

        // not my own
        if (!isset($_REQUEST[Emb3D::META_BOX_NONCE])) {
            return;
        }

        if (!wp_verify_nonce($_REQUEST[Emb3D::META_BOX_NONCE], Emb3D::META_BOX_NONCE)) {
            exit('Invalid nonce');
        }

        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        if (empty($_REQUEST[Emb3D::META_BOX_MODEL_ID])) {
            delete_post_meta($post_id, Emb3D::META_BOX_MODEL_ID);
            delete_post_meta($post_id, Emb3D::META_BOX_MODEL_FILENAME);
            delete_post_meta($post_id, Emb3D::META_BOX_MODEL_REPLACE_PRODUCT_IMAGE);
            delete_post_meta($post_id, Emb3D::META_BOX_MODEL_BACKGROUND_COLOR);
            delete_post_meta($post_id, Emb3D::META_BOX_MODEL_PROGRESS_COLOR);
        } else {
            update_post_meta($post_id, Emb3D::META_BOX_MODEL_ID, sanitize_text_field($_REQUEST[Emb3D::META_BOX_MODEL_ID]));

            if (!empty($_REQUEST[Emb3D::META_BOX_MODEL_FILENAME])) {
                update_post_meta($post_id, Emb3D::META_BOX_MODEL_FILENAME, sanitize_text_field($_REQUEST[Emb3D::META_BOX_MODEL_FILENAME]));
            }

            if (!empty($_REQUEST[Emb3D::META_BOX_MODEL_BACKGROUND_COLOR])) {
                update_post_meta($post_id, Emb3D::META_BOX_MODEL_BACKGROUND_COLOR, sanitize_text_field($_REQUEST[Emb3D::META_BOX_MODEL_BACKGROUND_COLOR]));
            }

            if (!empty($_REQUEST[Emb3D::META_BOX_MODEL_PROGRESS_COLOR])) {
                update_post_meta($post_id, Emb3D::META_BOX_MODEL_PROGRESS_COLOR, sanitize_text_field($_REQUEST[Emb3D::META_BOX_MODEL_PROGRESS_COLOR]));
            }

            $replace_product_image = intval($_REQUEST[Emb3D::META_BOX_MODEL_REPLACE_PRODUCT_IMAGE] == 'on');
            update_post_meta($post_id, Emb3D::META_BOX_MODEL_REPLACE_PRODUCT_IMAGE, $replace_product_image);
        }
    }

    public function add_actions()
    {
        add_action('admin_init', [$this, 'admin_init']);
        add_action('wp_ajax_emv_register_plugin', [$this, 'emv_register_plugin']);
        add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
        add_action('save_post', [$this, 'save_meta_boxes'], 10, 2);
    }

    public function emv_register_plugin()
    {
        if (!wp_verify_nonce($_REQUEST['nonce'], Emb3D::REGISTRATION_NONCE)) {
            exit('Invalid nonce');
        }

        if (empty($_REQUEST[Emb3D::REGISTRATION_KEY])) {
            delete_option(Emb3D::REGISTRATION_KEY);
        } else {
            update_option(Emb3D::REGISTRATION_KEY, sanitize_text_field($_REQUEST[Emb3D::REGISTRATION_KEY]));
        }
    }

    public function admin_menu()
    {
        add_menu_page(
            Emb3D::PLUGIN_SHORT_TITLE,
            Emb3D::PLUGIN_SHORT_TITLE,
            'administrator',
            $this->plugin_name,
            null,
            self::EMB3D_MENU_ICON,
            26
        );

        add_submenu_page(
            $this->plugin_name,
            __('Overview', 'emb3d-model-viewer'),
            __('Overview', 'emb3d-model-viewer'),
            'administrator',
            $this->plugin_name,
            [$this, 'display_overview']
        );

        if (!get_option(Emb3D::REGISTRATION_KEY)) {
            add_submenu_page(
                $this->plugin_name,
                __('Upgrade', 'emb3d-model-viewer'),
                '<div style="white-space: nowrap;">' . esc_html__('Upgrade to Premium', 'emb3d-model-viewer') . ' <span class="dashicons dashicons-star-filled" style="font-size: 15px;"></div>',
                'administrator',
                'emv-upgrade',
                '__return_false'
            );
        }
    }

    public function display_overview()
    {
        include_once(plugin_dir_path(__FILE__) . 'partials/emb3d-model-viewer-overview.php');
    }

    static function get_host()
    {
        return parse_url(get_site_url())['host'];
    }

    static function lord_icon($name)
    {
        return plugin_dir_url(__FILE__) . 'icons/' . $name . '.json';
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles()
    {
        wp_enqueue_style(
            Emb3D::STYLE_ADMIN,
            plugin_dir_url(__FILE__) . 'css/emb3d-model-viewer-admin.css',
            [],
            $this->version,
            'all'
        );
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts()
    {
        wp_enqueue_media();

        $suffix = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? '' : '.min';

        wp_enqueue_script(
            Emb3D::SCRIPT_ADMIN,
            plugin_dir_url(__FILE__) . 'js/emb3d-model-viewer-admin' . $suffix . '.js',
            ['jquery'],
            $this->version,
            false
        );

        wp_localize_script(
            Emb3D::SCRIPT_ADMIN,
            'frontendajax',
            array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce(Emb3D::REGISTRATION_NONCE)
            )
        );

        // [opt] load lord icon script only on the overview page
        if (isset($_GET['page']) && $_GET['page'] == $this->plugin_name) {
            wp_enqueue_script(
                Emb3D::SCRIPT_LORD_ICON,
                plugin_dir_url(__FILE__) . 'js/lord-icon.js',
                [],
                Emb3D::SCRIPT_LORD_ICON_VERSION
            );
        }

        $screen = get_current_screen();
        $screen_id = $screen ? $screen->id : '';

        // [opt] Only in product screen
        if ($screen_id === 'product') {
            wp_enqueue_style('wp-color-picker');
            wp_enqueue_script(
                Emb3D::SCRIPT_WP_COLOR_PICKER_ALPHA,
                plugin_dir_url(__FILE__) . 'js/wp-color-picker-alpha' . $suffix . '.js',
                ['wp-color-picker'],
                Emb3D::SCRIPT_WP_COLOR_PICKER_ALPHA_VERSION,
                true
            );
            wp_add_inline_script(
                Emb3D::SCRIPT_WP_COLOR_PICKER_ALPHA,
                'jQuery(function() { jQuery(".color-picker").wpColorPicker(); });'
            );
        }
    }
}
