<?php
namespace SPAATG;
use SPAATG\ShortPixelLogger\ShortPixelLogger as Log;

if ( ! defined( 'ABSPATH' ) ) {
 exit; // Exit if accessed directly.
}
/**
 * User: simon
 * Date: 11.04.2018
 * @todo This whole thing needs redoing.
 */
class ShortPixelFeedback {

    private $ctrl;
    private $plugin_file = '';
    private $plugin_name = '';

    function __construct( $_plugin_file, $slug) {

        $this->plugin_file = $_plugin_file;
        $this->plugin_name = $slug; //for translations

        // Skip the feedback when constant.
        if (defined('SPAATG_SKIP_FEEDBACK') && true == SPAATG_SKIP_FEEDBACK)
        {
           return false;
        }
        // Deactivation
        add_filter( 'plugin_action_links_' . plugin_basename( $this->plugin_file ), array( $this, 'filterActionLinks') );
				add_filter('network_admin_plugin_action_links_' . plugin_basename( $this->plugin_file ), array( $this, 'filterActionLinks'));
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueueAssets' ) );
        add_action( 'admin_footer-plugins.php', array( $this, 'goodbyeAjax') );
        add_action( 'wp_ajax_spaatg_deactivate_plugin', array( $this, 'deactivatePluginCallback') );

    }

    /**
     * Filter the deactivation link to allow us to present a form when the user deactivates the plugin
     * @since 1.0.0
     */
    public function filterActionLinks( $links ) {

        if( isset( $links['deactivate'] ) ) {

            $deactivation_link = $links['deactivate'];
            // Insert an onClick action to allow form before deactivating
            $deactivation_link = str_replace( '<a ',
                '<div class="shortpixel-deactivate-form-wrapper">
                     <span class="shortpixel-deactivate-form" id="shortpixel-deactivate-form-' . esc_attr( $this->plugin_name ) . '"></span>
                 </div><a id="shortpixel-deactivate-link-' . esc_attr( $this->plugin_name ) . '" ', $deactivation_link );
            $links['deactivate'] = $deactivation_link;
        }
        return $links;
    }

    /**
     * Form text strings
     * These can be filtered
     * @since 1.0.0
     */
    public function goodbyeAjax() {
        // Get our strings for the form
        $form = $this->getFormInfo();

      //  $form['body'] = 'bs';

        // Build the HTML to go in the form
        $html = '<div class="shortpixel-deactivate-form-head"><strong>' . esc_html( $form['heading'] ) . '</strong></div>';
        $html .= '<div class="shortpixel-deactivate-form-body">';
        if( is_array( $form['options'] ) ) {
            $html .= '<div class="shortpixel-deactivate-options">';
            $html .= '<p><strong>' . esc_html( $form['body'] ) . '</strong></p><p>';
            foreach( $form['options'] as $key => $option ) {
                $html .= '<input type="radio" name="shortpixel-deactivate-reason" id="' . esc_attr( $key ) . '" value="' . esc_attr( $key ) . '"> <label for="' . esc_attr( $key ) . '">' . esc_attr( $option ) . '</label><br>';
            }
            $html .= '</p><label id="shortpixel-deactivate-details-label" for="shortpixel-deactivate-reasons"><strong>' . esc_html( $form['details'] ) .'</strong></label><textarea name="shortpixel-deactivate-details" id="shortpixel-deactivate-details" rows="2" style="width:100%"></textarea>';
            $html .= '</div><!-- .shortpixel-deactivate-options -->';
        }
        $html .= '<hr/>';
	        $html .= '<span title="' . esc_attr__( 'Un-check this if you don\\\'t plan to use ShortPixel AI Alt Text Generator in the future on this website. You might also want to run a Bulk Delete SP Metadata before removing the plugin (Media Library -> Bulk AI Alt Text).', 'shortpixel-ai-alt-text-generator' )
            . '">'
            . sprintf(
                /* translators: 1: opening settings link, 2: closing settings link. */
                esc_html__(  'If you want to completely uninstall ShortPixel AI Alt Text Generator from your site, please go to %1$s Settings → ShortPixel AI Alt Text Generator → Tools %2$s.', 'shortpixel-ai-alt-text-generator' ),
                '<a href="' . esc_url(admin_url('/options-general.php?page=spaatg-settings&part=tools'))  . '">',
                '</a>'
            ) . '</span><br>';
        $html .= '<hr/>';
        $html .= '</div><!-- .shortpixel-deactivate-form-body -->';
        $html .= '<p class="deactivating-spinner"><span class="spinner"></span> ' . esc_html__( 'Submitting form', 'shortpixel-ai-alt-text-generator' ) . '</p>';
        $html .= '<div class="shortpixel-deactivate-form-footer"><p>';
        $html .= '<label for="anonymous" title="'
            . esc_html__("If you UNCHECK this then your email address and name will be sent along with your feedback. This can be used by ShortPixel to get back to you for more info or a solution.",'shortpixel-ai-alt-text-generator')
            . '"><input type="checkbox" name="shortpixel-deactivate-tracking" checked="checked" id="anonymous" value="1"> ' . esc_html__( 'Send anonymous', 'shortpixel-ai-alt-text-generator' ) . '</label><br>';
	        $html .= '<a id="shortpixel-deactivate-submit-form" class="button button-primary" href="#">'
	            . wp_kses(
		            __( '<span>Submit&nbsp;and&nbsp;</span>Deactivate', 'shortpixel-ai-alt-text-generator' ),
		            array(
			            'span' => array(),
		            )
	            )
	            . '</a>';
        $html .= '</p></div>';
        $config = array(
            'deactivateLinkId' => 'shortpixel-deactivate-link-' . $this->plugin_name,
            'formId' => 'shortpixel-deactivate-form-' . $this->plugin_name,
            'html' => $html,
            'nonce' => sanitize_key( wp_create_nonce( 'spaatg_deactivate_plugin' ) ),
            'detailsStrings' => array(
                'setup' => __( 'What was the dificult part ?', 'shortpixel-ai-alt-text-generator' ),
                'docs' => __( 'What can we describe more ?', 'shortpixel-ai-alt-text-generator' ),
                'features' => __( 'How could we improve ?', 'shortpixel-ai-alt-text-generator' ),
                'better-plugin' => __( 'Can you mention it ?', 'shortpixel-ai-alt-text-generator' ),
                'incompatibility' => __( 'With what plugin or theme is incompatible ?', 'shortpixel-ai-alt-text-generator' ),
                'maintenance' => __( 'Please specify', 'shortpixel-ai-alt-text-generator' ),
                'temporary' => '',
            ),
        );
        wp_add_inline_script( 'spaatg-feedback', 'window.SPAATGDeactivateFeedback = ' . wp_json_encode( $config ) . ';', 'before' );
        ?>
        <div class="shortpixel-deactivate-form-bg"></div>
    <?php }

    public function enqueueAssets( $hook_suffix ) {
        if ( 'plugins.php' !== $hook_suffix ) {
            return;
        }

        wp_register_style( 'spaatg-feedback', plugins_url( 'res/css/shortpixel-feedback.css', SPAATG_PLUGIN_FILE ), array(), SPAATG_IMAGE_OPTIMISER_VERSION );
        wp_register_script( 'spaatg-feedback', plugins_url( 'res/js/shortpixel-feedback.js', SPAATG_PLUGIN_FILE ), array( 'jquery' ), SPAATG_IMAGE_OPTIMISER_VERSION, true );
        wp_enqueue_style( 'spaatg-feedback' );
        wp_enqueue_script( 'spaatg-feedback' );
    }

    /*
     * Form text strings
     * These are non-filterable and used as fallback in case filtered strings aren't set correctly
     * @since 1.0.0
     */
    public function getFormInfo() {
        $form = array();
        $form['heading'] = __( 'Sorry to see you go', 'shortpixel-ai-alt-text-generator' );
        $form['body'] = __( 'Before you deactivate the plugin, would you quickly give us your reason for doing so?', 'shortpixel-ai-alt-text-generator' );
        $form['options'] = array(
						'temporary' 			=> __('Temporary deactivation', 'shortpixel-ai-alt-text-generator'),
            'setup'           => __( 'Set up is too difficult',  'shortpixel-ai-alt-text-generator' ),
            'docs'            => __( 'Lack of documentation',  'shortpixel-ai-alt-text-generator' ),
            'features'        => __( 'Not the features I wanted',  'shortpixel-ai-alt-text-generator' ),
            'better-plugin'   => __( 'Found a better plugin',  'shortpixel-ai-alt-text-generator' ),
            'incompatibility' => __( 'Incompatible with theme or plugin',  'shortpixel-ai-alt-text-generator' ),
            'maintenance'     => __( 'Other',  'shortpixel-ai-alt-text-generator' ),
        );
        $form['details'] = __( 'How could we improve ?',  'shortpixel-ai-alt-text-generator');
        return $form;
    }

    public function deactivatePluginCallback() {

        check_ajax_referer( 'spaatg_deactivate_plugin', 'security' );
        if ( ! current_user_can( 'activate_plugins' ) ) {
            wp_send_json(
                array(
                    'status' => 'forbidden',
                ),
                403
            );
        }

        $log_data = array(
            'has_reason' => isset($_POST['reason']),
            'has_details' => isset($_POST['details']),
            'anonymous' => isset($_POST['anonymous']) ? absint(wp_unslash($_POST['anonymous'])) : null,
        );
				Log::addDebug('Deactive Plugin Callback POST', $log_data);

        if ( isset($_POST['reason']) && isset($_POST['details']) && isset($_POST['anonymous']) ) {
            require_once(\wpSPAATG()->plugin_path() . 'class/view/shortpixel-plugin-request.php');
            $anonymous = (absint(wp_unslash($_POST['anonymous'])) === 1);
            $args = array(
                'reason' => sanitize_text_field(wp_unslash($_POST['reason'])),
                'details' => sanitize_textarea_field(wp_unslash($_POST['details'])),
                'anonymous' => $anonymous
            );
            $request = new ShortPixelPluginRequest( $this->plugin_file, 'https://' . SPAATG_API . '/v2/feedback.php', $args );
            if ( $request->request_successful ) {
                wp_send_json( array(
                    'status' => 'ok',
                ) );
            }else{
                wp_send_json( array(
                    'status' => 'nok',
                ) );
            }
        }else{
            wp_send_json( array(
                'status' => 'OK',
            ) );
        }

    }

}
