<?php

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

/**
 * Add custom class to Deactivate link
 */
add_filter( 'plugin_action_links_custom-product-badge-for-woocommerce/custom-product-badge-for-woocommerce.php', function( $actions ) {
    if ( isset( $actions['deactivate'] ) ) {
        $actions['deactivate'] = str_replace(
            '<a ',
            '<a class="cpbw-deactivate-link" ',
            $actions['deactivate']
        );
    }
    return $actions;
});

/**
 * Add Deactivation Feedback Modal
 */
add_action( 'admin_footer', function() {

    // Create nonce
    $nonce = wp_create_nonce( 'cpbw_deactivate_nonce' );
    ?>
    <style>
        #cpbw-deactivate-modal {display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.55);z-index:10000;}
        #cpbw-deactivate-modal .cpbw-modal-content {background:#fff;border-radius:8px;box-shadow:0 5px 30px rgba(0,0,0,0.25);padding:25px;max-width:480px;margin:8% auto;font-family:"Open Sans",sans-serif;animation:fadeInDown .3s ease;}
        #cpbw-deactivate-modal h2 {font-size:20px;margin:0 0 10px;color:#23282d;}
        #cpbw-deactivate-modal p {margin:0 0 15px;font-size:14px;color:#555;}
        #cpbw-deactivate-modal label {display:block;margin-bottom:8px;font-size:14px;}
        #cpbw-deactivate-modal textarea {width:100%;height:80px;border-radius:4px;border:1px solid #ccd0d4;padding:8px;font-size:13px;resize:vertical;}
        #cpbw-deactivate-modal .cpbw-actions {margin-top:15px;text-align:right;}
        @keyframes fadeInDown {from{opacity:0;transform:translateY(-20px);}to{opacity:1;transform:translateY(0);}}
    </style>

    <div id="cpbw-deactivate-modal">
        <div class="cpbw-modal-content">
            <h2><?php esc_html_e( 'We value your feedback 💬', 'custom-product-badge-for-woocommerce' ); ?></h2>
            <p><?php esc_html_e( 'Could you tell us why you’re deactivating?', 'custom-product-badge-for-woocommerce' ); ?></p>

            <form id="cpbw-deactivate-form">
                
                <!-- NONCE FIELD -->
                <input type="hidden" name="cpbw_nonce" value="<?php echo esc_attr( $nonce ); ?>">

                <label><input type="radio" name="reason" value="not_working"> <?php esc_html_e( 'The plugin is not working', 'custom-product-badge-for-woocommerce' ); ?></label>
                <label><input type="radio" name="reason" value="missing_feature"> <?php esc_html_e( 'It’s missing a feature I need', 'custom-product-badge-for-woocommerce' ); ?></label>
                <label><input type="radio" name="reason" value="temporary"> <?php esc_html_e( 'I’m just deactivating temporarily', 'custom-product-badge-for-woocommerce' ); ?></label>
                <label><input type="radio" name="reason" value="other"> <?php esc_html_e( 'Other (please specify)', 'custom-product-badge-for-woocommerce' ); ?></label>
                <textarea name="details" placeholder="<?php esc_attr_e( 'Your feedback...', 'custom-product-badge-for-woocommerce' ); ?>"></textarea>

                <div class="cpbw-actions">
                    <button type="submit" class="button button-primary"><?php esc_html_e( 'Submit & Deactivate', 'custom-product-badge-for-woocommerce' ); ?></button>
                    <button type="button" class="button button-secondary cpbw-skip"><?php esc_html_e( 'Skip & Deactivate', 'custom-product-badge-for-woocommerce' ); ?></button>
                    <button type="button" class="button cpbw-cancel"><?php esc_html_e( 'Cancel', 'custom-product-badge-for-woocommerce' ); ?></button>
                </div>
            </form>
        </div>
    </div>

    <script>
    (function($){
        $(document).on('click', '.cpbw-deactivate-link', function(e){
            e.preventDefault();
            var deactivateUrl = $(this).attr('href');
            $('#cpbw-deactivate-modal').fadeIn(200);

            // Handle submit
            $('#cpbw-deactivate-form').off('submit').on('submit', function(e){
                e.preventDefault();
                var data = $(this).serialize();

                $.post(ajaxurl, {
                    action: 'cpbw_save_deactivation_reason',
                    data: data
                }, function(){
                    window.location.href = deactivateUrl;
                });
            });

            // Skip button = deactivate without feedback
            $('.cpbw-skip').off('click').on('click', function(){
                window.location.href = deactivateUrl;
            });

            // Cancel button = close modal
            $('.cpbw-cancel').off('click').on('click', function(){
                $('#cpbw-deactivate-modal').fadeOut(200);
            });
        });
    })(jQuery);
    </script>
    <?php
});

/**
 * Handle AJAX to send feedback to API
 */
add_action( 'wp_ajax_cpbw_save_deactivation_reason', function() {

    if ( ! current_user_can( 'activate_plugins' ) ) {
        wp_send_json_error( ['message' => 'Permission denied'] );
    }

    // Parse data
    $data = [];
    if ( isset( $_POST['data'] ) ) {
        parse_str( $_POST['data'], $data );
    }

    // Verify nonce
    if ( ! isset( $data['cpbw_nonce'] ) || 
         ! wp_verify_nonce( $data['cpbw_nonce'], 'cpbw_deactivate_nonce' ) ) {

        wp_send_json_error( ['message' => 'Invalid nonce'] );
    }

    $reason   = sanitize_text_field( $data['reason'] ?? '' );
    $details  = sanitize_textarea_field( $data['details'] ?? '' );
    $site_url = esc_url( home_url() );
    $plugin   = 'custom-product-badge-for-woocommerce';

    $payload = [
        'reason'   => $reason,
        'details'  => $details,
        'site_url' => $site_url,
        'plugin'   => $plugin,
    ];

    // Send to your API
    $response = wp_remote_post( 'https://bb-feedback.vercel.app/api/feedbacks', [
        'timeout' => 15,
        'headers' => [ 'Content-Type' => 'application/json' ],
        'body'    => wp_json_encode( $payload ),
    ]);

    wp_send_json_success();
});
