<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://think-digitalmarketing.co.uk
 * @since      1.0.0
 *
 * @package    Think_Digital_Murder_Mystery
 * @subpackage Think_Digital_Murder_Mystery/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    Think_Digital_Murder_Mystery
 * @subpackage Think_Digital_Murder_Mystery/public
 * @author     Think Digital Marketing <hello@think-digitalmarketing.co.uk>
 */
class Think_Digital_Murder_Mystery_Public {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of the plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;

	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Think_Digital_Murder_Mystery_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Think_Digital_Murder_Mystery_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		// Enqueue Google Fonts
    wp_enqueue_style(
        'think-digital-murder-mystery-google-fonts',
        'https://fonts.googleapis.com/css2?family=Karla:ital,wght@0,200..800;1,200..800&family=Nosifer&display=swap',
        array(),
        null
    );
		
		
		wp_enqueue_style( 
    $this->plugin_name, 
    plugin_dir_url( __FILE__ ) . 'css/think-digital-murder-mystery-public.css', 
    array(), 
    time(), // use current timestamp to force reload
    'all' 
);

	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Think_Digital_Murder_Mystery_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Think_Digital_Murder_Mystery_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/think-digital-murder-mystery-public.js', array( 'jquery' ),  
    array(), 
    time(), // use current timestamp to force reload
    'all' 
);
		
		// Enqueue SweetAlert2
    wp_enqueue_script(
        'sweetalert2',
        'https://cdn.jsdelivr.net/npm/sweetalert2@11',
        array(),
        '11.0.0',
        true // Load in footer
    );

    // Enqueue your plugin’s JS and make it depend on SweetAlert2
    wp_enqueue_script(
        $this->plugin_name,
        plugin_dir_url(__FILE__) . 'js/think-digital-murder-mystery-public.js',
        array('jquery', 'sweetalert2'),
        $this->version,
        true
    );

	}

}



add_shortcode('show_murder_mystery_clues_frontend', 'show_murder_mystery_clues_frontend');
function show_murder_mystery_clues_frontend() {
    global $post;

    $active = get_post_meta($post->ID, '_murder_mystery_active', true);
    if ($active !== 'yes') return;

    $clues = get_post_meta($post->ID, '_murder_mystery_clues', true);
    if (!is_array($clues) || empty($clues)) return;

    // Your prize lookup
    $prize_name_position_lookup = get_post_meta($post->ID, 'prize_name_position_lookup', true);    
    
	
	
	$murder_mystery_reward = get_post_meta($post->ID, 'murder_mystery_reward', true);
	
	?>

	<?php
	
	echo '<div class="murder-mystery-container">';
	echo '<div class="murder-mystery-info">
    <h3 style="margin: 0 0 5px 0;" class="glitch-text" data-text="A Crime Has Been Committed!">A Crime Has Been Committed!</h3>
    <p>Uncover the clues, and solve the mystery to win a bonus!</p>
	</div>';
		
	echo '<p class="murder-mystery-reward">Bonus: ' . $murder_mystery_reward . '</p>';
	
	echo '<div class="murder-mystery-clues"><h5 style="margin: 0 0 10px 0;">The Clues You Need To Find:</h5></div>';
    echo '<div class="murder-mystery-display" style="display:flex; align-items:center; gap:10px;justify-content: center;">';

	$show_plus = false;
	
	$current_user_id = 0;
	
	$my_won_clues = array();
	
	if(is_user_logged_in()) {
		$current_user_id = get_current_user_id();		
		$tickets_won_array = get_post_meta($post->ID, 'tickets_won_array', true);
		
		foreach($tickets_won_array as $key => $tickets_won) {
			if($tickets_won['user_id'] == $current_user_id) {
				$my_won_clues[] = $tickets_won['prize_name'];
			}
		}
		
		if($my_won_clues) {
		$my_won_clues = array_unique($my_won_clues);
		}
		
		
	}
	
    foreach ($clues as $index => $clue) {
		if(empty($clue)) { continue; }
		
        $clue = sanitize_text_field($clue);
        $position = $prize_name_position_lookup[$clue] ?? null;

		$image_id = '';
		
        if ($position) {
            $image_id = get_post_meta($post->ID, 'image_prize_' . $position, true);            
        }
		
		if(empty($image_id)) {
			$image_id = get_post_meta($post->ID, '_thumbnail_id', true);
		}
		
		$image_url = wp_get_attachment_image_url($image_id, 'medium');
		
		
		if ($show_plus) {
			echo '<div class="plus-sign" style="font-size:24px; font-weight:bold;">+</div>';
		}

		$show_plus = true;
		
		$status = '🔒';
		
		if($my_won_clues) {
		if(in_array($clue, $my_won_clues)) {
			$status = '✅';
		}
		}
		
        ?>

        <div class="clue-box" style="background-image:url('<?php echo esc_url($image_url); ?>');">
            <div class="clue-text"><?php echo esc_html($clue); ?></div>
            <span class="clue-status-icon"><?php echo $status; ?></span>
        </div>

        <?php

      
    }
	
	
    echo '</div>';
	
	echo '<div style="margin-top:25px;"><button id="read-the-rules-btn" class="read-the-rules-button">Read The Rules</button></div>';
	
	echo '<div class="recent-clue-scroll-winners">';
	
	$is_active = get_post_meta($post->ID, '_murder_mystery_active', true);
    $clues = get_post_meta($post->ID, '_murder_mystery_clues', true);
	
	   if ($is_active === 'yes' && !empty($clues)) {
        

        $tickets_won_array = get_post_meta($post->ID, 'tickets_won_array', true);
        if (!empty($tickets_won_array) && is_array($tickets_won_array)) {
            // Build a clue set for easy matching
            $clues_cleaned = array_map('sanitize_text_field', array_filter($clues));
            $clue_count = count($clues_cleaned);

			
            $user_clues = [];

            // Group clues won by user
            foreach ($tickets_won_array as $entry) {
                if (empty($entry['user_id']) || empty($entry['prize_name'])) continue;

                $uid = $entry['user_id'];
                $prize = sanitize_text_field($entry['prize_name']);

                if (!isset($user_clues[$uid])) {
                    $user_clues[$uid] = [];
                }

                $user_clues[$uid][] = $prize;
            }

            $matched_users = [];

            // Check who has all clues
            foreach ($user_clues as $uid => $won_clues) {				
                $unique_won = array_unique($won_clues);
                $match = true;

                foreach ($clues_cleaned as $required_clue) {
                    if (!in_array($required_clue, $unique_won)) {
                        $match = false;
                        break;
                    }
                }

                if ($match) {
                    $matched_users[] = $uid;
                }
            }

            if (!empty($matched_users)) {
				echo '<h4>Murder solved by:</h4>';
                echo '<ul class="recent-clue-scroll-winners-loop">';
                foreach ($matched_users as $uid) {
                    $user = get_userdata($uid);
					if(empty($user)) {
						continue;
					}
                    $name = $user->first_name;
					if(empty($name)) {
						continue;
					}
					
					if($user->last_name) {
						$name .= ' ' . substr($user->last_name, 0, 1);
					}
					
                   
                    echo '<li>' . esc_html($name) . '</li>';
					
                }
                echo '</ul>';
				
				echo '<br><p><em>Who will join them?</em></p>';
				
            } else {
                echo '<p><em>No one has solved the mystery yet, be the first!</em></p>';
            }

        }
    }
	
	echo '</div>';
	
	
	echo '</div>';
}



// Add metabox
add_action('add_meta_boxes', 'add_murder_mystery_metabox');
function add_murder_mystery_metabox() {
    add_meta_box(
        'murder_mystery_metabox',
        'Murder Mystery',
        'render_murder_mystery_metabox',
        'product',
        'side',
        'default'
    );
}

// Render metabox content
function render_murder_mystery_metabox($post) {
    // Get current values
    $is_active = get_post_meta($post->ID, '_murder_mystery_active', true);
    $clues = get_post_meta($post->ID, '_murder_mystery_clues', true);
    if (!is_array($clues)) $clues = [];

    wp_nonce_field('save_murder_mystery_meta', 'murder_mystery_nonce');

    ?>
    <p>
        <label>
            <input type="checkbox" id="murder_mystery_active" name="murder_mystery_active" value="yes" <?php checked($is_active, 'yes'); ?> />
            Activate Murder Mystery Game
        </label>
    </p>


<script>
jQuery(document).ready(function($) {
    function updatePrizeOptionsInClues() {
        const prizeOptions = [];

        // 1. Collect all prize amounts (names)
        $('[id^="prize_"][id$="_amount"]').each(function() {
            const val = $(this).val().trim();
            if (val) {
                prizeOptions.push(val);
            }
        });

        // 2. Update all selects inside murder mystery clues
        $('#murder-mystery-clues select').each(function () {
            const $select = $(this);
            const currentValue = $select.val();
            const existingValue = $select.attr('value');

            $select.empty(); // clear existing options

            // Add a blank default option
            $select.append($('<option>', {
                value: '',
                text: '-- Select Prize (Optional) --'
            }));

            let existingFound = false;

            // Add all prize options
            prizeOptions.forEach(function (prize) {
                const option = $('<option>', {
                    value: prize,
                    text: prize
                });

                if (prize === currentValue || prize === existingValue) {
                    option.prop('selected', true);
                    existingFound = true;
                }

                $select.append(option);
            });

            // If existing value is set and not found in the options, add it
            if (existingValue && !existingFound) {
                $select.append($('<option>', {
                    value: existingValue,
                    text: existingValue,
                    selected: true
                }));
            }
        });
    }

    // ✅ Run it on page load
    updatePrizeOptionsInClues();

    // ✅ Re-run when any prize name is edited
    $('[id^="prize_"][id$="_amount"]').on('input', updatePrizeOptionsInClues);
});
</script>



    <div id="murder-mystery-clues" style="<?php echo ($is_active === 'yes') ? '' : 'display:none;'; ?>">
		
		<p>
			<label for="murder_mystery_reward">Mystery Reward:</label><br>
			<input type="text" style="width: 100%;" value="<?php echo get_post_meta($post->ID, 'murder_mystery_reward', true); ?>" name="murder_mystery_reward" id="murder_mystery_reward">
		</p>
		<hr>
        <?php for ($i = 1; $i <= 6; $i++): ?>
            <p>
                <label for="murder_mystery_clue_<?php echo $i; ?>">Instant Name <?php echo $i; ?>:</label><br>
               <select value="<?php echo esc_attr($clues[$i - 1] ?? ''); ?>" name="murder_mystery_clues[]" id="murder_mystery_clue_<?php echo $i; ?>" style="width:100%;" class="murder-mystery-select">
    <option value=""><?php echo $i > 3 ? 'Optional' : '-- Select Prize --'; ?></option>
    <?php
    // You can optionally pre-fill static options here if needed
    $selected_value = esc_attr($clues[$i - 1] ?? '');
    ?>
</select>

            </p>
        <?php endfor; ?>
    </div>

    <script>
        document.getElementById('murder_mystery_active').addEventListener('change', function () {
            document.getElementById('murder-mystery-clues').style.display = this.checked ? 'block' : 'none';
        });
    </script>
    <?php
	
	
	// Only show match results if the game is active and clues exist
    if ($is_active === 'yes' && !empty($clues)) {
        echo '<hr><h4>Users who matched ALL clues:</h4>';

        $tickets_won_array = get_post_meta($post->ID, 'tickets_won_array', true);
        if (!empty($tickets_won_array) && is_array($tickets_won_array)) {
            // Build a clue set for easy matching
            $clues_cleaned = array_map('sanitize_text_field', array_filter($clues));
            $clue_count = count($clues_cleaned);

			
            $user_clues = [];

            // Group clues won by user
            foreach ($tickets_won_array as $entry) {
                if (empty($entry['user_id']) || empty($entry['prize_name'])) continue;

                $uid = $entry['user_id'];
                $prize = sanitize_text_field($entry['prize_name']);

                if (!isset($user_clues[$uid])) {
                    $user_clues[$uid] = [];
                }

                $user_clues[$uid][] = $prize;
            }

            $matched_users = [];

            // Check who has all clues
            foreach ($user_clues as $uid => $won_clues) {				
                $unique_won = array_unique($won_clues);
                $match = true;

                foreach ($clues_cleaned as $required_clue) {
                    if (!in_array($required_clue, $unique_won)) {
                        $match = false;
                        break;
                    }
                }

                if ($match) {
                    $matched_users[] = $uid;
                }
            }

            if (!empty($matched_users)) {
                echo '<ul>';
                foreach ($matched_users as $uid) {
                    $user = get_userdata($uid);
					if(empty($user)) {
						continue;
					}
                    $name = $user->first_name ?? $user->display_name;
                    $email = $user->user_email ?? '';
                    echo '<li><a target="_blank" href="/wp-admin/admin.php?page=instant-prize-history&paged=1&competition_filter=18035&email='. urlencode($email) . '&type_filter=instant_win">' . esc_html($name) . ' (' . esc_html($email) . ')</a></li>';
                }
                echo '</ul>';
            } else {
                echo '<p><em>No users have matched all clues yet.</em></p>';
            }

        } else {
            echo '<p><em>No ticket win data found.</em></p>';
        }
    }
	
}

// Save metabox data
add_action('save_post_product', 'save_murder_mystery_meta');
function save_murder_mystery_meta($post_id) {
    if (!isset($_POST['murder_mystery_nonce']) || !wp_verify_nonce($_POST['murder_mystery_nonce'], 'save_murder_mystery_meta')) {
        return;
    }

    $is_active = isset($_POST['murder_mystery_active']) ? 'yes' : 'no';
    update_post_meta($post_id, '_murder_mystery_active', $is_active);

    if ($is_active === 'yes' && isset($_POST['murder_mystery_clues'])) {
        $clues = array_map('sanitize_text_field', $_POST['murder_mystery_clues']);
        update_post_meta($post_id, '_murder_mystery_clues', $clues);
    } else {
        delete_post_meta($post_id, '_murder_mystery_clues');
    }
	
	if(isset($_POST['murder_mystery_reward'])) {
		update_post_meta($post_id, 'murder_mystery_reward', $_POST['murder_mystery_reward']);
	}
	
}



