<?php

/**

 * SensFRX SMB Features Loader

 * This file integrates all the new SMB features into the main plugin

 * Add this to your main plugin file or admin init

 */



// Check if we're in WordPress admin

if (!is_admin()) {

    return;

}



/**

 * Load all SMB feature files

 */

function sensfrx_load_smb_features() {

    $base_dir = plugin_dir_path(__FILE__) . 'admin/includes/';



    // Core features to load

    $features = [

        // Fraud Management Center

        'sensfrx-fraud-management-filters.php',

        'sensfrx-fraud-export-actions.php',

        'sensfrx-fraud-management-table.php',



        // SMB Features

        'sensfrx-protection-tabs-smb.php',

        'sensfrx-smb-setup-wizard.php',

        'sensfrx-email-notifications.php',

        'sensfrx-weekly-report.php',

        'sensfrx-smb-integration.php',

        'sensfrx-honest-fallbacks.php',



        // Fixed version of AJAX handlers

        'sensfrx-smb-ajax-handlers-FIXED.php'

    ];



    // Load each feature file if it exists

    foreach ($features as $feature) {

        $file_path = $base_dir . $feature;

        if (file_exists($file_path)) {

            require_once $file_path;

        } else {

            // Log missing file for debugging

            error_log('SensFRX: Missing feature file - ' . $file_path);

        }

    }

}



// Hook to admin_init to load features

add_action('admin_init', 'sensfrx_load_smb_features');



/**

 * Add SMB menu items to WordPress admin

 */

function sensfrx_add_smb_menu_items() {

    // Main SensFRX menu (if not already exists)

    if (!menu_page_exists('sensfrx_fpwoo')) {

        add_menu_page(

            'SensFRX Protection',

            'SensFRX',

            'manage_options',

            'sensfrx_fpwoo',

            'sensfrx_main_dashboard',

            'dashicons-shield',

            26

        );

    }



    // Add Fraud Management submenu

    add_submenu_page(

        'sensfrx_fpwoo',

        'Fraud Management',

        '🔍 Fraud Management',

        'manage_options',

        'sensfrx-fraud-management',

        'sensfrx_fraud_management_page'

    );



    // Add Protection Settings submenu

    add_submenu_page(

        'sensfrx_fpwoo',

        'Protection Settings',

        '🛡️ Protection',

        'manage_options',

        'sensfrx-protection',

        'sensfrx_protection_page'

    );



    // Add Setup Wizard (hidden from menu but accessible)

    add_submenu_page(

        null, // Hidden from menu

        'Setup Wizard',

        'Setup Wizard',

        'manage_options',

        'sensfrx-setup-wizard',

        'sensfrx_setup_wizard_page'

    );



    // Add Email Settings submenu

    add_submenu_page(

        'sensfrx_fpwoo',

        'Email Notifications',

        '📧 Notifications',

        'manage_options',

        'sensfrx-email-settings',

        'sensfrx_email_settings_page'

    );

}



add_action('admin_menu', 'sensfrx_add_smb_menu_items', 20);



/**

 * Page callback functions

 */

function sensfrx_fraud_management_page() {

    ?>

    <div class="wrap">

        <h1>🔍 Fraud Management Center</h1>



        <?php

        // Load filters

        if (function_exists('sensfrx_render_friendly_filters')) {

            sensfrx_render_friendly_filters();

        }



        // Load export/bulk actions

        if (function_exists('sensfrx_render_export_bulk_actions')) {

            sensfrx_render_export_bulk_actions();

        }



        // Load table

        if (function_exists('sensfrx_render_fraud_management_table')) {

            sensfrx_render_fraud_management_table();

        }

        ?>

    </div>

    <?php

}



function sensfrx_protection_page() {

    ?>

    <div class="wrap">

        <h1>🛡️ Protection Settings</h1>



        <?php

        // Load protection tabs

        if (function_exists('sensfrx_render_protection_tabs')) {

            sensfrx_render_protection_tabs();

        }

        ?>

    </div>

    <?php

}



function sensfrx_setup_wizard_page() {

    // Load setup wizard

    if (function_exists('sensfrx_render_setup_wizard')) {

        sensfrx_render_setup_wizard();

    }

}



function sensfrx_email_settings_page() {

    ?>

    <div class="wrap">

        <h1>📧 Email Notifications</h1>



        <?php

        // Load email settings

        if (function_exists('sensfrx_render_email_settings')) {

            sensfrx_render_email_settings();

        }

        ?>

    </div>

    <?php

}



/**

 * Check if menu page exists

 */

function menu_page_exists($menu_slug) {

    global $menu;

    if (!is_array($menu)) {

        return false;

    }



    foreach ($menu as $item) {

        if (isset($item[2]) && $item[2] === $menu_slug) {

            return true;

        }

    }

    return false;

}



/**

 * Enqueue SMB styles and scripts

 */

function sensfrx_enqueue_smb_assets() {

    // Only load on our pages

    $screen = get_current_screen();

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

        return;

    }



    // Add inline styles for SMB features

    wp_add_inline_style('wp-admin', '

        .sensfrx-table tbody tr:hover {

            background-color: #f9fafb !important;

        }

        .filter-pill {

            transition: all 0.2s ease;

        }

        .filter-pill:hover {

            transform: translateY(-1px);

            box-shadow: 0 2px 4px rgba(0,0,0,0.1);

        }

        .action-btn {

            transition: all 0.2s ease;

        }

        .action-btn:hover {

            transform: scale(1.05);

        }

        .sensfrx-section {

            animation: fadeIn 0.3s ease;

        }

        @keyframes fadeIn {

            from { opacity: 0; transform: translateY(10px); }

            to { opacity: 1; transform: translateY(0); }

        }

    ');



    // Add JavaScript for AJAX nonce

    wp_localize_script('jquery', 'sensfrx_ajax', array(

        'ajax_url' => admin_url('admin-ajax.php'),

        'nonce' => wp_create_nonce('sensfrx_ajax_nonce'),

        'filter_nonce' => wp_create_nonce('sensfrx_filter'),

        'export_nonce' => wp_create_nonce('sensfrx_export'),

        'bulk_nonce' => wp_create_nonce('sensfrx_bulk')

    ));

}



add_action('admin_enqueue_scripts', 'sensfrx_enqueue_smb_assets');



/**

 * Activation notice for first-time users

 */

function sensfrx_show_activation_notice() {

    $setup_complete = get_option('sensfrx_wizard_completed', false);



    if (!$setup_complete && current_user_can('manage_options')) {

        ?>

        <div class="notice notice-success is-dismissible">

            <h2>🎉 SensFRX SMB Features Activated!</h2>

            <p><strong>New features are now available:</strong></p>

            <ul style="list-style: disc; margin-left: 20px;">

                <li>🔍 Fraud Management Center with shop owner friendly filters</li>

                <li>🛡️ Protection Settings with Block/Trust Lists</li>

                <li>📧 Email Notifications with templates</li>

                <li>📊 Weekly Protection Reports</li>

                <li>🚀 3-minute Setup Wizard</li>

            </ul>

            <p>

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

                    Start Setup Wizard

                </a>

                <a href="<?php echo esc_url( admin_url('admin.php?page=sensfrx-fraud-management') ); ?>" class="button">

                    View Fraud Management

                </a>

            </p>

        </div>

        <?php

    }

}



add_action('admin_notices', 'sensfrx_show_activation_notice');



/**

 * Add dashboard widget

 */

function sensfrx_add_dashboard_widgets() {

    if (function_exists('sensfrx_honest_dashboard_widget')) {

        wp_add_dashboard_widget(

            'sensfrx_protection_status',

            '🛡️ SensFRX Fraud Protection',

            'sensfrx_honest_dashboard_widget'

        );

    }

}



add_action('wp_dashboard_setup', 'sensfrx_add_dashboard_widgets');



/**

 * Initialize SMB features on plugin activation

 */

function sensfrx_initialize_smb_features() {

    // Set default options

    $default_options = [

        'sensfrx_smb_rules' => [

            'failed_logins' => ['enabled' => true],

            'disposable_emails' => ['enabled' => true],

            'high_risk_countries' => ['enabled' => false],

            'velocity_check' => ['enabled' => true],

            'address_mismatch' => ['enabled' => false],

            'large_first_order' => ['enabled' => true]

        ],

        'sensfrx_email_settings' => [

            'email_alerts' => true,

            'high_risk_alerts' => true,

            'weekly_report' => true,

            'notification_email' => get_option('admin_email')

        ]

    ];



    foreach ($default_options as $option_name => $option_value) {

        if (get_option($option_name) === false) {

            update_option($option_name, $option_value);

        }

    }



    // Schedule weekly report cron

    if (!wp_next_scheduled('sensfrx_weekly_report_cron')) {

        wp_schedule_event(

            strtotime('next Monday 9:00am'),

            'weekly',

            'sensfrx_weekly_report_cron'

        );

    }

}



// Initialize on activation

register_activation_hook(__FILE__, 'sensfrx_initialize_smb_features');



// Also initialize if not done yet

add_action('admin_init', function() {

    if (get_option('sensfrx_smb_initialized') !== 'yes') {

        sensfrx_initialize_smb_features();

        update_option('sensfrx_smb_initialized', 'yes');

    }

});

