<?php
/**
 * Conflict Detector — Plugin conflict detection & GDPR consent integration.
 *
 * Detects: third-party FB pixel plugins, duplicate CAPI plugins.
 * Integrates: CookieYes, Complianz, CookieBot, GDPR Cookie Consent.
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core;

defined( 'ABSPATH' ) || exit;

class Conflict_Detector {

    /**
     * Known conflicting plugins.
     *
     * @var array
     */
    const CONFLICTING_PLUGINS = array(
        'facebook-for-woocommerce/facebook-for-woocommerce.php'
            => 'Meta for WooCommerce (Facebook for WooCommerce)',
        'pixelyoursite/pixelyoursite.php'
            => 'PixelYourSite',
        'pixel-caffeine/pixel-caffeine.php'
            => 'Pixel Caffeine',
        'official-facebook-pixel/facebook-for-wordpress.php'
            => 'Official Facebook Pixel',
        'leadin/leadin.php'
            => 'HubSpot (may inject FB pixel)',
    );

    /**
     * Register hooks.
     */
    public function register_hooks() {
        add_action( 'admin_notices', array( $this, 'check_conflicts' ) );

        // GDPR consent filter integration.
        add_filter( 'capiflow_has_tracking_consent', array( $this, 'check_gdpr_consent' ) );
    }

    /**
     * Check for conflicting plugins and display admin notice.
     */
    public function check_conflicts() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Only check on our settings page and plugins page.
        $screen = get_current_screen();
        if ( ! $screen || ! in_array( $screen->id, array( 'plugins', 'toplevel_page_capiflow-dashboard' ), true ) ) {
            return;
        }

        $active_conflicts = array();

        foreach ( self::CONFLICTING_PLUGINS as $plugin_file => $plugin_name ) {
            if ( is_plugin_active( $plugin_file ) ) {
                $active_conflicts[] = $plugin_name;
            }
        }

        if ( ! empty( $active_conflicts ) ) {
            $plugins_list = '<strong>' . implode( '</strong>, <strong>', $active_conflicts ) . '</strong>';

            echo '<div class="notice notice-warning is-dismissible">';
            echo '<p><strong>⚠️ CapiFlow:</strong> ';
            echo wp_kses_post(
                sprintf(
                    /* translators: %s: List of conflicting plugin names */
                    __( 'Potential conflicts detected with: %s. These plugins may inject duplicate Facebook Pixels causing double-counted events. Please disable their pixel features or deactivate them.', 'capiflow' ),
                    $plugins_list
                )
            );
            echo '</p></div>';
        }
    }

    /**
     * GDPR consent integration.
     *
     * Checks major consent management platforms.
     *
     * @param bool $has_consent Current consent status.
     * @return bool Whether tracking consent is granted.
     */
    public function check_gdpr_consent( $has_consent ) {
        // If consent enforcement is disabled in settings, always allow.
        if ( ! get_option( 'capiflow_consent_enforcement', false ) ) {
            return $has_consent;
        }

        // If already blocked by another filter, respect it.
        if ( ! $has_consent ) {
            return false;
        }

        // CookieYes.
        if ( function_exists( 'cky_consent_given' ) ) {
            return (bool) cky_consent_given( 'analytics' );
        }

        // Complianz.
        if ( function_exists( 'cmplz_has_consent' ) ) {
            return (bool) cmplz_has_consent( 'statistics' );
        }

        // CookieBot.
        if ( isset( $_COOKIE['CookieConsent'] ) ) {
            $consent = sanitize_text_field( wp_unslash( $_COOKIE['CookieConsent'] ) );
            // CookieBot stores consent as JSON-encoded or comma-separated.
            if ( strpos( $consent, 'statistics:true' ) !== false || strpos( $consent, '"statistics":true' ) !== false ) {
                return true;
            }
            if ( strpos( $consent, 'statistics:false' ) !== false || strpos( $consent, '"statistics":false' ) !== false ) {
                return false;
            }
        }

        // GDPR Cookie Consent by WebToffee.
        if ( isset( $_COOKIE['viewed_cookie_policy'] ) && 'yes' === sanitize_text_field( wp_unslash( $_COOKIE['viewed_cookie_policy'] ) ) ) {
            return true;
        }

        return apply_filters( 'capiflow_gdpr_consent_default', true );
    }

    /**
     * Get system health data for the dashboard.
     *
     * @return array System status checks.
     */
    public static function get_system_health() {
        $health = array();

        // PHP version.
        $health['php'] = array(
            'label'   => 'PHP Version',
            'value'   => PHP_VERSION,
            'status'  => version_compare( PHP_VERSION, '7.4', '>=' ) ? 'good' : 'bad',
            'message' => version_compare( PHP_VERSION, '7.4', '>=' )
                ? ''
                : 'PHP 7.4+ required',
        );

        // WooCommerce.
        $health['woocommerce'] = array(
            'label'   => 'WooCommerce',
            'value'   => defined( 'WC_VERSION' ) ? WC_VERSION : 'Not installed',
            'status'  => class_exists( 'WooCommerce' ) ? 'good' : 'bad',
            'message' => '',
        );

        // OpenSSL.
        $health['openssl'] = array(
            'label'   => 'OpenSSL Extension',
            'value'   => extension_loaded( 'openssl' ) ? 'Loaded' : 'Missing',
            'status'  => extension_loaded( 'openssl' ) ? 'good' : 'bad',
            'message' => '',
        );

        // Action Scheduler.
        $health['action_scheduler'] = array(
            'label'   => 'Action Scheduler',
            'value'   => function_exists( 'as_schedule_recurring_action' ) ? 'Available' : 'Missing',
            'status'  => function_exists( 'as_schedule_recurring_action' ) ? 'good' : 'warning',
            'message' => function_exists( 'as_schedule_recurring_action' )
                ? ''
                : 'WooCommerce provides Action Scheduler',
        );

        // CAPI Connection.
        $pixel_id = get_option( 'capiflow_pixel_id', '' );
        if ( ! empty( $pixel_id ) ) {
            $sender = new CAPI_Sender();
            $test   = $sender->test_connection( $pixel_id );
            $health['capi_connection'] = array(
                'label'   => 'Meta CAPI Connection',
                'value'   => $test['success'] ? 'Connected' : 'Failed',
                'status'  => $test['success'] ? 'good' : 'bad',
                'message' => $test['message'],
            );
        } else {
            $health['capi_connection'] = array(
                'label'   => 'Meta CAPI Connection',
                'value'   => 'Not configured',
                'status'  => 'warning',
                'message' => 'Enter Pixel ID in settings',
            );
        }

        // REST API — check route registration (not loopback; shared hosting blocks self-requests).
        $rest_server    = rest_get_server();
        $routes         = $rest_server->get_routes();
        $route_exists   = isset( $routes['/capiflow/v1/track'] );
        $rest_available = ! ( defined( 'WP_REST_API_DISABLED' ) && WP_REST_API_DISABLED );
        $permalink_ok   = ! empty( get_option( 'permalink_structure', '' ) );

        if ( $route_exists && $rest_available ) {
            $rest_status  = 'good';
            $rest_value   = 'Registered';
            $rest_message = rest_url( 'capiflow/v1/track' );
        } elseif ( ! $rest_available ) {
            $rest_status  = 'bad';
            $rest_value   = 'Disabled';
            $rest_message = 'WP REST API is disabled. Remove WP_REST_API_DISABLED constant.';
        } elseif ( ! $route_exists ) {
            $rest_status  = 'bad';
            $rest_value   = 'Not Registered';
            $rest_message = 'The /capiflow/v1/track route is missing. Try flushing permalinks.';
        } else {
            $rest_status  = 'warning';
            $rest_value   = 'Unknown';
            $rest_message = '';
        }

        // Warn about plain permalinks (REST works but with ?rest_route= format).
        if ( ! $permalink_ok && 'good' === $rest_status ) {
            $rest_status  = 'warning';
            $rest_message = 'Using plain permalinks. Set to "Post name" in Settings → Permalinks for clean URLs.';
        }

        $health['rest_api'] = array(
            'label'   => 'REST API Endpoint',
            'value'   => $rest_value,
            'status'  => $rest_status,
            'message' => $rest_message,
        );

        // Object cache (Redis/Memcached).
        $health['object_cache'] = array(
            'label'   => 'Object Cache',
            'value'   => wp_using_ext_object_cache() ? 'Active (Redis/Memcached)' : 'Default',
            'status'  => 'good',
            'message' => '',
        );

        // WP-Cron.
        $health['wp_cron'] = array(
            'label'   => 'WP-Cron',
            'value'   => ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) ? 'Disabled (use system cron)' : 'Active',
            'status'  => 'good',
            'message' => ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON )
                ? 'Ensure system cron calls wp-cron.php every minute'
                : '',
        );

        return $health;
    }
}
