<?php

/**

 * Demo Data Generator for SensFRX

 *

 * Provides realistic sample data for first-time installs and handles zero/low data states

 * with educational messaging to prevent user churn.

 *

 * @link       https://sensfrx.ai

 * @since      1.0.0

 *

 * @package    SensFRX

 * @subpackage SensFRX/includes

 */



if (!defined('ABSPATH')) {

    die('Direct access not permitted');

}



class SensFRX_Demo_Data {



    /**

     * Check if user should see demo data

     *

     * @return boolean

     */

    public static function should_show_demo_data() {

        // Show demo if:

        // 1. Plugin just installed (no real data yet)

        // 2. User explicitly enabled demo mode

        // 3. Very low data volume (less than 5 transactions)



        $demo_mode = get_option('sensfrx_demo_mode', 'auto');



        if ($demo_mode === 'enabled') {

            return true;

        }



        if ($demo_mode === 'disabled') {

            return false;

        }



        // Auto mode: check if we have real data

        global $wpdb;

        $table_name = $wpdb->prefix . 'sensfrx_fraud_cases';



        // Check if table exists

        $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ));

        if ( $table_exists !== $table_name ) { return true; }





        // Count real transactions

        $real_count = (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . esc_sql( $table_name ));



        // Show demo if less than 5 real transactions

        return ($real_count < 5);

    }



    /**

     * Generate realistic demo fraud statistics

     *

     * @return array

     */

    public static function get_demo_stats() {

        // Simulated 30-day metrics for a growing e-commerce store

        return array(

            'total_logins' => array(

                'current' => 847,

                'previous' => 723,

                'change' => '+17%',

                'trend' => 'up'

            ),

            'total_transactions' => array(

                'current' => 234,

                'previous' => 198,

                'change' => '+18%',

                'trend' => 'up'

            ),

            'total_registrations' => array(

                'current' => 156,

                'previous' => 142,

                'change' => '+10%',

                'trend' => 'up'

            ),

            'suspicious_activity' => array(

                'current' => 23,

                'previous' => 31,

                'change' => '-26%',

                'trend' => 'down',

                'label' => 'Blocked'

            ),

            'fraud_prevented' => array(

                'amount' => '$2,847',

                'count' => 12,

                'percentage' => '5.1%'

            ),

            'risk_score' => array(

                'average' => 27,

                'high_risk' => 8,

                'medium_risk' => 47,

                'low_risk' => 179

            )

        );

    }



    /**

     * Generate demo fraud cases for review queue

     *

     * @param int $count Number of demo cases to generate

     * @return array

     */

    public static function get_demo_fraud_cases($count = 3) {

        $cases = array();



        $risk_scenarios = array(

            array(

                'customer' => 'Sarah M.',

                'email' => 's****@example.com',

                'amount' => '$127.50',

                'risk_score' => 68,

                'risk_level' => 'medium',

                'reason' => 'New customer, high-value order',

                'country' => 'United States',

                'device' => 'Mobile',

                'time' => '2 hours ago'

            ),

            array(

                'customer' => 'John D.',

                'email' => 'j****@gmail.com',

                'amount' => '$89.99',

                'risk_score' => 52,

                'risk_level' => 'medium',

                'reason' => 'Multiple failed login attempts',

                'country' => 'Canada',

                'device' => 'Desktop',

                'time' => '5 hours ago'

            ),

            array(

                'customer' => 'Mike R.',

                'email' => 'm****@yahoo.com',

                'amount' => '$245.00',

                'risk_score' => 47,

                'risk_level' => 'low',

                'reason' => 'Shipping address mismatch',

                'country' => 'United Kingdom',

                'device' => 'Mobile',

                'time' => '1 day ago'

            )

        );



        for ($i = 0; $i < min($count, count($risk_scenarios)); $i++) {

            $cases[] = $risk_scenarios[$i];

        }



        return $cases;

    }



    /**

     * Get smart empty state message based on context

     *

     * @param string $context The dashboard section (metrics, review_queue, etc.)

     * @return array Message data with title, description, and action

     */

    public static function get_empty_state_message($context) {

        $messages = array(

            'review_queue' => array(

                'icon' => 'shield-check',

                'title' => 'No Orders Need Review',

                'description' => 'Great news! All your orders are passing our fraud checks automatically.',

                'insight' => 'This means your Smart Protection policies are working perfectly.',

                'action' => array(

                    'text' => 'Review Protection Settings',

                    'link' => '?page=sensfrx_fpwoo&tab=validation-rules'

                ),

                'tip' => 'Tip: You can adjust sensitivity levels in Validation Rules if you want stricter checks.'

            ),

            'recent_activity' => array(

                'icon' => 'activity',

                'title' => 'Waiting for Your First Orders',

                'description' => 'Once customers start placing orders, you\'ll see real-time fraud analysis here.',

                'insight' => 'SensFRX is actively protecting your store right now - we\'re just waiting for traffic.',

                'action' => array(

                    'text' => 'Test with Sample Order',

                    'link' => '?page=sensfrx_fpwoo&tab=settings#test-mode'

                ),

                'tip' => 'While you wait, explore our Smart Protection policies to customize your fraud rules.'

            ),

            'metrics_low' => array(

                'icon' => 'trending-up',

                'title' => 'Building Your Protection Profile',

                'description' => 'We need a bit more data to show meaningful trends and patterns.',

                'insight' => 'After ~25-50 transactions, you\'ll see detailed analytics about your customers and threats.',

                'progress' => true,

                'action' => array(

                    'text' => 'See What\'s Coming',

                    'link' => '#',

                    'modal' => 'demo-preview'

                ),

                'tip' => 'Every transaction helps us learn and better protect your store.'

            ),

            'fraud_cases_zero' => array(

                'icon' => 'shield',

                'title' => 'Zero Fraud Detected',

                'description' => 'Excellent! We haven\'t detected any fraudulent activity on your store.',

                'insight' => 'This could mean your current traffic is legitimate, or you\'re in the early growth phase.',

                'action' => array(

                    'text' => 'View Protection Status',

                    'link' => '?page=sensfrx_fpwoo&tab=dashboard'

                ),

                'tip' => 'Keep your protection policies up to date as your store grows.'

            )

        );



        return isset($messages[$context]) ? $messages[$context] : $messages['recent_activity'];

    }



    /**

     * Render smart empty state UI

     *

     * @param string $context Context for the empty state

     * @param array $options Additional display options

     * @return string HTML for empty state

     */

    public static function render_empty_state($context, $options = array()) {

        $message = self::get_empty_state_message($context);

        $show_demo_toggle = isset($options['show_demo_toggle']) ? $options['show_demo_toggle'] : true;

        $compact = isset($options['compact']) ? $options['compact'] : false;



        $padding = $compact ? '32px 24px' : '48px 32px';



        ob_start();

        ?>

        <div class="sensfrx-empty-state" style="text-align: center; padding: <?php echo esc_attr($padding); ?>; background: linear-gradient(135deg, #f9fafb 0%, #ffffff 100%); border-radius: 12px; border: 2px dashed #e5e7eb;">



            <!-- Icon -->

            <div style="margin-bottom: 20px;">

                <div style="width: 64px; height: 64px; margin: 0 auto; background: linear-gradient(135deg, #EFF6FF 0%, #DBEAFE 100%); border-radius: 16px; display: flex; align-items: center; justify-content: center;">

                    <?php echo esc_html( self::get_icon_svg( $message['icon'], 32 ) ); ?>

                </div>

            </div>



            <!-- Title -->

            <h3 style="margin: 0 0 8px; font-size: 18px; font-weight: 700; color: #111827;">

                <?php echo esc_html($message['title']); ?>

            </h3>



            <!-- Description -->

            <p style="margin: 0 0 16px; font-size: 14px; color: #6B7280; line-height: 1.6; max-width: 480px; margin-left: auto; margin-right: auto;">

                <?php echo esc_html($message['description']); ?>

            </p>



            <!-- Insight Box -->

            <div style="background: white; border-left: 3px solid #3B82F6; padding: 12px 16px; border-radius: 6px; margin: 20px auto; max-width: 520px; text-align: left;">

                <div style="display: flex; align-items: start; gap: 10px;">

                    <svg width="18" height="18" viewBox="0 0 20 20" fill="none" style="flex-shrink: 0; margin-top: 2px;">

                        <path d="M10 0C4.5 0 0 4.5 0 10s4.5 10 10 10 10-4.5 10-10S15.5 0 10 0zm1 15H9v-2h2v2zm0-4H9V5h2v6z" fill="#3B82F6"/>

                    </svg>

                    <p style="margin: 0; font-size: 13px; color: #374151; line-height: 1.5;">

                        <?php echo esc_html($message['insight']); ?>

                    </p>

                </div>

            </div>



            <!-- Progress Bar (if applicable) -->

            <?php if (isset($message['progress']) && $message['progress']): ?>

            <div style="max-width: 360px; margin: 20px auto;">

                <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">

                    <span style="font-size: 12px; color: #6B7280; font-weight: 600;">Data Collection Progress</span>

                    <span style="font-size: 12px; color: #3B82F6; font-weight: 700;">12%</span>

                </div>

                <div style="height: 6px; background: #E5E7EB; border-radius: 3px; overflow: hidden;">

                    <div style="height: 100%; background: linear-gradient(90deg, #3B82F6 0%, #1E40AF 100%); width: 12%; transition: width 0.3s ease;"></div>

                </div>

                <p style="margin: 8px 0 0; font-size: 11px; color: #9CA3AF;">~13 more transactions needed for full analytics</p>

            </div>

            <?php endif; ?>



            <!-- Action Button -->

            <?php if (isset($message['action'])): ?>

            <a href="<?php echo esc_url($message['action']['link']); ?>"

               style="display: inline-block; margin-top: 12px; padding: 10px 24px; background: linear-gradient(135deg, #3B82F6 0%, #1E40AF 100%); color: white; text-decoration: none; border-radius: 8px; font-size: 14px; font-weight: 600; transition: transform 0.2s;"

               onmouseover="this.style.transform='translateY(-1px)'"

               onmouseout="this.style.transform='translateY(0)'">

                <?php echo esc_html($message['action']['text']); ?> →

            </a>

            <?php endif; ?>



            <!-- Tip -->

            <?php if (isset($message['tip'])): ?>

            <p style="margin: 20px 0 0; font-size: 12px; color: #9CA3AF; font-style: italic;">

                <?php echo esc_html($message['tip']); ?>

            </p>

            <?php endif; ?>



            <!-- Demo Mode Toggle -->

            <?php if ($show_demo_toggle): ?>

            <div style="margin-top: 24px; padding-top: 20px; border-top: 1px solid #E5E7EB;">

                <label style="display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: 12px; color: #6B7280;">

                    <input type="checkbox" id="sensfrx-demo-toggle" style="width: 16px; height: 16px; cursor: pointer; accent-color: #3B82F6;">

                    <span>Show me sample data to see how it looks</span>

                </label>

            </div>

            <?php endif; ?>

        </div>

        <?php

        return ob_get_clean();

    }



    /**

     * Get SVG icon by name

     *

     * @param string $name Icon name

     * @param int $size Icon size

     * @return string SVG HTML

     */

    private static function get_icon_svg($name, $size = 24) {

        $icons = array(

            'shield-check' => '<svg width="' . $size . '" height="' . $size . '" viewBox="0 0 24 24" fill="none"><path d="M12 2L4 6v6c0 5.5 3.8 10.7 8 12 4.2-1.3 8-6.5 8-12V6l-8-4z" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M9 12l2 2 4-4" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'activity' => '<svg width="' . $size . '" height="' . $size . '" viewBox="0 0 24 24" fill="none"><path d="M22 12h-4l-3 9L9 3l-3 9H2" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'trending-up' => '<svg width="' . $size . '" height="' . $size . '" viewBox="0 0 24 24" fill="none"><path d="M23 6l-9.5 9.5-5-5L1 18" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M17 6h6v6" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',

            'shield' => '<svg width="' . $size . '" height="' . $size . '" viewBox="0 0 24 24" fill="none"><path d="M12 2L4 6v6c0 5.5 3.8 10.7 8 12 4.2-1.3 8-6.5 8-12V6l-8-4z" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'

        );



        return isset($icons[$name]) ? $icons[$name] : $icons['shield'];

    }

}

