<?php
/**
 * ZUTALW Frontend: Enqueue scripts & Output public UI
 * Optimized Version: Click Trigger + Security Checks + Object Caching
 * FIXED: Pass tradein_enabled to JS and add comprehensive debug logs
 */

if ( ! defined( 'ABSPATH' ) ) { exit; }

class ZUTALW_Frontend {

    protected $cache_group = 'zutalw_spin_limits';

    public function __construct() {
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_public_assets' ) );
        add_action( 'wp_footer', array( $this, 'auto_display_wheel' ) );
        add_action( 'wp_footer', array( $this, 'loading_markup' ) );
        add_action( 'wp_footer', array( $this, 'popup_notify_markup' ) );

        add_action( 'wp_ajax_zutalw_check_limit', array( $this, 'check_spin_limit_by_ip' ) );
        add_action( 'wp_ajax_nopriv_zutalw_check_limit', array( $this, 'check_spin_limit_by_ip' ) );
    }

    public function enqueue_public_assets() {
        // 1. Always load CSS
        wp_enqueue_style( 'zutalw-style', ZUTALW_ASSETS_URL . 'css/rotate_style.css', array(), ZUTALW_VERSION );
        
        // 2. Load Admin Setup (Optional UI helpers)
        wp_enqueue_script( 'zutalw-admin-setup', ZUTALW_ASSETS_URL . 'js/admin-setup.js', array( 'jquery' ), ZUTALW_VERSION, true );

        // Helper string for versioning
        $ver = '?ver=' . ZUTALW_VERSION;

        // 4. List of heavy library files
        $scripts = array(
            'p5'          => ZUTALW_ASSETS_URL . 'js/p5.min.js' . $ver,
            'p5_dom'      => ZUTALW_ASSETS_URL . 'js/p5.dom.min.js' . $ver,
            'p5_sound'    => ZUTALW_ASSETS_URL . 'js/p5.sound.min.js' . $ver,
            'matter'      => ZUTALW_ASSETS_URL . 'js/matter.js' . $ver,
            'decomp'      => ZUTALW_ASSETS_URL . 'js/decomp.js' . $ver,
            'pathseg'     => ZUTALW_ASSETS_URL . 'js/pathseg.js' . $ver,
            'arcshape'    => ZUTALW_ASSETS_URL . 'js/arcshape.js' . $ver,
            'particle'    => ZUTALW_ASSETS_URL . 'js/particle.js' . $ver,
            'boundary'    => ZUTALW_ASSETS_URL . 'js/boundary.js' . $ver,
            'fingerprint' => ZUTALW_ASSETS_URL . 'js/fingerprint.min.js'. $ver,
            'sketch'      => ZUTALW_ASSETS_URL . 'js/sketch.js' . $ver,
            'custom'      => ZUTALW_ASSETS_URL . 'js/custom_rotate.js' . $ver,
        );

        // Get precise campaign for this specific page
        $active_campaign = $this->get_current_page_campaign();
        $target_campaign_id = $active_campaign ? $active_campaign['id'] : 0;
        
        // LẤY CỜ TRADE-IN TỪ DATABASE VÀ ÉP KIỂU INT
        $tradein_enabled = $active_campaign ? intval($active_campaign['tradein_enabled']) : 0;

        // 3. Prepare configuration data
        global $wpdb;
        $config_json = '';
        
        // 🔥 LOG DEBUG MẠNH MẼ ĐỂ KIỂM TRA TRẠNG THÁI BẬT/TẮT TRADE-IN
        $php_debug_log = array( 
            'status'          => 'started', 
            'campaign_id'     => $target_campaign_id,
            'tradein_enabled' => $tradein_enabled // CHÈN LOG VÀO ĐÂY
        );

        if ( $target_campaign_id > 0 ) {
            $table_campaigns = $wpdb->prefix . 'zutalw_campaigns';
            $table_segments  = $wpdb->prefix . 'zutalw_segments';
            
            $has_pool_col = $wpdb->get_results( "SHOW COLUMNS FROM `{$table_segments}` LIKE 'pool_level'" );
            $php_debug_log['has_pool_column'] = !empty($has_pool_col);
            
            if ( !empty($has_pool_col) ) {
                // 🔥 NẾU BẬT TRADE-IN THÌ ÉP MẶC ĐỊNH LẤY POOL 2 TỪ BACKEND
                $initial_pool = ($tradein_enabled === 1) ? 2 : 1;
                
                $segments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table_segments} WHERE campaign_id = %d AND pool_level = %d ORDER BY sort_order ASC", $target_campaign_id, $initial_pool ), ARRAY_A );
                $php_debug_log['query_type'] = 'Filtered by Pool Level ' . $initial_pool;
            } else {
                $segments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table_segments} WHERE campaign_id = %d ORDER BY sort_order ASC", $target_campaign_id ), ARRAY_A );
                $php_debug_log['query_type'] = 'Fallback: Loaded ALL (Column missing)';
            }
            
            $php_debug_log['total_found'] = is_array($segments) ? count($segments) : 0;
            $php_debug_log['prizes_loaded'] = array();
            
            $config_array = array(
                array( 'game_mode' => 'weighted' ) 
            );
            
            if ( $segments ) {
                foreach ( $segments as $seg ) {
                    // Ghi nhận chi tiết từng giải thưởng đang được load
                    $php_debug_log['prizes_loaded'][] = array(
                        'id'   => $seg['id'],
                        'name' => $seg['label'],
                        'pool' => isset($seg['pool_level']) ? $seg['pool_level'] : 'none'
                    );

                    $config_array[] = array(
                        'id'          => $seg['id'],
                        'label'       => $seg['label'],
                        'bg_color'    => $seg['bg_color'],
                        'text_color'  => $seg['text_color'], 
                        'image_url'   => isset($seg['image_url']) ? $seg['image_url'] : '',
                        'probability' => $seg['weight']
                    );
                }
                $config_json = wp_json_encode( $config_array );
            }
        } else {
            $php_debug_log['error'] = 'Campaign ID is 0 or not found on this page.';
        }

        // Bắn mảng Debug thẳng ra F12 Console của trình duyệt
        wp_add_inline_script( 'jquery', 'console.log("🔥 ZUTALW PHP DEBUG LOG:", ' . wp_json_encode($php_debug_log) . ');' );

        // 5. Config Data
        $localize_data = array(
            'ajax_url'           => admin_url( 'admin-ajax.php' ),
            'home_url'           => home_url(),
            'assets_url'         => ZUTALW_ASSETS_URL, 
            'plugin_url'         => ZUTALW_URL,
            'mode_admin'         => 'false',
            'getConfig'          => $config_json, 
            'nonce'              => wp_create_nonce( 'zutalw-nonce' ), 
            'popup_delay'        => (int)get_option( 'zutalw_popup_delay', 0 ) * 1000, 
            'max_spins'          => get_option( 'zutalw_max_spins', 1 ),
            'target_campaign_id' => $target_campaign_id,
            'tradein_enabled'    => $tradein_enabled, // 🔥 BƠM CỜ TRADE-IN RA JS QUA ZutalwConfig
            'recaptcha_site_key' => get_option( 'zutalw_recaptcha_site_key', '' ),
            'i18n'               => array(
                'notice_title' => esc_html__( 'Notification', 'zuta-lucky-wheel' ),
                'err_name'     => esc_html__( 'Please enter your full name', 'zuta-lucky-wheel' ),
                'err_phone'    => esc_html__( 'Please enter your phone number', 'zuta-lucky-wheel' ),
                'success'      => esc_html__( 'Congratulations! Information sent successfully!', 'zuta-lucky-wheel' ),
                'error'        => esc_html__( 'Error sending information. Please try again!', 'zuta-lucky-wheel' ),
                'notice'       => esc_html__( 'Notification', 'zuta-lucky-wheel' ), 
                'close'        => esc_html__( 'Close', 'zuta-lucky-wheel' )
            )
        );

        // 6. Enqueue Trigger file
        wp_enqueue_script( 'zutalw-trigger', ZUTALW_ASSETS_URL . 'js/zutalw-trigger.js', array( 'jquery' ), ZUTALW_VERSION, true );
        
        // 7. PASS DATA TO TRIGGER
        wp_localize_script( 'zutalw-trigger', 'ZutalwConfig', $localize_data );

        // 8. Pass script list separately
        wp_localize_script( 'zutalw-trigger', 'zutalw_Lazy_Assets', array(
            'scripts' => $scripts
        ));
        
        if ( ! empty( $localize_data['recaptcha_site_key'] ) ) {
            wp_enqueue_script( 
                'google-recaptcha', 
                'https://www.google.com/recaptcha/api.js?render=' . esc_attr( $localize_data['recaptcha_site_key'] ), 
                array(), 
                ZUTALW_VERSION, 
                true 
            );
        }
    }

    public function auto_display_wheel() {
       if ( is_admin() || current_user_can( 'manage_options' ) ) return;

        $active_campaign = $this->get_current_page_campaign();
        
        // --- GIÁ TRỊ MẶC ĐỊNH ---
        $gift_url          = ZUTALW_ASSETS_URL . 'images/gift1.png';
        $trigger_title     = __( 'CONGRATULATIONS!', 'zuta-lucky-wheel' );
        $trigger_shorttext = __( 'You have won a free spin!', 'zuta-lucky-wheel' );
        $trigger_desc      = __( 'FREE SPINS', 'zuta-lucky-wheel' );
        $trigger_btn       = __( 'SPIN NOW', 'zuta-lucky-wheel' );
        $game_title        = 'Zuta Lucky Wheel';
        $camp_id           = 0;

        // --- LẤY DỮ LIỆU TỪ DB ---
        if ( $active_campaign ) {
            $camp_id  = $active_campaign['id'];
            $settings = $active_campaign['settings'];

            if ( ! empty( $settings['display']['game_title'] ) ) {
                $game_title = $settings['display']['game_title'];
            }

            if ( ! empty( $settings['design'] ) ) {
                $d = $settings['design'];
                $gift_url          = ! empty( $d['trigger_img'] )       ? $d['trigger_img']       : $gift_url;
                $trigger_title     = ! empty( $d['trigger_title'] )     ? $d['trigger_title']     : $trigger_title;
                $trigger_shorttext = ! empty( $d['trigger_shorttext'] ) ? $d['trigger_shorttext'] : $trigger_shorttext;
                $trigger_desc      = ! empty( $d['trigger_desc'] )      ? $d['trigger_desc']      : $trigger_desc;
                $trigger_btn       = ! empty( $d['trigger_btn'] )       ? $d['trigger_btn']       : $trigger_btn;
            }
        }
        
        // 1. Gift Trigger UI (HIỂN THỊ SHORTTEXT)
        echo '<div id="zutalw-gift-trigger" class="zutalw-gift-overlay" style="display:none;">
            <div class="zutalw-gift-card">
                <div class="zutalw-card-close">&#10005;</div>
                <div class="zutalw-card-img-wrapper">
                    <img src="' . esc_url( $gift_url ) . '" class="zutalw-card-img">
                </div>
                <h3 class="zutalw-card-title">' . esc_html( $trigger_title ) . '</h3>
                <div class="zutalw-card-desc">
                    ' . ( !empty($trigger_shorttext) ? '<p class="zutalw-short-desc">' . nl2br(esc_html($trigger_shorttext)) . '</p>' : '' ) . '
                    <span class="highlight">
                        <span id="zutalw-spins-left">0</span> ' . esc_html( $trigger_desc ) . '
                    </span>
                </div>
                <a href="#zutalw_lucky_spin_current" class="zutalw-card-btn">' . esc_html( $trigger_btn ) . '</a>
            </div>
        </div>';

        // 2. Main Game Canvas UI
        echo '<div id="zutalw-popup-wrapper" style="display:none;">
                <div class="zutalw-game-card">
                    <div class="zutalw-close-game">&#10005;</div>
                    <h3 class="zutalw-game-title">' . esc_html( $game_title ) . '</h3>
                    <div class="zutalw-wheel-pointer"></div>
                    <div id="area-game" data-id="' . esc_attr( $camp_id ) . '" data-license="0"></div>
                </div>
            </div>';
        
        // 4. Fireworks & Congratulations UI
        echo '
        <div id="zutalw-congrats-overlay" style="display:none;">
            <canvas id="zutalw-fireworks-canvas"></canvas>
            <div class="zutalw-congrats-box">
                <div class="zutalw-congrats-close">&#10005;</div>
                <h2 class="congrats-title">' . esc_html__( 'Congratulations on your gift!', 'zuta-lucky-wheel' ) . '</h2>
                <p class="congrats-gift" id="zutalw-won-gift-name"></p>
                
                <div class="zutalw-action-buttons" style="display: flex; gap: 10px; justify-content: center; margin-top: 15px;">
                    <button id="zutalw-btn-claim-gift" style="background: #4CAF50; color: #fff; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">' . esc_html__( 'Claim Gift', 'zuta-lucky-wheel' ) . '</button>
                    
                    <button id="zutalw-btn-trade-in" style="background: #FF9800; color: #fff; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">' . esc_html__( 'Trade-in for Extra Spin', 'zuta-lucky-wheel' ) . '</button>
                </div>
            </div>
        </div>';
    }

    public function loading_markup() {
        echo '<div id="zutalw-loading" class="zutalw-popup-processing" style="display:none;position:fixed;z-index:9999999;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,0.6);"><div class="processing" style="position:relative;background:#fff;border-radius:10px;width:200px;height:200px;margin:20% auto;text-align:center;"><img class="loading" src="' . esc_url( ZUTALW_ASSETS_URL . 'images/spinner.gif' ) . '" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:80px;height:80px;"></div></div>';
    }

    public function popup_notify_markup() {
        echo '<div id="zutalw-popup-notify" class="zutalw-popup-notify" style="display:none;"></div>';
    }

    public function check_spin_limit_by_ip() {
        check_ajax_referer( 'zutalw-nonce', 'security' );
        $device_id   = isset($_POST['device_id']) ? sanitize_text_field( $_POST['device_id'] ) : '';
        $campaign_id = isset($_POST['idcampain']) ? intval( $_POST['idcampain'] ) : 0;

        if ( empty($device_id) || $campaign_id <= 0 ) {
            wp_send_json_error( array( 'message' => 'Invalid data' ) );
        }

        global $wpdb;
        $table_limits    = $wpdb->prefix . 'zutalw_spin_limits';
        $table_campaigns = $wpdb->prefix . 'zutalw_campaigns';

        // 1. Check if this device has visited this campaign before
        $row = $wpdb->get_row( $wpdb->prepare( 
            "SELECT spins_left FROM $table_limits WHERE device_id = %s AND campaign_id = %d LIMIT 1", 
            $device_id, $campaign_id 
        ) );

        if ( ! $row ) {
            // First time visiting -> Get default spins from campaign settings
            $limit = 1;
            $campaign = $wpdb->get_row( $wpdb->prepare( "SELECT settings FROM $table_campaigns WHERE id = %d", $campaign_id ) );
            if ( $campaign && !empty($campaign->settings) ) {
                $settings = json_decode($campaign->settings, true);
                $limit = isset($settings['display']['max_spins']) ? intval($settings['display']['max_spins']) : 1;
            }

            // Log the device to start tracking limits
            $wpdb->insert(
                $table_limits,
                array(
                    'campaign_id' => $campaign_id,
                    'device_id'   => $device_id,
                    'spins_total' => $limit,
                    'spins_used'  => 0,
                    'spins_left'  => $limit
                ),
                array( '%d', '%s', '%d', '%d', '%d' )
            );
            wp_send_json_success( array( 'spins_left' => $limit ) );
        } else {
            // Visited before -> Return remaining spins
            wp_send_json_success( array( 'spins_left' => (int)$row->spins_left ) );
        }
    }

    private function get_current_page_campaign() {
        global $wpdb;
        $table = $wpdb->prefix . 'zutalw_campaigns';
        
        if ( $wpdb->get_var( "SHOW TABLES LIKE '$table'" ) != $table ) {
            return null;
        }

        // 🔥 FIX: Lấy TOÀN BỘ cột bằng "SELECT *" thay vì chỉ lấy "id, settings"
        $campaigns = $wpdb->get_results( "SELECT * FROM $table WHERE status = 'active' ORDER BY id DESC" );
        
        $current_page_id = get_queried_object_id();
        $is_homepage     = is_front_page() || is_home(); 
        
        $matched_campaigns = array(); 
        $global_campaigns  = array(); 

        foreach ( $campaigns as $camp ) {
            $settings = json_decode( $camp->settings, true );
            $target_page = isset( $settings['display']['target_page'] ) ? intval( $settings['display']['target_page'] ) : 0;
            $tradein_enabled = isset( $camp->tradein_enabled ) ? intval( $camp->tradein_enabled ) : 0; // LẤY CỜ TỪ KẾT QUẢ SQL
            
            if ( ($target_page === -1 && $is_homepage) || ($target_page > 0 && $target_page === $current_page_id) ) {
                $matched_campaigns[] = array( 'id' => $camp->id, 'settings' => $settings, 'tradein_enabled' => $tradein_enabled );
            }
            
            if ( $target_page === 0 ) {
                $global_campaigns[] = array( 'id' => $camp->id, 'settings' => $settings, 'tradein_enabled' => $tradein_enabled );
            }
        }

        $display_mode = get_option( 'zutalw_multiple_campaigns_mode', 'latest' );

        if ( count( $matched_campaigns ) > 0 ) {
            if ( $display_mode === 'random' ) {
                $random_index = array_rand( $matched_campaigns );
                return $matched_campaigns[ $random_index ];
            }
            return $matched_campaigns[0];
        }

        if ( count( $global_campaigns ) > 0 ) {
            if ( $display_mode === 'random' ) {
                $random_index = array_rand( $global_campaigns );
                return $global_campaigns[ $random_index ];
            }
            return $global_campaigns[0];
        }

        return null;
    }
}