<?php
/**
 * This is a short description of the package.
 *
 * @package           Sensfrx
 *
 * Plugin Name:       Sensfrx - Fraud Prevention for Woocommerce
 * Plugin URI:        https://sensfrx.ai
 * Description:       Prevent your WooCommerce store from fraudulent activities with Sensfrx.ai (SFX). Seamlessly integrate advanced fraud detection and prevention capabilities into your online store to secure your business and customers.
 * Version:           3.0.8
 * Author:            Sensfrx.ai (SFX)
 * License:           GPLv2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       sensfrx-fraud-prevention-for-woocommerce
 * Requires at least: 5.4
 * Requires PHP:      7.4
 * Requires Plugins:  woocommerce
 * Tested up to:      6.8.1
 * WC requires at least: 7.0
 * WC tested up to:      8.5
 */
if (! defined('WPINC')) {
    die;
}
define('SENSFRX_VERSION', '3.0.8');
// Activation and deactivation hooks
register_activation_hook(__FILE__, 'SensFRX_activate');
register_deactivation_hook(__FILE__, 'SensFRX_deactivate');
// REMOVED: Duplicate register_activation_hook - table creation now handled inside SensFRX_activate()
// register_activation_hook( __FILE__, 'sensfrx_table_create' );
// REMOVED: Table deletion on deactivation (WordPress.org compliance)
// Tables should only be deleted on uninstall, not deactivation
// See uninstall.php for proper data cleanup logic
function SensFRX_activate()
{
                       // The code that runs during plugin activation.
    require_once plugin_dir_path(__FILE__) . 'includes/class-sensfrx-activator.php';
    SensFRX_Activator::activate();
    // Create tables if function exists
    if (function_exists('sensfrx_table_create')) {
        sensfrx_table_create();
    }
    // Run activation callback
    if (function_exists('sensfrx_plugin_activation_callback')) {
        sensfrx_plugin_activation_callback();
    }
}
function SensFRX_deactivate()
{
    // The code that runs during plugin deactivation.
    // NOTE: Deactivation should be reversible - we do NOT delete any data here
    // All settings, credentials, and fraud data are preserved for reactivation
    require_once plugin_dir_path(__FILE__) . 'includes/class-sensfrx-deactivator.php';
    SensFRX_Deactivator::deactivate();
    // Clear scheduled cron tasks (these will be re-registered on reactivation)
    wp_clear_scheduled_hook('sensfrx_interval_cron_event');
}
function sensfrx_table_create()
{
                   // Table Insertion which sensfrx require for custom functionality.
    require_once plugin_dir_path(__FILE__) . 'includes/class-sensfrx-table-create.php';
    SensFRX_Table_Create::table_create();
}
// NOTE: This function is preserved for backward compatibility but should NOT be called on deactivation
// Table deletion should only occur during uninstall (see uninstall.php)
function sensfrx_table_delete()
{
    // This function is intentionally not called on deactivation
    // It's preserved here for backward compatibility with older code references
    // For proper cleanup, see uninstall.php
    require_once plugin_dir_path(__FILE__) . 'includes/class-sensfrx-table-delete.php';
    SensFRX_Table_Delete::table_delete();
}
require plugin_dir_path(__FILE__) . 'includes/class-sensfrx.php';
/**
 * Begins execution of the plugin.
 *
 * @since    1.0.0
 */
function SensFRX_run()
{
    $plugin = new SensFRX();
    $plugin->run();
    if (!defined('SENSFRX_URL')) {
        define('SENSFRX_URL', plugin_dir_url(__FILE__));
    }
    if (!defined('SENSFRX_DIR')) {
        define('SENSFRX_DIR', plugin_dir_path(__FILE__));
    }
    if (!defined('SENSFRX_FILE')) {
        define('SENSFRX_FILE', plugin_basename(__FILE__));
    }
    if (!defined('SENSFRX_SLUG')) {
        define('SENSFRX_SLUG', basename(dirname(__FILE__)));
    }
    if (!defined('SENSFRX_PIXEL_URL')) {
        define('SENSFRX_PIXEL_URL', 'https://p.sensfrx.ai/as.js?p=');
    }
}
SensFRX_run();
/**
 * Declare HPOS (High-Performance Order Storage) compatibility
 *
 * This declares that our plugin is compatible with WooCommerce's
 * High-Performance Order Storage (HPOS) feature.
 *
 * Required for WooCommerce 8.0+ and marketplace approval.
 *
 * @since 3.0.5
 */
add_action('before_woocommerce_init', function () {
    if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
            'custom_order_tables',
            __FILE__,
            true
        );
    }
});
function sensfrx_plugin_activation_callback()
{
    // Check if user already has credentials configured
    $options = get_option('sensfrx_options', SensFRX::default_options());
    $has_credentials = !empty($options['sensfrx_property_id']) && !empty($options['sensfrx_property_secret']);
    if (!$has_credentials) {
        // New user - show onboarding
        if (get_option('SensFRX_active', true)) {
            update_option('SensFRX_active', false);
            set_transient('Sensfrx_redirect_to_integration_page', true, 30);
        }
    }
}
function sensfrx_plugin_check_redirection()
{
    function my_custom_plugin_woocommerce_notice()
    {
        ?>
        <div class="notice notice-error">
            <p>
                <b style="color: blue;"><?php echo esc_html('Sensfrx - Fraud Prevention for Woocommerce'); ?></b>
                <b style="color: red;"> <?php echo esc_html('requires WooCommerce to be installed and active.'); ?></b>
            </p>
        </div>
        <?php
    }
    if (!is_plugin_active('woocommerce/woocommerce.php')) {
            add_action('admin_notices', 'my_custom_plugin_woocommerce_notice');
    }
    // Show persistent installation banner if setup is incomplete
    $options = get_option('sensfrx_options', SensFRX::default_options());
    $has_credentials = !empty($options['sensfrx_property_id']) && !empty($options['sensfrx_property_secret']);
    $banner_dismissed_until = get_option('sensfrx_setup_banner_dismissed', 0);
    // Show banner if: no credentials AND (never dismissed OR dismissal expired)
    $should_show_banner = !$has_credentials && (time() >= $banner_dismissed_until);
    if ($should_show_banner) {
        add_action('admin_notices', 'sensfrx_installation_incomplete_banner', 1);
    }
    if (get_transient('Sensfrx_redirect_to_integration_page')) {
        delete_transient('Sensfrx_redirect_to_integration_page');                            // Delete the transient to prevent further redirections
        wp_safe_redirect(admin_url('admin.php?page=sensfrx_fpwoo'));        // Redirect to the specified URL after plugin activation
    }
}
/**
 * Check if current page is a full-screen/full-editor page
 * These pages hide the admin menu and should not show the setup banner
 * 
 * @return bool True if current page is a full-screen editor page
 */
function sensfrx_is_fullscreen_editor_page() {
    $screen = get_current_screen();
    if ( ! $screen ) {
        return false;
    }
    // Check for WooCommerce Email Editor (uses full-screen mode)
    if ( isset( $_GET['woo_email'] ) ) {
        return true;
    }
    // Check for WooCommerce Email Editor screen patterns
    if ( strpos( $screen->id, 'woocommerce' ) !== false && strpos( $screen->id, 'email' ) !== false ) {
        return true;
    }
    // Check for WordPress Site Editor (full-screen mode)
    if ( $screen->id === 'site-editor' || $screen->base === 'site-editor' ) {
        return true;
    }
    // Check for Post/Page editor screens (Gutenberg editor - these are typically fullscreen by default)
    if ( $screen->base === 'post' ) {
        // Check if it's using block editor (method_exists check for compatibility)
        if ( method_exists( $screen, 'is_block_editor' ) && $screen->is_block_editor() ) {
            return true;
        }
        // Also check for standard post types that use block editor
        if ( in_array( $screen->post_type, array( 'post', 'page' ) ) ) {
            return true;
        }
    }
    return false;
}
function sensfrx_installation_incomplete_banner()
{
    // Hide banner on full-screen/full-editor pages
    if ( sensfrx_is_fullscreen_editor_page() ) {
        return;
    }
    ?>
    <div class="notice" style="position: relative; z-index: 3007; margin: 0 0 0 -20px; padding: 12px 20px; background: #246cf2; color: #fff; display: flex; align-items: center; justify-content: space-between; border: none; border-radius: 0; width: calc(100% + 20px);">
        <div>
            <strong style="font-size: 14px; font-weight: 400; color: #fff;">Sensfrx.ai (SFX) setup is incomplete</strong>
        </div>
        <div style="display: flex; gap: 12px; align-items: center;">
            <a href="https://discord.gg/zGBGQdwT4r" target="_blank" rel="noopener" style="color: #fff; text-decoration: underline; font-size: 13px;">Need help?</a>
            <a href="<?php echo esc_url( admin_url('admin.php?page=sensfrx_fpwoo') ); ?>" class="button" style="background: #fff; border: 1px solid #fff; color: #246cf2; font-size: 13px; padding: 4px 16px; height: auto; font-weight: 600; border-radius: 3px;">RESUME SETUP</a>
            <button type="button" class="button" style="background: transparent; border: 1px solid #fff; color: #fff; font-size: 13px; padding: 4px 16px; height: auto; font-weight: 400; border-radius: 3px;" onclick="sensfrxDismissBanner(event)">REMIND ME LATER</button>
        </div>
    </div>
    <!-- Professional Modal -->
    <div id="sensfrx-reminder-modal" style="display: none; position: fixed; z-index: 999999; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); backdrop-filter: blur(2px);">
        <div style="position: relative; background-color: #fff; margin: 10% auto; padding: 0; width: 90%; max-width: 480px; border-radius: 8px; box-shadow: 0 4px 24px rgba(0,0,0,0.2); animation: slideDown 0.3s ease;">
            <div style="padding: 24px 24px 20px; border-bottom: 1px solid #e5e7eb;">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <div style="width: 40px; height: 40px; border-radius: 50%; background: #246cf2; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 20px;">🔔</div>
                    <h3 style="margin: 0; font-size: 18px; font-weight: 600; color: #1d2327;">Notice Dismissed</h3>
                </div>
            </div>
            <div style="padding: 24px;">
                <p style="margin: 0 0 20px 0; font-size: 14px; line-height: 1.6; color: #50575e;">
                    You will be reminded again in <strong>24 hours</strong>.
                </p>
                <p style="margin: 0; font-size: 13px; line-height: 1.5; color: #6c757d; background: #f8f9fa; padding: 12px; border-radius: 4px; border-left: 3px solid #246cf2;">
                    💡 <strong>Tip:</strong> Complete your setup now to start protecting your store from fraud immediately.
                </p>
            </div>
            <div style="padding: 16px 24px; background: #f8f9fa; border-radius: 0 0 8px 8px; text-align: right;">
                <button onclick="closeSensfrxModal()" style="background: #246cf2; color: #fff; border: none; padding: 10px 24px; border-radius: 4px; font-size: 14px; font-weight: 500; cursor: pointer;">Got it</button>
            </div>
        </div>
    </div>
    <style>
    @keyframes slideDown {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    </style>
    <script>
    function sensfrxDismissBanner(e) {
        e.preventDefault();
        fetch('<?php echo esc_url(admin_url('admin-ajax.php') ); ?>', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'action=sensfrx_dismiss_setup_banner&nonce=<?php echo esc_html( wp_create_nonce('sensfrx_dismiss_banner') ); ?>'
        }).then(response => {
            if (response.ok) {
                e.target.closest('.notice').style.display = 'none';
                document.getElementById('sensfrx-reminder-modal').style.display = 'block';
            }
        });
    }
    function closeSensfrxModal() {
        document.getElementById('sensfrx-reminder-modal').style.display = 'none';
    }
    </script>
    <?php
}
// Handle banner dismissal via AJAX
add_action('wp_ajax_sensfrx_dismiss_setup_banner', 'sensfrx_handle_dismiss_banner');
function sensfrx_handle_dismiss_banner()
{
    check_ajax_referer('sensfrx_dismiss_banner', 'nonce');
    update_option('sensfrx_setup_banner_dismissed', time() + (24 * 60 * 60)); // Remind after 24 hours
    // Send reminder email after 24 hours
    sensfrx_schedule_reminder_email();
    wp_send_json_success();
}
// Schedule reminder email
function sensfrx_schedule_reminder_email()
{
    // Clear any existing scheduled email
    wp_clear_scheduled_hook('sensfrx_send_reminder_email');
    // Schedule email for 24 hours from now
    wp_schedule_single_event(time() + (24 * 60 * 60), 'sensfrx_send_reminder_email');
}
// Send reminder email hook
add_action('sensfrx_send_reminder_email', 'sensfrx_send_setup_reminder_email');
function sensfrx_send_setup_reminder_email()
{
    // Check if setup is still incomplete
    $options = get_option('sensfrx_options', SensFRX::default_options());
    $has_credentials = !empty($options['sensfrx_property_id']) && !empty($options['sensfrx_property_secret']);
    // Only send if still not configured
    if (!$has_credentials) {
        $admin_email = get_option('admin_email');
        $site_name = get_bloginfo('name');
        $setup_url = admin_url('admin.php?page=sensfrx_fpwoo');
        $subject = 'Complete Your Sensfrx.ai (SFX) Setup - ' . $site_name;
        $message = "Hello,\n\n";
        $message .= "This is a friendly reminder that your Sensfrx.ai (SFX) fraud prevention setup is incomplete on " . $site_name . ".\n\n";
        $message .= "Completing the setup will help protect your WooCommerce store from fraudulent activities and ensure the security of your business and customers.\n\n";
        $message .= "To complete the setup, please visit:\n";
        $message .= $setup_url . "\n\n";
        $message .= "If you need assistance, our community is ready to help:\n";
        $message .= "https://discord.gg/zGBGQdwT4r\n\n";
        $message .= "Or learn more about Sensfrx.ai (SFX):\n";
        $message .= "https://wordpress.org/plugins/sensfrx-fraud-prevention-for-woocommerce/\n\n";
        $message .= "Thank you for choosing Sensfrx.ai (SFX) to protect your store.\n\n";
        $message .= "Best regards,\n";
        $message .= "The Sensfrx.ai (SFX) Team";
        $headers = array('Content-Type: text/plain; charset=UTF-8');
        wp_mail($admin_email, $subject, $message, $headers);
    }
}
add_action('admin_init', 'sensfrx_plugin_check_redirection');
// Review banner functionality
add_action('admin_notices', 'sensfrx_review_banner');
function sensfrx_review_banner()
{
    // Only show to admins
    if (!current_user_can('manage_options')) {
        return;
    }
    // Don't show on onboarding page (when configuring)
    $options = get_option('sensfrx_options', SensFRX::default_options());
    $has_credentials = !empty($options['sensfrx_property_id']) && !empty($options['sensfrx_property_secret']);
    if (!$has_credentials) {
        return; // Don't show during initial setup/onboarding
    }
    // Check if banner was dismissed (comes back after 7 days)
    $dismissed_until = get_option('sensfrx_review_dismissed_until', 0);
    if (time() < $dismissed_until) {
        return; // Still in dismissed period
    }
    // Show the banner
    ?>
    <div class="notice notice-info sensfrx-review-banner is-dismissible" style="position: relative; border-left: 4px solid #246cf2; padding: 12px 40px 12px 20px; background: #fff;">
        <button type="button" class="notice-dismiss" onclick="sensfrxDismissReview()" style="position: absolute; top: 0; right: 0; padding: 9px; background: none; border: none; color: #787c82; cursor: pointer;">
            <span class="screen-reader-text">Dismiss this notice.</span>
        </button>
        <div style="display: flex; align-items: center; gap: 16px;">
            <div style="flex-shrink: 0;">
                <img src="<?php echo esc_url( plugins_url('admin/image/sensfrx.png', __FILE__) ); ?>" alt="Sensfrx.ai (SFX)" style="width: 80px; height: auto;">
            </div>
            <div style="flex: 1;">
                <h3 style="margin: 0 0 8px 0; font-size: 16px; font-weight: 600; color: #1d2327;">
                    Enjoying Sensfrx.ai (SFX) Fraud Prevention?
                </h3>
                <p style="margin: 0 0 12px 0; font-size: 14px; line-height: 1.6; color: #50575e;">
                    We hope Sensfrx.ai (SFX) is helping protect your WooCommerce store from fraud. If you have a moment, please consider leaving a review on WordPress.org. Your feedback helps us improve and helps other store owners discover our fraud prevention solution.
                </p>
                <div style="display: flex; gap: 12px; align-items: center;">
                    <a href="https://wordpress.org/support/plugin/sensfrx-fraud-prevention-for-woocommerce/reviews/#new-post" target="_blank" rel="noopener" class="button button-primary" style="background: #246cf2; border-color: #246cf2; text-decoration: none;" onclick="sensfrxDismissReview()">
                        Leave a Review
                    </a>
                    <button type="button" class="button" onclick="sensfrxDismissReview()">
                        Maybe later
                    </button>
                </div>
            </div>
        </div>
    </div>
    <script>
    function sensfrxDismissReview() {
        fetch('<?php echo esc_url( admin_url('admin-ajax.php') ); ?>', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'action=sensfrx_dismiss_review&nonce=<?php echo esc_html( wp_create_nonce('sensfrx_review_action') ); ?>'
        }).then(response => {
            if (response.ok) {
                document.querySelector('.sensfrx-review-banner').style.display = 'none';
            }
        });
    }
    </script>
    <?php
}
// Handle review banner dismissal (comes back after 7 days)
add_action('wp_ajax_sensfrx_dismiss_review', 'sensfrx_handle_dismiss_review');
function sensfrx_handle_dismiss_review()
{
    check_ajax_referer('sensfrx_review_action', 'nonce');
    // Set to come back in 7 days
    update_option('sensfrx_review_dismissed_until', time() + (7 * 24 * 60 * 60));
    wp_send_json_success();
}
// Cronjob setup
// Step 1: Add a custom schedule for every minute
add_filter('cron_schedules', 'sensfrx_add_every_minute_schedule');
function sensfrx_add_every_minute_schedule($schedules)
{
    $schedules['every_minute'] = array(
        'interval' => 60, // 60 seconds = 1 minute
        'display'  => __('Every Minute'),
    );
    return $schedules;
}
// Step 2: Schedule the cron event if it's not already scheduled
add_action('wp', 'sensfrx_interval_cron_event');
function sensfrx_interval_cron_event()
{
    if (!wp_next_scheduled('sensfrx_cron_task')) {
        wp_schedule_event(time(), 'every_minute', 'sensfrx_cron_task'); // Hook the event to our custom interval
    }
}
// Step 3: Define what happens when the event is triggered
add_action('sensfrx_cron_task', 'run_sensfrx_cron_task');
function run_sensfrx_cron_task()
{
    $current_time = time();
    $last_run_time = get_option('sensfrx_interval_last_run_time', 0);
    if (($current_time - $last_run_time) >= 5) {
        update_option('sensfrx_interval_last_run_time', $current_time);
        $log_message = date('Y-m-d H:i:s');
        $logs = get_option('sensfrx_cron_logs', []);
        $logs[] = $log_message;
        if (count($logs) > 20) {
            array_shift($logs);
        }
        update_option('sensfrx_cron_logs', $logs);
    }
}
// Step 3: update the plugin that time it inserted
// add_filter( 'upgrader_process_complete', 'sensfrx_interval_update' );
// function sensfrx_interval_update() {
//  sensfrx_interval_cron_event();
// }
