<?php
/*
Plugin Name: Zap Reviews Widget for Elementor
Description: פלאגין מותאם להצגת ביקורות וציון מזאפ כווידג'ט באלמנטור.
Version: 1.0.0
Author:Ido Navarro
Requires at least:5.0
Author URI: https://idonavarro.com
License:GPL-2.0+
License URI:http://www.gnu.org/licenses/gpl-2.0.txt
WC tested up to: 6.7.1
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

/**
 * Check if Elementor is installed and activated
 */
function zap_reviews_check_elementor() {
    if (!did_action('elementor/loaded')) {
        add_action('admin_notices', 'zap_reviews_elementor_missing_notice');
        return false;
    }
    return true;
}

/**
 * Display admin notice if Elementor is not installed
 */
function zap_reviews_elementor_missing_notice() {
    $message = sprintf(
        __('"%1$s" requires "%2$s" to be installed and activated. %3$s', 'zap-reviews-for-elementor'),
        '<strong>' . __('Zap Reviews Widget', 'zap-reviews-for-elementor') . '</strong>',
        '<strong>' . __('Elementor', 'zap-reviews-for-elementor') . '</strong>',
        '<a href="' . esc_url(admin_url('plugin-install.php?s=Elementor&tab=search&type=term')) . '">' . __('Please install Elementor', 'zap-reviews-for-elementor') . '</a>'
    );
    printf('<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message);
}

/**
 * Register Widget
 */
function register_zap_reviews_widget() {
    require_once plugin_dir_path(__FILE__) . 'zap-reviews-widget-class.php';
    \Elementor\Plugin::instance()->widgets_manager->register_widget_type(new Zap_Reviews_Widget());
}

/**
 * Initialize plugin
 */
function zap_reviews_init() {
    if (zap_reviews_check_elementor()) {
        // Register the widget
        add_action('elementor/widgets/widgets_registered', 'register_zap_reviews_widget');
        
        // Enqueue Zap's JavaScript files
        add_action('wp_enqueue_scripts', function() {
            wp_enqueue_script('zap-reviews', 'https://zap.dbusiness.co/js/zap-reviews.js', [], null, true);
            wp_enqueue_script('zap-score', 'https://zap.dbusiness.co/js/zap-score.js', [], null, true);
        });
    }
}

// Register activation hook
register_activation_hook(__FILE__, function() {
    if (!did_action('elementor/loaded')) {
        deactivate_plugins(plugin_basename(__FILE__));
        wp_die(
            __('Zap Reviews Widget requires Elementor to be installed and activated.', 'zap-reviews-for-elementor'),
            'Plugin dependency check',
            ['back_link' => true]
        );
    }
});

// Initialize plugin
add_action('plugins_loaded', 'zap_reviews_init');

/**
 * Add deactivation feedback form
 */
function zap_reviews_add_deactivation_feedback_form() {
    // Only load if we're on plugins.php
    $screen = get_current_screen();
    if ($screen->id !== 'plugins') {
        return;
    }

    // Add the feedback form HTML and JavaScript
    ?>
    <div id="zap-reviews-deactivate-feedback" style="display: none;">
        <div class="zap-reviews-feedback-overlay"></div>
        <div class="zap-reviews-feedback-form">
            <h2><?php _e('Quick Feedback', 'zap-reviews-for-elementor'); ?></h2>
            <p><?php _e('If you have a moment, please share why you are deactivating Zap Reviews:', 'zap-reviews-for-elementor'); ?></p>
            <form method="post">
                <div class="feedback-options">
                    <label>
                        <input type="radio" name="zap_reviews_feedback" value="no-longer-needed">
                        <?php _e('I no longer need the plugin', 'zap-reviews-for-elementor'); ?>
                    </label>
                    <label>
                        <input type="radio" name="zap_reviews_feedback" value="better-plugin">
                        <?php _e('I found a better plugin', 'zap-reviews-for-elementor'); ?>
                    </label>
                    <label>
                        <input type="radio" name="zap_reviews_feedback" value="not-working">
                        <?php _e('I couldn\'t get the plugin to work', 'zap-reviews-for-elementor'); ?>
                    </label>
                    <label>
                        <input type="radio" name="zap_reviews_feedback" value="temporary">
                        <?php _e('It\'s a temporary deactivation', 'zap-reviews-for-elementor'); ?>
                    </label>
                    <label>
                        <input type="radio" name="zap_reviews_feedback" value="elementor-pro">
                        <?php _e('I have Elementor Pro', 'zap-reviews-for-elementor'); ?>
                    </label>
                    <label>
                        <input type="radio" name="zap_reviews_feedback" value="other">
                        <?php _e('Other', 'zap-reviews-for-elementor'); ?>
                    </label>
                </div>
                <div class="feedback-buttons">
                    <button type="submit" class="button button-primary"><?php _e('Submit & Deactivate', 'zap-reviews-for-elementor'); ?></button>
                    <a href="#" class="skip"><?php _e('Skip & Deactivate', 'zap-reviews-for-elementor'); ?></a>
                </div>
            </form>
        </div>
    </div>

    <style>
        .zap-reviews-feedback-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 999999;
        }
        .zap-reviews-feedback-form {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #fff;
            padding: 30px;
            max-width: 500px;
            width: 100%;
            border-radius: 5px;
            z-index: 1000000;
        }
        .feedback-options label {
            display: block;
            margin: 10px 0;
        }
        .feedback-buttons {
            margin-top: 20px;
            text-align: right;
        }
        .feedback-buttons .skip {
            margin-left: 10px;
            color: #a0a5aa;
            text-decoration: none;
        }
    </style>

    <script>
    jQuery(document).ready(function($) {
        var deactivateLink = $('tr[data-plugin="zap-reviews-widget/zap-reviews-widget.php"] .deactivate a');
        
        deactivateLink.on('click', function(e) {
            e.preventDefault();
            $('#zap-reviews-deactivate-feedback').show();
        });

        // Handle form submission
        $('#zap-reviews-deactivate-feedback form').on('submit', function(e) {
            e.preventDefault();
            var feedback = $('input[name="zap_reviews_feedback"]:checked').val();
            
            // Send feedback via AJAX
            $.post(ajaxurl, {
                action: 'zap_reviews_deactivation_feedback',
                feedback: feedback,
                nonce: '<?php echo wp_create_nonce("zap_reviews_feedback"); ?>'
            }, function() {
                // Proceed with deactivation
                window.location.href = deactivateLink.attr('href');
            });
        });

        // Handle skip button
        $('.feedback-buttons .skip').on('click', function(e) {
            e.preventDefault();
            window.location.href = deactivateLink.attr('href');
        });
    });
    </script>
    <?php
}
add_action('admin_footer', 'zap_reviews_add_deactivation_feedback_form');

/**
 * Handle the AJAX feedback submission
 */
function zap_reviews_handle_feedback() {
    check_ajax_referer('zap_reviews_feedback', 'nonce');

    $feedback = isset($_POST['feedback']) ? sanitize_text_field($_POST['feedback']) : '';
    
    if ($feedback) {
        $to = 'navarro.ido@gmail.com';
        $subject = 'Zap Reviews Widget Deactivation Feedback';
        $body = "Deactivation reason: " . $feedback;
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        wp_mail($to, $subject, $body, $headers);
    }

    wp_die();
}
add_action('wp_ajax_zap_reviews_deactivation_feedback', 'zap_reviews_handle_feedback');
