<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class OPA_Uninstall_Feedback {

    public function __construct() {
        add_action('admin_footer', array($this, 'orderpickingapp_deactivate_scripts'));
        add_action('wp_ajax_orderpickingapp_submit_uninstall_reason', array($this, "orderpickingapp_send_uninstall_reason"));
    }

    public function orderpickingapp_deactivate_scripts() {

        global $pagenow;
        if ( 'plugins.php' !== $pagenow ){
            return;
        }
        $reasons = $this->orderpickingapp_get_uninstall_reasons();
        ?>
        <div class="orderpickingapp-modal" id="orderpickingapp-orderpickingapp-modal">
            <div class="orderpickingapp-modal-wrap">
                <div class="orderpickingapp-modal-header">
                    <h3><?php esc_html_e( 'If you have a moment, please let us know why you are deactivating:', 'order-picking-app' ); ?></h3>
                </div>
                <div class="orderpickingapp-modal-body">
                    <ul class="reasons">
                        <?php foreach ( $reasons as $reason ) : ?>
                            <li data-type="<?php echo esc_attr($reason['type']); ?>" data-placeholder="<?php echo esc_attr($reason['placeholder']); ?>">
                                <label>
                                    <input
                                            type="radio"
                                            name="selected-reason"
                                            value="<?php echo esc_attr( $reason['id'] ); ?>"
                                    >
                                    <?php echo esc_html( $reason['text'] ); ?>
                                </label>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <div class="orderpickingapp-modal-footer">
                    <a class="button-primary" href="<?php echo esc_url( 'https://orderpickingapp.com' ); ?>" target="_blank">
                        <span class="dashicons dashicons-external" style="margin-top:3px;"></span>
                        <?php esc_html_e( 'Get support', 'order-picking-app' ); ?>
                    </a>
                    <button class="button-primary orderpickingapp-model-submit">
                        <?php esc_html_e( 'Submit & Deactivate', 'order-picking-app' ); ?>
                    </button>

                    <button class="button-secondary orderpickingapp-model-cancel">
                        <?php esc_html_e( 'Cancel', 'order-picking-app' ); ?>
                    </button>
                </div>
            </div>
        </div>

        <style type="text/css">
            .orderpickingapp-modal {
                position: fixed;
                z-index: 99999;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
                background: rgba(0,0,0,0.5);
                display: none;
            }
            .orderpickingapp-modal.modal-active {display: block;}
            .orderpickingapp-modal-wrap {
                width: 50%;
                position: relative;
                margin: 10% auto;
                background: #fff;
            }
            .orderpickingapp-modal-header {
                border-bottom: 1px solid #eee;
                padding: 8px 20px;
            }
            .orderpickingapp-modal-header h3 {
                line-height: 150%;
                margin: 0;
            }
            .orderpickingapp-modal-body {padding: 5px 20px 20px 20px;}
            .orderpickingapp-modal-body .input-text,.orderpickingapp-modal-body textarea {width:75%;}
            .orderpickingapp-modal-body .reason-input {
                margin-top: 5px;
                margin-left: 20px;
            }
            .orderpickingapp-modal-footer {
                border-top: 1px solid #eee;
                padding: 12px 20px;
                text-align: right;
            }
            .reviewlink, .supportlink{
                padding:10px 0px 0px 35px !important;
                font-size: 14px;
            }
            .review-and-deactivate{
                padding:5px;
            }
            .wt-uninstall-feedback-privacy-policy {
                text-align: left;
                font-size: 12px;
                color: #aaa;
                line-height: 14px;
                margin-top: 20px;
                font-style: italic;
            }

            .wt-uninstall-feedback-privacy-policy a {
                font-size: 11px;
                color: #4b9cc3;
                text-decoration-color: #99c3d7;
            }
        </style>
        <script type="text/javascript">
            (function ($) {
                $(function () {
                    var modal = $('#orderpickingapp-orderpickingapp-modal');
                    var deactivateLink = '';

                    $(document).on('click', '#deactivate-order-picking-app', function (e) {
                        e.preventDefault();
                        modal.addClass('modal-active');
                        deactivateLink = $(this).attr('href');
                        modal.find('a.dont-bother-me').attr('href', deactivateLink).css('float', 'left');
                    });

                    modal.on('click', 'a.review-and-deactivate', function (e) {
                        e.preventDefault();
                        window.open("https://wordpress.org/plugins/order-picking-app/reviews/#new-post");
                        window.location.href = deactivateLink;
                    });
                    modal.on('click', 'a.doc-and-support-doc', function (e) {
                        e.preventDefault();
                        window.open("https://orderpickingapp.com/support/");
                    });
                    modal.on('click', 'a.doc-and-support-forum', function (e) {
                        e.preventDefault();
                        window.open("https://orderpickingapp.com/contact/");
                    });
                    modal.on('click', 'button.orderpickingapp-model-cancel', function (e) {
                        e.preventDefault();
                        modal.removeClass('modal-active');
                    });
                    modal.on('click', 'input[type="radio"]', function () {
                        var parent = $(this).parents('li:first');
                        modal.find('.reason-input').remove();
                        var inputType = parent.data('type'),
                            inputPlaceholder = parent.data('placeholder');
                        var reasonInputHtml = '';
                        if ('reviewhtml' === inputType) {
                            if($('.reviewlink').length == 0){
                                reasonInputHtml = '<div class="reviewlink"><a href="#" target="_blank" class="review-and-deactivate"><?php esc_html_e('Deactivate and leave a review', 'order-picking-app'); ?> <span class="xa-orderpickingapp-rating-link"> &#9733;&#9733;&#9733;&#9733;&#9733; </span></a></div>';
                            }
                        }else if('supportlink' === inputType){
                            if($('.supportlink').length == 0){
                                reasonInputHtml = '<div class="supportlink"><?php esc_html_e('Please go through the', 'order-picking-app'); ?><a href="#" target="_blank" class="doc-and-support-doc"> <?php esc_html_e('documentation', 'order-picking-app'); ?></a> <?php esc_html_e('or contact us via', 'order-picking-app'); ?><a href="#" target="_blank" class="doc-and-support-forum"> <?php esc_html_e('support', 'order-picking-app'); ?></a></div>';
                            }
                        }else {
                            if($('.reviewlink').length){
                                $('.reviewlink'). remove();
                            }
                            if($('.supportlink').length){
                                $('.supportlink'). remove();
                            }
                            reasonInputHtml = '<div class="reason-input">' + (('text' === inputType) ? '<input type="text" class="input-text" size="40" />' : '<textarea rows="5" cols="45"></textarea>') + '</div>';
                        }
                        if (inputType !== '') {
                            parent.append($(reasonInputHtml));
                            parent.find('input, textarea').attr('placeholder', inputPlaceholder).focus();
                        }
                    });

                    modal.on('click', 'button.orderpickingapp-model-submit', function (e) {
                        e.preventDefault();
                        var button = $(this);
                        if (button.hasClass('disabled')) {
                            return;
                        }
                        var $radio = $('input[type="radio"]:checked', modal);
                        var $selected_reason = $radio.parents('li:first'),
                            $input = $selected_reason.find('textarea, input[type="text"]');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'orderpickingapp_submit_uninstall_reason',
                                security: '<?php echo esc_js( wp_create_nonce( 'orderpickingapp_uninstall_nonce' ) ); ?>',
                                reason_id: (0 === $radio.length) ? 'none' : $radio.val(),
                                reason_info: (0 !== $input.length) ? $input.val().trim() : ''
                            },
                            beforeSend: function () {
                                button.addClass('disabled');
                                button.text('<?php echo esc_js( __( 'Processing...', 'order-picking-app' ) ); ?>');
                            },
                            complete: function () {
                                window.location.href = deactivateLink;
                            }
                        });
                    });
                });
            }(jQuery));
        </script>
        <?php
    }

    public function orderpickingapp_send_uninstall_reason() {
        check_ajax_referer( 'orderpickingapp_uninstall_nonce', 'security' );

        if (!isset($_POST['reason_id'])) {
            return;
        }

        $reason_id = isset( $_POST['reason_id'] )
            ? sanitize_text_field( wp_unslash( $_POST['reason_id'] ) )
            : '';

        $reason_info = isset( $_POST['reason_info'] )
            ? sanitize_textarea_field( wp_unslash( $_POST['reason_info'] ) )
            : '';

        $body  = '<table>';
        $body .= '<tr>';
        $body .= '<td><strong>' . esc_html__( 'Site', 'order-picking-app' ) . ':</strong></td>';
        $body .= '<td>' . esc_html( home_url() ) . '</td>';
        $body .= '</tr>';

        $body .= '<tr>';
        $body .= '<td><strong>' . esc_html__( 'Reason', 'order-picking-app' ) . ':</strong></td>';
        $body .= '<td>' . esc_html( $reason_id ) . '</td>';
        $body .= '</tr>';

        $body .= '<tr>';
        $body .= '<td><strong>' . esc_html__( 'Additional information', 'order-picking-app' ) . ':</strong></td>';
        $body .= '<td>' . nl2br( esc_html( $reason_info ) ) . '</td>';
        $body .= '</tr>';
        $body .= '</table>';

        $to = 'support@orderpickingapp.nl';
        $subject = esc_html__( 'WooCommerce deactivation feedback', 'order-picking-app' );
        $headers = array('Content-Type: text/html; charset=UTF-8');
        wp_mail( $to, $subject, $body, $headers );
    }

    private function orderpickingapp_get_uninstall_reasons() {

        $reasons = array(
            array(
                'id' => 'used-it',
                'text' => __('Used it successfully. Don\'t need anymore.', 'order-picking-app'),
                'type' => 'reviewhtml',
                'placeholder' => __('Have used it successfully and aint in need of it anymore', 'order-picking-app')
            ),
            array(
                'id' => 'temporary-deactivation',
                'text' => __('Temporary deactivation', 'order-picking-app'),
                'type' => '',
                'placeholder' => __('Temporary de-activation. Will re-activate later.', 'order-picking-app')
            ),
            array(
                'id' => 'could-not-understand',
                'text' => __('I couldn\'t understand how to make it work', 'order-picking-app'),
                'type' => 'supportlink',
                'placeholder' => __('Would you like us to assist you?', 'order-picking-app')
            ),
            array(
                'id' => 'found-better-plugin',
                'text' => __('I found a better plugin', 'order-picking-app'),
                'type' => 'text',
                'placeholder' => __('Which plugin?', 'order-picking-app')
            ),
            array(
                'id' => 'not-have-that-feature',
                'text' => __('The plugin is great, but I need specific feature that you don\'t support', 'order-picking-app'),
                'type' => 'textarea',
                'placeholder' => __('Could you tell us more about that feature?', 'order-picking-app')
            ),
            array(
                'id' => 'is-not-working',
                'text' => __('The plugin is not working', 'order-picking-app'),
                'type' => 'textarea',
                'placeholder' => __('Could you tell us a bit more whats not working?', 'order-picking-app')
            ),
            array(
                'id' => 'looking-for-other',
                'text' => __('It\'s not what I was looking for', 'order-picking-app'),
                'type' => 'textarea',
                'placeholder' => __('Could you tell us a bit more?', 'order-picking-app')
            ),
            array(
                'id' => 'did-not-work-as-expected',
                'text' => __('The plugin didn\'t work as expected', 'order-picking-app'),
                'type' => 'textarea',
                'placeholder' => __('What did you expect?', 'order-picking-app')
            ),
            array(
                'id' => 'other',
                'text' => __('Other', 'order-picking-app'),
                'type' => 'textarea',
                'placeholder' => __('Could you tell us a bit more?', 'order-picking-app')
            ),
        );

        return $reasons;
    }

}