<?php

/**

 * SensFRX Honest Fallback System

 * NO FALSE SECURITY - Real protection or clear demo mode

 */



/**

 * Check if we're in demo mode (SDK not configured)

 */

function sensfrx_is_demo_mode() {

    $options = get_option('sensfrx_options', []);

    return empty($options['sensfrx_property_id']) ||

           empty($options['sensfrx_property_secret']) ||

           !class_exists('SensFRX\SensFRX');

}



/**

 * Get protection status message

 */

function sensfrx_get_protection_status() {

    if (sensfrx_is_demo_mode()) {

        return [

            'status' => 'demo',

            'message' => '⚠️ Demo Mode - Not Protected',

            'details' => 'Connect to SensFRX API for real protection',

            'color' => '#f59e0b' // Warning orange

        ];

    }



    return [

        'status' => 'active',

        'message' => '✅ Protection Active',

        'details' => 'Connected to SensFRX Cloud',

        'color' => '#10b981' // Success green

    ];

}



/**

 * HONEST fraud cases handler

 */

function sensfrx_get_honest_fraud_cases($filter = 'all') {

    if (sensfrx_is_demo_mode()) {

        // CLEARLY MARKED AS DEMO DATA

        return [

            'success' => true,

            'demo_mode' => true, // CLEAR FLAG

            'message' => 'Showing demo data - Connect API for real fraud data',

            'data' => [

                [

                    'id' => 'demo_1',

                    'type' => '🎭 DEMO: Example Fraud Block',

                    'email' => 'demo@example.com',

                    'ip_address' => 'XXX.XXX.XXX.XXX',

                    'risk_score' => 'N/A',

                    'status' => 'demo',

                    'timestamp' => current_time('c'),

                    'details' => [

                        'message' => 'This is example data. Real threats will appear here once API is connected.'

                    ]

                ]

            ]

        ];

    }



    // Real API call here

    return sensfrx_get_real_fraud_data($filter);

}



/**

 * HONEST statistics - No fake numbers

 */

function sensfrx_get_honest_stats() {

    if (sensfrx_is_demo_mode()) {

        return [

            'mode' => 'demo',

            'blocked_threats' => [

                'value' => 0,

                'label' => 'Blocked (Demo)',

                'real' => false

            ],

            'trusted_customers' => [

                'value' => 0,

                'label' => 'Trusted (Demo)',

                'real' => false

            ],

            'ai_patterns' => [

                'value' => '---',

                'label' => 'Not Available',

                'real' => false

            ],

            'accuracy_rate' => [

                'value' => '---',

                'label' => 'Connect API to Calculate',

                'real' => false

            ],

            'fraud_prevented' => [

                'value' => '$0',

                'label' => 'No Protection Active',

                'real' => false

            ],

            'message' => '⚠️ Demo Mode: Connect to SensFRX for real protection'

        ];

    }



    // Real stats from API

    return sensfrx_get_real_stats();

}



/**

 * LOCAL BLOCKING THAT ACTUALLY WORKS

 */

add_action('woocommerce_checkout_process', 'sensfrx_enforce_local_blocks', 5);

function sensfrx_enforce_local_blocks() {

    // This ACTUALLY blocks orders

    if (!isset($_POST['billing_email'])) {

        return;

    }



    $email = sanitize_email($_POST['billing_email']);

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



    // Check local blacklist and ACTUALLY BLOCK

    $local_blacklist = get_option('sensfrx_local_blacklist', []);



    foreach ($local_blacklist as $blocked_item) {

        if ($blocked_item['status'] !== 'active') {

            continue;

        }



        // Check email blocks

        if ($blocked_item['type'] === 'email' && $blocked_item['value'] === $email) {

            wc_add_notice(

                '🛡️ Order blocked: This email has been flagged for fraudulent activity.',

                'error'

            );



            // Log the ACTUAL block

            sensfrx_log_real_block($email, 'email', 'local_blacklist');

            return; // Stop checkout

        }



        // Check IP blocks

        if ($blocked_item['type'] === 'ip' && $blocked_item['value'] === $ip) {

            wc_add_notice(

                '🛡️ Order blocked: Your connection has been flagged for security reasons.',

                'error'

            );



            // Log the ACTUAL block

            sensfrx_log_real_block($ip, 'ip', 'local_blacklist');

            return; // Stop checkout

        }

    }

}



/**

 * Log REAL blocks only

 */

function sensfrx_log_real_block($value, $type, $source) {

    $block_log = get_option('sensfrx_real_blocks', []);



    $block_log[] = [

        'value' => $value,

        'type' => $type,

        'source' => $source, // 'local_blacklist' or 'api'

        'timestamp' => current_time('mysql'),

        'prevented_amount' => WC()->cart ? WC()->cart->total : 0,

        'real_block' => true // This actually happened

    ];



    // Keep last 1000 real blocks

    if (count($block_log) > 1000) {

        $block_log = array_slice($block_log, -1000);

    }



    update_option('sensfrx_real_blocks', $block_log);

}



/**

 * Dashboard widget - HONEST version

 */

function sensfrx_honest_dashboard_widget() {

    $status = sensfrx_get_protection_status();

    $real_blocks = get_option('sensfrx_real_blocks', []);



    // Count REAL blocks only

    $today_count = 0;

    $week_count = 0;

    $total_prevented = 0;



    $today = date('Y-m-d');

    $week_ago = date('Y-m-d', strtotime('-7 days'));



    foreach ($real_blocks as $block) {

        $block_date = date('Y-m-d', strtotime($block['timestamp']));

        if ($block_date === $today) {

            $today_count++;

        }

        if ($block_date >= $week_ago) {

            $week_count++;

        }

        $total_prevented += floatval($block['prevented_amount']);

    }



    ?>

    <div style="padding: 10px; background: <?php echo esc_html( $status['color'] ); ?>; color: white; border-radius: 6px; margin-bottom: 15px;">

        <strong><?php echo esc_html( $status['message'] ); ?></strong><br>

        <small><?php echo esc_html( $status['details'] ); ?></small>

    </div>



    <?php if (sensfrx_is_demo_mode()): ?>

        <div style="background: #fef3c7; border: 1px solid #fbbf24; padding: 10px; border-radius: 6px; margin-bottom: 15px;">

            <strong>👋 Welcome to SensFRX!</strong><br>

            <p style="margin: 5px 0;">To start protecting your store:</p>

            <ol style="margin: 5px 0 0 20px; padding: 0;">

                <li>Complete the setup wizard</li>

                <li>Connect your API credentials</li>

                <li>Configure protection rules</li>

            </ol>

            <a href="<?php echo esc_url( admin_url('admin.php?page=sensfrx-setup-wizard') ); ?>"

               class="button button-primary" style="margin-top: 10px;">

                Start Setup

            </a>

        </div>

    <?php else: ?>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px;">

            <div style="text-align: center; padding: 10px; background: #f3f4f6; border-radius: 6px;">

                <div style="font-size: 20px; font-weight: bold;"><?php echo esc_html( $today_count ); ?></div>

                <div style="font-size: 12px; color: #6b7280;">Real Blocks Today</div>

            </div>

            <div style="text-align: center; padding: 10px; background: #f3f4f6; border-radius: 6px;">

                <div style="font-size: 20px; font-weight: bold;">$<?php echo number_format($total_prevented, 2); ?></div>

                <div style="font-size: 12px; color: #6b7280;">Fraud Prevented</div>

            </div>

        </div>

    <?php endif; ?>



    <div style="border-top: 1px solid #e5e7eb; padding-top: 10px;">

        <a href="<?php echo esc_url( admin_url('admin.php?page=sensfrx_fpwoo') ); ?>"

           class="button button-secondary" style="width: 100%; text-align: center;">

            <?php echo sensfrx_is_demo_mode() ? 'Complete Setup' : 'View Dashboard'; ?>

        </a>

    </div>

    <?php

}



/**

 * Add warning banner to admin pages in demo mode

 */

add_action('admin_notices', 'sensfrx_demo_mode_warning');

function sensfrx_demo_mode_warning() {

    if (!sensfrx_is_demo_mode()) {

        return;

    }



    // Only show on WooCommerce and SensFRX pages

    $screen = get_current_screen();

    if (!$screen || (strpos($screen->id, 'woocommerce') === false && strpos($screen->id, 'sensfrx') === false)) {

        return;

    }



    ?>

    <div class="notice notice-warning">

        <p>

            <strong>⚠️ SensFRX Demo Mode:</strong>

            Your store is NOT protected against fraud.

            <a href="<?php echo esc_url( admin_url('admin.php?page=sensfrx-setup-wizard') ); ?>">Complete setup</a>

            to enable real protection or

            <a href="#" onclick="jQuery(this).closest('.notice').fadeOut(); return false;">dismiss</a>

        </p>

    </div>

    <?php

}



/**

 * Mark all demo data clearly in REST responses

 */

add_filter('rest_pre_echo_response', 'sensfrx_mark_demo_data', 10, 3);

function sensfrx_mark_demo_data($result, $server, $request) {

    $route = $request->get_route();



    if (strpos($route, 'sensfrx') !== false && sensfrx_is_demo_mode()) {

        if (is_array($result)) {

            $result['_demo_mode'] = true;

            $result['_warning'] = 'This is demo data. Connect API for real data.';

        }

    }



    return $result;

}



/**

 * Email notification - HONEST version

 */

function sensfrx_send_honest_notification($event_type, $data) {

    $subject_prefix = sensfrx_is_demo_mode() ? '[DEMO] ' : '';

    $footer_warning = sensfrx_is_demo_mode()

        ? '<p style="color: #f59e0b; margin-top: 20px; padding: 10px; background: #fef3c7; border-radius: 4px;">

           ⚠️ This is a demo notification. Real protection is not active.

           <a href="' . admin_url('admin.php?page=sensfrx-setup-wizard') . '">Complete setup</a>

           </p>'

        : '';



    // Rest of email sending logic

    $subject = $subject_prefix . $data['subject'];

    $body = $data['body'] . $footer_warning;



    wp_mail(

        get_option('admin_email'),

        $subject,

        $body,

        ['Content-Type: text/html; charset=UTF-8']

    );

}