<?php
/**
 * Zutalw Admin Campaigns Manager
 * Handles the creation, listing, segment building, leads management, and Anti-Fraud logging.
 */

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

class ZUTALW_Admin_Campaigns {

    private $table_campaigns;
    private $table_segments;
    private $table_prize_logs; 
    private $table_spin_limits; 

    public function __construct() {
        global $wpdb;
        $this->table_campaigns   = $wpdb->prefix . 'zutalw_campaigns';
        $this->table_segments    = $wpdb->prefix . 'zutalw_segments';
        $this->table_prize_logs  = $wpdb->prefix . 'zutalw_prize_logs'; 
        $this->table_spin_limits = $wpdb->prefix . 'zutalw_spin_limits'; 
        
    }

	public function render() {
        wp_enqueue_script( 'jquery-ui-sortable' );
        wp_enqueue_media();

        $action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : 'list';
        $id     = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0;

        $saved_id = $this->handle_submission();
        
        if ( $saved_id > 0 && $action === 'add' ) {
            // WordPress admin headers are already sent, so PHP redirect will fail. 
            // We use JavaScript to safely redirect to the list page.
            $list_url = admin_url( 'admin.php?page=lucky-wheel-settings&tab=campaigns' );
            echo '<script type="text/javascript">
                window.location.replace("' . esc_url_raw( $list_url ) . '");
            </script>';
            exit;
        }

        if ( $action === 'edit' || $action === 'add' ) {
            $this->render_form( $id );
        } else {
            $this->render_list();
        }
    }

    private function handle_submission() {
        if ( isset( $_POST['zutalw_save_campaign'] ) && check_admin_referer( 'zutalw_campaign_nonce' ) ) {
            global $wpdb;

            $id              = isset( $_POST['campaign_id'] ) ? intval( $_POST['campaign_id'] ) : 0;
            $name            = isset( $_POST['campaign_name'] ) ? sanitize_text_field( wp_unslash( $_POST['campaign_name'] ) ) : '';
            $status          = isset( $_POST['campaign_status'] ) ? sanitize_text_field( wp_unslash( $_POST['campaign_status'] ) ) : 'active';
            $tradein_enabled = isset( $_POST['tradein_enabled'] ) ? 1 : 0;
            
            $start_date      = !empty( $_POST['start_date'] ) ? sanitize_text_field( wp_unslash( $_POST['start_date'] ) ) : null;
            $end_date        = !empty( $_POST['end_date'] ) ? sanitize_text_field( wp_unslash( $_POST['end_date'] ) ) : null;
            
            $settings_array  = isset( $_POST['settings'] ) ? (array) wp_unslash( $_POST['settings'] ) : array();
            $settings_json   = json_encode( $settings_array );

            if ( empty( $name ) ) {
                echo '<div class="notice notice-error"><p>' . esc_html__( 'Campaign Name is required.', 'zuta-lucky-wheel' ) . '</p></div>';
                return 0;
            }

            $campaign_data = array(
                'name'            => $name,
                'status'          => $status,
                'tradein_enabled' => $tradein_enabled,
                'start_date'      => $start_date,
                'end_date'        => $end_date,
                'settings'        => $settings_json,
            );
            
            $format = array( '%s', '%s', '%d', '%s', '%s', '%s' );
            $campaign_id = $id;

            if ( $id > 0 ) {
                $wpdb->update( $this->table_campaigns, $campaign_data, array( 'id' => $id ), $format, array( '%d' ) );
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Campaign updated successfully.', 'zuta-lucky-wheel' ) . '</p></div>';
            } else {
                $wpdb->insert( $this->table_campaigns, $campaign_data, $format );
                $campaign_id = $wpdb->insert_id;
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Campaign created successfully.', 'zuta-lucky-wheel' ) . '</p></div>';
            }

            if ( $campaign_id > 0 && isset( $_POST['segments'] ) && is_array( $_POST['segments'] ) ) {
                $submitted_segments = wp_unslash( $_POST['segments'] );
                $submitted_ids = array();

                foreach ( $submitted_segments as $key => $seg ) {
                    if ( $key === '{{INDEX}}' ) continue;

                    $seg_id     = isset( $seg['id'] ) ? intval( $seg['id'] ) : 0;
                    $seg_data   = array(
                        'campaign_id'    => $campaign_id,
                        'label'          => isset( $seg['label'] ) ? sanitize_text_field( $seg['label'] ) : '',
                        'bg_color'       => isset( $seg['bg_color'] ) ? sanitize_hex_color( $seg['bg_color'] ) : '#ffffff',
                        'text_color'     => isset( $seg['text_color'] ) ? sanitize_hex_color( $seg['text_color'] ) : '#000000',
                        'weight'         => isset( $seg['weight'] ) ? intval( $seg['weight'] ) : 1,
                        'quantity_total' => isset( $seg['quantity_total'] ) ? intval( $seg['quantity_total'] ) : -1,
                        'pool_type'      => isset( $seg['pool_type'] ) ? sanitize_text_field( $seg['pool_type'] ) : 'basic',
                        'pool_level'     => isset( $seg['pool_level'] ) ? intval( $seg['pool_level'] ) : 1,
                        'sort_order'     => isset( $seg['sort_order'] ) ? intval( $seg['sort_order'] ) : 0,
                        'image_url'      => isset( $seg['image_url'] ) ? sanitize_url( $seg['image_url'] ) : '',
                    );

                    if ( $seg_id > 0 ) {
                        // Update existing segment
                        // Formats: campaign_id(%d), label(%s), bg_color(%s), text_color(%s), weight(%d), quantity_total(%d), pool_type(%s), pool_level(%d), sort_order(%d), image_url(%s)
                        $wpdb->update( 
                            $this->table_segments, 
                            $seg_data, 
                            array( 'id' => $seg_id ), 
                            array( '%d', '%s', '%s', '%s', '%d', '%d', '%s', '%d', '%d', '%s' ), 
                            array( '%d' ) 
                        );
                        $submitted_ids[] = $seg_id;
                    } else {
                        // Insert new segment
                        // Formats: campaign_id(%d), label(%s), bg_color(%s), text_color(%s), weight(%d), quantity_total(%d), pool_type(%s), pool_level(%d), sort_order(%d), image_url(%s), quantity_remaining(%d)
                        $seg_data['quantity_remaining'] = $seg_data['quantity_total'];
                        $wpdb->insert( 
                            $this->table_segments, 
                            $seg_data, 
                            array( '%d', '%s', '%s', '%s', '%d', '%d', '%s', '%d', '%d', '%s', '%d' ) 
                        );
                        $submitted_ids[] = $wpdb->insert_id;
                    }
                }

                if ( ! empty( $submitted_ids ) ) {
                    $ids_placeholder = implode( ',', array_fill( 0, count( $submitted_ids ), '%d' ) );
                    $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table_segments} WHERE campaign_id = %d AND id NOT IN ($ids_placeholder)", array_merge( array( $campaign_id ), $submitted_ids ) ) );
                }
            } else if ( $campaign_id > 0 && !isset( $_POST['segments'] ) && $id > 0 ) {
                 $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table_segments} WHERE campaign_id = %d", $campaign_id ) );
            }

            return $campaign_id;
        }
        return 0;
    }

    private function render_list() {
        global $wpdb;
        $campaigns = $wpdb->get_results( "SELECT * FROM {$this->table_campaigns} ORDER BY id DESC" );
        $add_url = admin_url( 'admin.php?page=lucky-wheel-settings&tab=campaigns&action=add' );
        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e( 'Campaigns Manager', 'zuta-lucky-wheel' ); ?></h1>
            <a href="<?php echo esc_url( $add_url ); ?>" class="page-title-action"><?php esc_html_e( 'Create New', 'zuta-lucky-wheel' ); ?></a>
            <hr class="wp-header-end">
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width: 50px;">ID</th>
                        <th><?php esc_html_e( 'Name', 'zuta-lucky-wheel' ); ?></th>
                        <th><?php esc_html_e( 'Shortcode', 'zuta-lucky-wheel' ); ?></th>
                        <th><?php esc_html_e( 'Status', 'zuta-lucky-wheel' ); ?></th>
                        <th><?php esc_html_e( 'Created At', 'zuta-lucky-wheel' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ( $campaigns ) : foreach ( $campaigns as $campaign ) : 
                        $edit_url = admin_url( 'admin.php?page=lucky-wheel-settings&tab=campaigns&action=edit&id=' . $campaign->id );
                    ?>
                        <tr>
                            <td><?php echo esc_html( $campaign->id ); ?></td>
                            <td><strong><a href="<?php echo esc_url($edit_url); ?>"><?php echo esc_html($campaign->name); ?></a></strong></td>
                            <td><code>[zutalw_lucky_spin id="<?php echo $campaign->id; ?>"]</code></td>
                            <td><?php echo ucfirst($campaign->status); ?></td>
                            <td><?php echo esc_html($campaign->created_at); ?></td>
                        </tr>
                    <?php endforeach; else : ?>
                        <tr><td colspan="5"><?php esc_html_e( 'No campaigns found.', 'zuta-lucky-wheel' ); ?></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }

   private function render_form( $id = 0 ) {
        global $wpdb;
        $is_edit = ( $id > 0 );
        $campaign = null;
        $segments = array();
        $leads    = array();
        $fraud_logs = array();

        if ( $is_edit ) {
            $campaign = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$this->table_campaigns} WHERE id = %d", $id ) );
            $segments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->table_segments} WHERE campaign_id = %d ORDER BY sort_order ASC, id ASC", $id ), ARRAY_A );
            
            if ( $wpdb->get_var("SHOW TABLES LIKE '{$this->table_prize_logs}'") == $this->table_prize_logs ) {
                $leads = $wpdb->get_results( $wpdb->prepare( "
                    SELECT * FROM {$this->table_prize_logs} 
                    WHERE campaign_id = %d ORDER BY id DESC LIMIT 1
                ", $id ) );
            }

            if ( $wpdb->get_var("SHOW TABLES LIKE '{$this->table_spin_limits}'") == $this->table_spin_limits ) {
                $fraud_logs = $wpdb->get_results( $wpdb->prepare( "
                    SELECT * FROM {$this->table_spin_limits} 
                    WHERE campaign_id = %d ORDER BY updated_at DESC LIMIT 1
                ", $id ) );
            }
        }

        $name            = isset($campaign->name) ? $campaign->name : '';
        $status          = isset($campaign->status) ? $campaign->status : 'active';
        $tradein_enabled = isset($campaign->tradein_enabled) ? $campaign->tradein_enabled : 0;
        $start_date      = isset($campaign->start_date) && $campaign->start_date ? date( 'Y-m-d\TH:i', strtotime( $campaign->start_date ) ) : '';
        $end_date        = isset($campaign->end_date) && $campaign->end_date ? date( 'Y-m-d\TH:i', strtotime( $campaign->end_date ) ) : '';
        $back_url        = admin_url( 'admin.php?page=lucky-wheel-settings&tab=campaigns' );
        
        $raw_json = isset($campaign->settings) ? $campaign->settings : '';
        $raw_settings = (!empty($raw_json)) ? json_decode($raw_json, true) : array();
        if ( ! is_array( $raw_settings ) ) { $raw_settings = array(); }

        $raw_design = (isset($raw_settings['design']) && is_array($raw_settings['design'])) ? $raw_settings['design'] : array();
        $design = wp_parse_args( $raw_design, array(
            'wheel_size'   => 500,
            'border_color' => '#333333',
            'center_logo'  => '',
            'trigger_img'   => ZUTALW_ASSETS_URL . 'images/gift1.png',
            'trigger_title' => __( 'CONGRATULATIONS!', 'zuta-lucky-wheel' ),
            'trigger_shorttext' => '',
            'trigger_desc'  => __( 'FREE SPINS', 'zuta-lucky-wheel' ),
            'trigger_btn'   => __( 'SPIN NOW', 'zuta-lucky-wheel' )
        ));

        $raw_display = (isset($raw_settings['display']) && is_array($raw_settings['display'])) ? $raw_settings['display'] : array();
        $display = wp_parse_args( $raw_display, array(
            'game_title'  => 'Zuta Lucky Wheel',
            'popup_delay' => 0,
            'max_spins'   => 1,
            'reset_days'  => 1
        ));

        ?>
        <div class="wrap">
            <h1><?php echo $is_edit ? esc_html__( 'Edit Campaign', 'zuta-lucky-wheel' ) : esc_html__( 'Add New Campaign', 'zuta-lucky-wheel' ); ?></h1>
            <a href="<?php echo esc_url($back_url); ?>" class="page-title-action"><?php esc_html_e( 'Back to List', 'zuta-lucky-wheel' ); ?></a>
            <hr class="wp-header-end">

            <h2 class="nav-tab-wrapper zutalw-sub-tabs" style="margin: 20px 0;">
                <a href="#tab-general" class="nav-tab nav-tab-active"><?php esc_html_e( '1. General & Slices', 'zuta-lucky-wheel' ); ?></a>
                <a href="#tab-design" class="nav-tab"><?php esc_html_e( '2. Design', 'zuta-lucky-wheel' ); ?></a>
                <a href="#tab-display" class="nav-tab"><?php esc_html_e( '3. Display & Logic', 'zuta-lucky-wheel' ); ?></a>
                <?php if ( $is_edit ) : ?>
                    <a href="#tab-leads" class="nav-tab"><?php esc_html_e( '4. All Leads', 'zuta-lucky-wheel' ); ?></a>
                    <a href="#tab-unique-leads" class="nav-tab" style="color: #00a32a;"><?php esc_html_e( '5. Unique Winners', 'zuta-lucky-wheel' ); ?></a>
                    
                    <a href="#tab-fraud" class="nav-tab"><?php esc_html_e( '6. Anti-Fraud Logs', 'zuta-lucky-wheel' ); ?></a>
                <?php endif; ?>
            </h2>

            <form method="post" action="">
                <?php wp_nonce_field( 'zutalw_campaign_nonce' ); ?>
                <input type="hidden" name="campaign_id" value="<?php echo esc_attr( $id ); ?>">

                <div id="tab-general" class="zutalw-tab-content">
                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div class="zutalw-narrow-sidebar" style="flex: 0 0 250px; background: #fff; padding: 20px; border: 1px solid #ccd0d4;">
                            <h3><?php esc_html_e( 'General Settings', 'zuta-lucky-wheel' ); ?></h3>
                            <table class="form-table">
                                <tr><th><?php esc_html_e( 'Name *', 'zuta-lucky-wheel' ); ?></th><td><input type="text" name="campaign_name" value="<?php echo esc_attr($name); ?>" required></td></tr>
                                <tr><th><?php esc_html_e( 'Status', 'zuta-lucky-wheel' ); ?></th><td>
                                    <select name="campaign_status">
                                        <option value="active" <?php selected($status, 'active'); ?>><?php esc_html_e( 'Active', 'zuta-lucky-wheel' ); ?></option>
                                        <option value="draft" <?php selected($status, 'draft'); ?>><?php esc_html_e( 'Draft', 'zuta-lucky-wheel' ); ?></option>
                                    </select>
                                </td></tr>
                               <tr>
    <th><?php esc_html_e( 'Form Submission Flow', 'zuta-lucky-wheel' ); ?></th>
    <td>
        <label>
            <input type="checkbox" name="tradein_enabled" value="1" <?php checked($tradein_enabled, 1); ?>> 
            <strong><?php esc_html_e( 'Require user details before spinning', 'zuta-lucky-wheel' ); ?></strong>
        </label>
        <p class="description" style="margin-top: 8px;">
            <?php esc_html_e( 'If checked: Users must submit the form upfront to verify their spin eligibility and limits. This effectively prevents fraud (e.g., spinning anonymously multiple times and only claiming the highest-value prize).', 'zuta-lucky-wheel' ); ?>
            <br>
            <?php esc_html_e( 'If unchecked: Users can spin first and fill out the form later to claim their prize.', 'zuta-lucky-wheel' ); ?>
        </p>
    </td>
</tr>
                                <tr><th><?php esc_html_e( 'Start Date', 'zuta-lucky-wheel' ); ?></th><td><input type="datetime-local" name="start_date" value="<?php echo esc_attr($start_date); ?>"></td></tr>
                                <tr><th><?php esc_html_e( 'End Date', 'zuta-lucky-wheel' ); ?></th><td><input type="datetime-local" name="end_date" value="<?php echo esc_attr($end_date); ?>"></td></tr>
                            </table>
                        </div>

                        <div style="flex: 1; min-width: 700px; background: #fff; padding: 20px; border: 1px solid #ccd0d4;">
                            <h3><?php esc_html_e( 'Wheel Segments Builder', 'zuta-lucky-wheel' ); ?> 
                                <button type="button" class="button button-primary" id="zutalw-add-segment" style="float:right;"><?php esc_html_e( 'Add Segment', 'zuta-lucky-wheel' ); ?></button>
                            </h3>
                            <table class="wp-list-table widefat striped">
                                <thead>
                                    <tr>
                                        <th width="30"></th>
                                        <th width="80"><?php esc_html_e( 'Icon', 'zuta-lucky-wheel' ); ?></th>
                                        <th><?php esc_html_e( 'Label', 'zuta-lucky-wheel' ); ?></th>
                                        <th width="100"><?php esc_html_e( 'BG Color', 'zuta-lucky-wheel' ); ?></th>
                                        <th width="100"><?php esc_html_e( 'Text Color', 'zuta-lucky-wheel' ); ?></th>
                                        <th width="80"><?php esc_html_e( 'Weight', 'zuta-lucky-wheel' ); ?></th>
                                        <th width="80"><?php esc_html_e( 'Qty', 'zuta-lucky-wheel' ); ?></th>
                                        <th width="100"><?php esc_html_e( 'Pool', 'zuta-lucky-wheel' ); ?></th>
                                        <th width="40"></th>
                                    </tr>
                                </thead>
                                <tbody id="zutalw-segments-wrapper">
                                    <?php 
                                        $idx = 0;
                                        if ($segments) {
                                            foreach($segments as $seg) { $this->render_segment_row($idx++, $seg); }
                                        } else {
                                            $this->render_segment_row(0, array('label'=>'Gift 1', 'bg_color'=>'#e74c3c', 'text_color'=>'#ffffff', 'weight'=>1, 'quantity_total'=>-1));
                                        }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div id="tab-design" class="zutalw-tab-content" style="display:none;">
                    <div style="background: #fff; padding: 20px; border: 1px solid #ccd0d4;">
                        <h3><?php esc_html_e( 'Wheel Design Customization', 'zuta-lucky-wheel' ); ?></h3>
                        <table class="form-table">
                            <tr style="border-top: 1px solid #eee;"><td colspan="2"><h4><?php esc_html_e( 'Trigger Popup Settings (Initial Notification)', 'zuta-lucky-wheel' ); ?></h4></td></tr>
                            
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Trigger Image', 'zuta-lucky-wheel' ); ?></th>
                                <td>
                                    <input type="text" name="settings[design][trigger_img]" class="zutalw-image-url regular-text" value="<?php echo esc_attr( $design['trigger_img'] ); ?>">
                                    <button type="button" class="button zutalw-upload-img-btn"><?php esc_html_e( 'Select Image', 'zuta-lucky-wheel' ); ?></button>
                                    <p class="description"><?php esc_html_e( 'Featured image shown in the initial popup.', 'zuta-lucky-wheel' ); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Trigger Title', 'zuta-lucky-wheel' ); ?></th>
                                <td><input type="text" name="settings[design][trigger_title]" value="<?php echo esc_attr( $design['trigger_title'] ); ?>" class="regular-text"></td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Trigger Description (Short)', 'zuta-lucky-wheel' ); ?></th>
                                <td>
                                    <textarea name="settings[design][trigger_shorttext]" rows="3" class="large-text"><?php echo esc_textarea( $design['trigger_shorttext'] ); ?></textarea>
                                    <p class="description"><?php esc_html_e( 'Additional text to explain the notification.', 'zuta-lucky-wheel' ); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Trigger Sub-label', 'zuta-lucky-wheel' ); ?></th>
                                <td>
                                    <input type="text" name="settings[design][trigger_desc]" value="<?php echo esc_attr( $design['trigger_desc'] ); ?>" class="regular-text">
                                    <p class="description"><?php esc_html_e( 'Text shown next to the spin count (e.g., FREE SPINS).', 'zuta-lucky-wheel' ); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Trigger Button Text', 'zuta-lucky-wheel' ); ?></th>
                                <td><input type="text" name="settings[design][trigger_btn]" value="<?php echo esc_attr( $design['trigger_btn'] ); ?>" class="regular-text"></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <div id="tab-display" class="zutalw-tab-content" style="display:none;">
                    <div style="background: #fff; padding: 20px; border: 1px solid #ccd0d4; max-width: 800px;">
                        <h3><?php esc_html_e( 'Display & Logic Conditions', 'zuta-lucky-wheel' ); ?></h3>
                        <table class="form-table">
                            <tr valign="top">
                                <th scope="row"><label for="zutalw_game_title"><?php echo esc_html__( 'Game Popup Title', 'zuta-lucky-wheel' ); ?></label></th>
                                <td>
                                    <input type="text" id="zutalw_game_title" name="settings[display][game_title]" value="<?php echo esc_attr( $display['game_title'] ); ?>" class="regular-text" />
                                </td>
                            </tr>
                            <?php
                            $target_page_id = isset( $display['target_page'] ) ? intval( $display['target_page'] ) : 0;
                            $target_page_title = '';
                            
                            if ( $target_page_id === -1 ) {
                                $target_page_title = '[System] Homepage';
                            } elseif ( $target_page_id > 0 ) {
                                $p = get_post( $target_page_id );
                                if ( $p ) {
                                    $type_label = ( $p->post_type === 'page' ) ? 'Page' : 'Post';
                                    $target_page_title = '[' . $type_label . '] ' . $p->post_title . ' (ID: ' . $p->ID . ')';
                                }
                            }
                            ?>
                            <tr valign="top">
                                <th scope="row"><label for="zutalw_target_page_search"><?php echo esc_html__( 'Target Page / Post', 'zuta-lucky-wheel' ); ?></label></th>
                                <td>
                                    <div class="zutalw-ajax-search-wrap" style="position: relative; max-width: 400px;">
                                        <input type="text" id="zutalw_target_page_search" class="regular-text" style="width: 100%; box-sizing: border-box;" placeholder="Search by keyword..." value="<?php echo esc_attr( $target_page_title ); ?>" autocomplete="off">
                                        <input type="hidden" id="zutalw_target_page_id" name="settings[display][target_page]" value="<?php echo esc_attr( $target_page_id ); ?>">
                                        <div style="margin-top: 8px; font-size: 13px;">
                                            <a href="#" id="zutalw_set_homepage" style="color: #2271b1; text-decoration: none; margin-right: 15px; font-weight: 500;">🏠 Set as Homepage</a>
                                            <a href="#" id="zutalw_clear_page" style="color: #d63638; text-decoration: none;">&times; Clear (All Pages)</a>
                                        </div>
                                        <ul id="zutalw_search_results" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: #fff; border: 1px solid #ccd0d4; box-shadow: 0 4px 6px rgba(0,0,0,.1); z-index: 9999; margin: 0; padding: 0; max-height: 250px; overflow-y: auto; list-style: none;"></ul>
                                    </div>
                                </td>
                            </tr>
                            <tr valign="top">
                                <th scope="row"><label for="zutalw_popup_delay"><?php echo esc_html__( 'Popup Delay (seconds)', 'zuta-lucky-wheel' ); ?></label></th>
                                <td>
                                    <input type="number" id="zutalw_popup_delay" name="settings[display][popup_delay]" value="<?php echo esc_attr( $display['popup_delay'] ); ?>" class="regular-text" min="0" />
                                </td>
                            </tr>
                            <tr valign="top">
                                <th scope="row"><label for="zutalw_max_spins"><?php echo esc_html__( 'Max Spins per Device', 'zuta-lucky-wheel' ); ?></label></th>
                                <td>
                                    <input type="number" id="zutalw_max_spins" name="settings[display][max_spins]" value="<?php echo esc_attr( $display['max_spins'] ); ?>" class="regular-text" min="1" />
                                </td>
                            </tr>
                            <tr valign="top">
                                <th scope="row"><label for="zutalw_reset_days"><?php echo esc_html__( 'Reset Limit After (Days)', 'zuta-lucky-wheel' ); ?></label></th>
                                <td>
                                    <input type="number" id="zutalw_reset_days" name="settings[display][reset_days]" value="<?php echo esc_attr( $display['reset_days'] ); ?>" class="regular-text" min="1" />
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <p class="submit">
                    <?php submit_button( esc_html__( 'Save All Campaign Settings', 'zuta-lucky-wheel' ), 'primary', 'zutalw_save_campaign', false ); ?>
                </p>
            </form>

            <?php if ( $is_edit ) : ?>
            
            <div id="tab-leads" class="zutalw-tab-content" style="display:none;">
                <div style="background: #fff; padding: 20px; border: 1px solid #ccd0d4;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3 style="margin:0;"><?php esc_html_e( 'All Campaign Leads', 'zuta-lucky-wheel' ); ?></h3>
                            <p class="description"><?php esc_html_e( 'Contains all interactions (including duplicates from the same device).', 'zuta-lucky-wheel' ); ?></p>
                        </div>
                        <?php 
                            $export_link = add_query_arg( array(
                                'action'      => 'zutalw_export_campaign_leads',
                                'campaign_id' => $id,
                                '_wpnonce'    => wp_create_nonce( 'zutalw_export_campaign_nonce' )
                            ), admin_url( 'admin.php' ) ); 
                        ?>
                        <a href="<?php echo esc_url( $export_link ); ?>" class="button button-secondary"><?php esc_html_e( 'Export All (Raw)', 'zuta-lucky-wheel' ); ?></a>
                    </div>
                    
                    <table class="wp-list-table widefat fixed striped" style="margin-top: 15px;">
                        <thead>
                            <tr>
                                <th style="width: 60px;">ID</th>
                                <th><?php esc_html_e( 'Player Name', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Device ID', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Phone', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Email', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Prize Won', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Source URL', 'zuta-lucky-wheel' ); ?></th>
                                <th style="width: 150px;"><?php esc_html_e( 'Date', 'zuta-lucky-wheel' ); ?></th>
                            </tr>
                        </thead>
                        <tbody id="zutalw-leads-ajax-target"></tbody>
                    </table>
                </div>
            </div>

            <div id="tab-unique-leads" class="zutalw-tab-content" style="display:none;">
                <div style="background: #fff; padding: 20px; border: 1px solid #ccd0d4; border-left: 4px solid #00a32a;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3 style="margin:0; color: #00a32a;"><span class="dashicons dashicons-saved"></span> <?php esc_html_e( 'Unique Winners (Deduplicated)', 'zuta-lucky-wheel' ); ?></h3>
                            <p class="description"><?php esc_html_e( 'Automatically filters out duplicates by Phone, Email, or Device ID. Only the LATEST prize for each unique user is shown here.', 'zuta-lucky-wheel' ); ?></p>
                        </div>
                        <?php 
                            $export_unique_link = add_query_arg( array(
                                'action'      => 'zutalw_export_unique_leads',
                                'campaign_id' => $id,
                                '_wpnonce'    => wp_create_nonce( 'zutalw_export_campaign_nonce' )
                            ), admin_url( 'admin.php' ) ); 
                        ?>
                        <a href="<?php echo esc_url( $export_unique_link ); ?>" class="button button-primary"><?php esc_html_e( 'Export Unique Winners (.csv)', 'zuta-lucky-wheel' ); ?></a>
                    </div>
                    
                    <table class="wp-list-table widefat fixed striped" style="margin-top: 15px;">
                        <thead>
                            <tr>
                                <th style="width: 60px;">ID</th>
                                <th><?php esc_html_e( 'Player Name', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Device ID', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Phone', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Email', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Latest Prize', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Source URL', 'zuta-lucky-wheel' ); ?></th>
                                <th style="width: 150px;"><?php esc_html_e( 'Date', 'zuta-lucky-wheel' ); ?></th>
                            </tr>
                        </thead>
                        <tbody id="zutalw-unique-leads-ajax-target"></tbody>
                    </table>
                </div>
            </div>

            <div id="tab-fraud" class="zutalw-tab-content" style="display:none;">
                <div style="background: #fff; padding: 20px; border: 1px solid #ccd0d4; border-left: 4px solid #d63638;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3 style="margin:0; color:#d63638;"><span class="dashicons dashicons-shield"></span> <?php esc_html_e( 'Anti-Fraud & Device Limits', 'zuta-lucky-wheel' ); ?></h3>
                            <p class="description"><?php esc_html_e( 'Raw logs of every device that interacted with the wheel. Cross-reference "Device ID" with the Leads tab to spot cloning or spam.', 'zuta-lucky-wheel' ); ?></p>
                        </div>
                    </div>
                    <table class="wp-list-table widefat fixed striped" style="margin-top: 15px;">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Device ID (Fingerprint)', 'zuta-lucky-wheel' ); ?></th>
                                <th style="width: 120px; text-align: center;"><?php esc_html_e( 'Total Allowed', 'zuta-lucky-wheel' ); ?></th>
                                <th style="width: 120px; text-align: center;"><?php esc_html_e( 'Spins Used', 'zuta-lucky-wheel' ); ?></th>
                                <th style="width: 120px; text-align: center;"><?php esc_html_e( 'Spins Left', 'zuta-lucky-wheel' ); ?></th>
                                <th><?php esc_html_e( 'Last Active', 'zuta-lucky-wheel' ); ?></th>
                            </tr>
                        </thead>
                        <tbody id="zutalw-fraud-ajax-target"></tbody>
                    </table>
                </div>
            </div>

            <?php endif; ?>

            <table style="display:none;">
                <tbody id="zutalw-segment-template">
                    <?php $this->render_segment_row( '{{INDEX}}', array('label'=>'New Prize', 'bg_color'=>'#cccccc', 'text_color'=>'#000000', 'weight'=>1, 'quantity_total'=>-1) ); ?>
                </tbody>
            </table>
        </div>

        <script>
            jQuery(document).ready(function($) {

                // --- 1. HÀM XỬ LÝ AJAX PHÂN TRANG (ĐÃ CẬP NHẬT TAB MỚI) ---
                function loadAjaxTable(targetTab, pageNum) {
                    let campaignId = $('input[name="campaign_id"]').val();
                    let nonce = $('input[name="_wpnonce"]').val();

                    if (campaignId === "0" || !campaignId) return;

                    let ajaxAction = '';
                    let targetDiv = '';

                    if (targetTab === '#tab-leads') {
                        ajaxAction = 'zutalw_reload_admin_leads';
                        targetDiv = '#zutalw-leads-ajax-target';
                    } else if (targetTab === '#tab-fraud') {
                        ajaxAction = 'zutalw_reload_admin_fraud';
                        targetDiv = '#zutalw-fraud-ajax-target';
                    } else if (targetTab === '#tab-unique-leads') {
                        // Thêm logic gọi Ajax cho tab Unique
                        ajaxAction = 'zutalw_reload_unique_leads';
                        targetDiv = '#zutalw-unique-leads-ajax-target';
                    } else {
                        return;
                    }

                    $(targetDiv).css('opacity', '0.5');

                    $.post(ajaxurl, {
                        action: ajaxAction,
                        campaign_id: campaignId,
                        page: pageNum,
                        security: nonce
                    }).done(function(res) {
                        $(targetDiv).html(res).css('opacity', '1');
                    }).fail(function(xhr, status, error) {
                        console.error("AJAX Error:", error);
                        $(targetDiv).css('opacity', '1');
                    });
                }

                // --- 2. XỬ LÝ CLICK CHUYỂN TAB ---
                $('.nav-tab-wrapper a').on('click', function(e) {
                    e.preventDefault();
                    let targetTab = $(this).attr('href');

                    $('.nav-tab-wrapper a').removeClass('nav-tab-active');
                    $(this).addClass('nav-tab-active');
                    $('.zutalw-tab-content').hide();
                    $(targetTab).show();

                    // Mở rộng kiểm tra cho cả tab Unique
                    if (targetTab === '#tab-leads' || targetTab === '#tab-fraud' || targetTab === '#tab-unique-leads') {
                        loadAjaxTable(targetTab, 1);
                    }
                });

                // --- 3. XỬ LÝ CLICK NÚT PHÂN TRANG ---
                $(document).on('click', '.zutalw-page-btn', function(e) {
                    e.preventDefault();
                    let requestedPage = $(this).data('page');
                    let targetTab = $(this).data('target');
                    
                    $('html, body').animate({ scrollTop: $(targetTab).offset().top - 50 }, 300);
                    loadAjaxTable(targetTab, requestedPage);
                });

                // =========================================================
                // --- 4. SCRIPT XÂY DỰNG SEGMENT, MÀU SẮC & UPLOAD ẢNH ---
                // =========================================================
                $('.zutalw-color-picker').not('#zutalw-segment-template .zutalw-color-picker').wpColorPicker();

                $('#zutalw-segments-wrapper').sortable({ 
                    handle: '.drag-handle',
                    update: function() {
                        $('#zutalw-segments-wrapper tr').each(function(i){ $(this).find('.zutalw-sort-order').val(i); });
                    }
                });

                let segIdx = <?php echo isset($idx) ? intval($idx) : 0; ?>;
                $('#zutalw-add-segment').on('click', function() {
                    let html = $('#zutalw-segment-template').html().replace(/{{INDEX}}/g, segIdx++);
                    let $row = $(html).appendTo('#zutalw-segments-wrapper');
                    $row.find('.zutalw-color-picker').wpColorPicker();
                });

                $(document).on('click', '.zutalw-remove-segment', function() {
                    if(confirm("<?php esc_html_e('Remove this slice?', 'zuta-lucky-wheel'); ?>")) $(this).closest('tr').remove();
                });

                $(document).on('click', '.zutalw-upload-img-btn', function(e) {
                    e.preventDefault();
                    let $btn = $(this), $td = $btn.closest('td'), $input = $td.find('.zutalw-image-url');
                    let frame = wp.media({ title: 'Select Image', multiple: false }).on('select', function() {
                        let url = frame.state().get('selection').first().toJSON().url;
                        $input.val(url);
                        $td.find('.zutalw-img-preview img').attr('src', url);
                        $td.find('.zutalw-img-preview').html('<img src="'+url+'" style="max-width:100%;">');
                    }).open();
                });

                // =========================================================
                // --- 5. SCRIPT AJAX SEARCH PAGE/POST ---
                // =========================================================
                var timer;
                var $input = $('#zutalw_target_page_search');
                var $hidden = $('#zutalw_target_page_id');
                var $results = $('#zutalw_search_results');

                $('#zutalw_set_homepage').on('click', function(e){
                    e.preventDefault(); $input.val('[System] Homepage'); $hidden.val('-1'); $results.hide();
                });

                $('#zutalw_clear_page').on('click', function(e){
                    e.preventDefault(); $input.val(''); $hidden.val('0'); $results.hide();
                });

                $input.on('keyup', function() {
                    clearTimeout(timer);
                    var keyword = $(this).val().trim();
                    if (keyword.length < 2) { $results.hide(); return; }
                    $results.html('<li style="padding: 10px; color: #666; font-style: italic;">Searching...</li>').show();
                    timer = setTimeout(function() {
                        $.ajax({
                            url: ajaxurl, type: 'POST', data: { action: 'zutalw_search_posts', keyword: keyword },
                            success: function(res) {
                                if (res.success && res.data.length > 0) {
                                    var html = '';
                                    $.each(res.data, function(i, item) {
                                        html += '<li class="zutalw-result-item" data-id="' + item.id + '" data-title="' + item.text + '" style="padding: 10px; cursor: pointer; border-bottom: 1px solid #f0f0f0;">' + item.text + '</li>';
                                    });
                                    $results.html(html);
                                } else { $results.html('<li style="padding: 10px; color: #d63638;">No results found.</li>'); }
                            }
                        });
                    }, 500); 
                });

                $(document).on('click', '.zutalw-result-item', function() {
                    $input.val($(this).data('title')); $hidden.val($(this).data('id')); $results.hide();
                });

                $('<style>.zutalw-result-item:hover { background-color: #f0f6fc; color: #2271b1; }</style>').appendTo('head');
                $(document).on('click', function(e) { if (!$(e.target).closest('.zutalw-ajax-search-wrap').length) { $results.hide(); } });
            });
        </script>

        <style>
            .drag-handle { cursor: move; color: #999; text-align:center; font-size: 20px; }
            .zutalw-tab-content { margin-top: 15px; }
            .zutalw-narrow-sidebar .form-table th, .zutalw-narrow-sidebar .form-table td { display: block; width: 100%!important; padding: 5px 0; }
            .zutalw-narrow-sidebar input, .zutalw-narrow-sidebar select { width: 100%; }
            .zutalw-img-preview { width: 50px; height: 50px; background: #eee; display: flex; align-items: center; justify-content: center; overflow: hidden; border-radius: 4px; border: 1px solid #ddd; }
        </style>
        <?php
    }
    
    private function render_segment_row( $index, $data = array() ) {
        $data = wp_parse_args( $data, array(
            'id'             => 0,
            'sort_order'     => $index,
            'label'          => '',
            'bg_color'       => '#ffffff',
            'text_color'     => '#000000',
            'weight'         => 1,
            'quantity_total' => -1,
            'pool_type'      => 'basic',
            'pool_level'     => 1,
            'image_url'      => ''
        ));
        
        $name_base = "segments[{$index}]";
        ?>
        <tr>
            <td class="drag-handle">☰</td>
            <td>
                <div class="zutalw-img-preview">
                    <?php if(!empty($data['image_url'])) echo '<img src="'.esc_url($data['image_url']).'" style="max-width:100%;">'; ?>
                </div>
                <input type="hidden" name="<?php echo $name_base; ?>[image_url]" class="zutalw-image-url" value="<?php echo esc_url($data['image_url']); ?>">
                <button type="button" class="button button-small zutalw-upload-img-btn"><span class="dashicons dashicons-camera"></span></button>
            </td>
            <td>
                <input type="hidden" name="<?php echo $name_base; ?>[id]" value="<?php echo esc_attr($data['id']); ?>">
                <input type="hidden" name="<?php echo $name_base; ?>[sort_order]" class="zutalw-sort-order" value="<?php echo esc_attr($data['sort_order']); ?>">
                <input type="text" name="<?php echo $name_base; ?>[label]" value="<?php echo esc_attr($data['label']); ?>" style="width:100%" required>
            </td>
            <td><input type="text" name="<?php echo $name_base; ?>[bg_color]" class="zutalw-color-picker" value="<?php echo esc_attr($data['bg_color']); ?>"></td>
            
            <td><input type="text" name="<?php echo $name_base; ?>[text_color]" class="zutalw-color-picker" value="<?php echo esc_attr($data['text_color']); ?>"></td>
            
            <td><input type="number" name="<?php echo $name_base; ?>[weight]" value="<?php echo intval($data['weight']); ?>" style="width:60px"></td>
            <td><input type="number" name="<?php echo $name_base; ?>[quantity_total]" value="<?php echo intval($data['quantity_total']); ?>" style="width:60px"></td>
            <td>
                <select name="<?php echo $name_base; ?>[pool_level]">
                    <option value="1" <?php selected($data['pool_level'], 1); ?>>
                        <?php esc_html_e( 'Pool 1 (Basic)', 'zuta-lucky-wheel' ); ?>
                    </option>
                    <option value="2" <?php selected($data['pool_level'], 2); ?>>
                        <?php esc_html_e( 'Pool 2 (VIP)', 'zuta-lucky-wheel' ); ?>
                    </option>
                </select>
            </td>
            <td><button type="button" class="button zutalw-remove-segment" style="color:red">X</button></td>
        </tr>
        <?php
    }
}