<?php
/**
 * Better Badge – Plugin Data Consent System (Single File)
 * Text Domain: custom-product-badge-for-woocommerce
 */

add_action('admin_notices', function () {

    if ( ! current_user_can('manage_options') ) return;
    if ( get_option('cpbw_consent_given') !== false ) return;

    // If no dismissal record, show the notice after 3 days of plugin activation
    if ( empty( $dismiss_type ) ) {
        $activation_time = get_option( 'cpbw_install_time' );
        if ( $activation_time && ( time() < ( $activation_time + ( 3 * DAY_IN_SECONDS ) ) ) ) {
            return;
        }
    }

    $nonce = wp_create_nonce('cpbw_consent_nonce');
    $td    = 'custom-product-badge-for-woocommerce';
    ?>
    <style>
        .cpbw-consent-bar {
            background: #f1f5f9;
            border-left: 4px solid #2271b1;
            padding: 14px 16px;
            border-radius: 4px;
            margin-bottom: 15px;
            position: relative;
        }

        .cpbw-dismiss {
            position: absolute;
            top: 8px;
            right: 12px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            color: #50575e;
        }
        .cpbw-dismiss:hover {
            color: #000;
        }

        .cpbw-consent-title {
            font-weight: 600;
            color: #1d2327;
            margin: 0 0 6px 0;
            font-size: 15px;
        }

        .cpbw-consent-msg {
            font-size: 14px;
            color: #3c434a;
            margin: 0 0 6px 0;
        }

        .cpbw-collect-toggle {
            cursor: pointer;
            color: #2271b1;
            font-weight: 500;
            text-decoration: underline;
            user-select: none;
            margin-left: 4px;
        }

        .cpbw-collect-list {
            display: none;
            margin-left: 20px;
            margin-top: 4px;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .cpbw-consent-actions {
            margin-top: 6px;
            display: flex;
            gap: 6px;
        }
    </style>

    <div class="notice notice-info cpbw-consent-bar">
        <!-- Dismiss X button -->
        <span class="cpbw-dismiss" id="cpbw-consent-dismiss">&times;</span>

        <p class="cpbw-consent-title">
            <?php echo esc_html__( '🔒 Better Badge Plugin Data Consent', $td ); ?>
        </p>

        <p class="cpbw-consent-msg">
            <?php echo esc_html__( 'To improve compatibility, provide better support, and ensure that your experience with the Better Badge plugin is seamless across different environments, we need your permission to collect limited site information', $td ); ?>
            <span class="cpbw-collect-toggle" id="cpbw-collect-toggle">
                <?php echo esc_html__( 'What we collect', $td ); ?>
            </span>.
        </p>

        <ul class="cpbw-collect-list" id="cpbw-collect-list">
            <li><?php echo esc_html__( 'Site URL', $td ); ?></li>
            <li><?php echo esc_html__( 'Admin Email', $td ); ?></li>
            <li><?php echo esc_html__( 'WordPress & PHP Version', $td ); ?></li>
            <li><?php echo esc_html__( 'Active Theme (Name & Version)', $td ); ?></li>
            <li><?php echo esc_html__( 'Active Plugins (Name & Version)', $td ); ?></li>
        </ul>

        <div class="cpbw-consent-actions">
            <button class="button button-primary" id="cpbw-consent-accept">
                <?php echo esc_html__( 'Allow', $td ); ?>
            </button>
            <button class="button" id="cpbw-consent-decline">
                <?php echo esc_html__( 'Decline', $td ); ?>
            </button>
        </div>
    </div>

    <script>
        (function ($) {
            const $consentBar = $('.cpbw-consent-bar');
            
            // Toggle bullet list
            $('#cpbw-collect-toggle').on('click', function () {
                $('#cpbw-collect-list').slideToggle(150);
            });

            function fadeThenRequest(action) {
                // 1️⃣ Fade out first
                $consentBar.fadeOut(150);

                // 2️⃣ Then send the request
                $.post(ajaxurl, {
                    action: action,
                    nonce: '<?php echo esc_js($nonce); ?>'
                });
            }

            // Accept consent
            $('#cpbw-consent-accept').on('click', function () {
                fadeThenRequest('cpbw_accept_consent');
            });

            // Decline consent
            $('#cpbw-consent-decline').on('click', function () {
                fadeThenRequest('cpbw_decline_consent');
            });

            // Dismiss notice (treated same as decline)
            $('#cpbw-consent-dismiss').on('click', function () {
                fadeThenRequest('cpbw_decline_consent');
            });

        })(jQuery);
        </script>
    <?php
});

/**
 * Get environment data (cached)
 */
function cpbw_get_environment_data($force_refresh = false) {
    $cache_key = 'cpbw_environment_data';
    if (!$force_refresh) {
        $cached = get_transient($cache_key);
        if ($cached !== false) return $cached;
    }
    if (!function_exists('get_plugin_data')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $plugins = [];
    foreach (get_option('active_plugins', []) as $plugin_path) {
        $plugin_file = WP_PLUGIN_DIR . '/' . $plugin_path;
        if (file_exists($plugin_file)) {
            $plugin_data = get_plugin_data($plugin_file, false, false);
            $plugins[] = [
                'name'    => $plugin_data['Name'],
                'version' => $plugin_data['Version'],
                'author'  => wp_strip_all_tags($plugin_data['Author']),
            ];
        }
    }

    $theme = wp_get_theme();

    $data = [
        'site_url'    => get_site_url(),
        'admin_email' => get_option('admin_email'),
        'wordpress'   => ['version'=>get_bloginfo('version'), 'locale'=>get_locale()],
        'php'         => ['version'=>PHP_VERSION],
        'theme'       => ['name'=>$theme->get('Name'), 'version'=>$theme->get('Version'), 'author'=>wp_strip_all_tags($theme->get('Author'))],
        'plugins'     => $plugins,
    ];

    set_transient($cache_key, $data, DAY_IN_SECONDS);
    return $data;
}

/**
 * Accept consent
 */
add_action('wp_ajax_cpbw_accept_consent', function () {
    check_ajax_referer('cpbw_consent_nonce','nonce');
    update_option('cpbw_consent_given', true);
    $data = cpbw_get_environment_data(true);
    wp_remote_post('https://bb-feedback.vercel.app/api/consents', [
        'headers'   => ['Content-Type'=>'application/json'],
        'body'      => wp_json_encode($data),
        'timeout'   => 15,
    ]);
    wp_die();
});

/**
 * Decline consent
 */
add_action('wp_ajax_cpbw_decline_consent', function () {
    check_ajax_referer('cpbw_consent_nonce','nonce');
    update_option('cpbw_consent_given','declined');
    wp_die();
});
