<?php
/*
Plugin Name: Instant Emoji Reactions
Plugin URI: https://profiles.wordpress.org/usamakhalid14/
Description: Add emoji reactions to posts and custom post types, allowing both logged-in and guest users to react.
Version: 1.0.2
Requires at least: 5.0
Requires PHP: 7.4
Author: Usama Khalid
Author URI: https://www.linkedin.com/in/usama-khalid-84677720b/
License: GPL-2.0+
License URI: https://opensource.org/licenses/GPL-2.0
Text Domain: instant-emoji-reactions
*/

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('INSTANT_EMOJI_REACTIONS_VERSION', '1.0');

// Enqueue scripts for AJAX
add_action('wp_enqueue_scripts', 'instant_emoji_reactions_enqueue_assets');
function instant_emoji_reactions_enqueue_assets() {
    wp_enqueue_script('emoji-reactions-js', plugin_dir_url(__FILE__) . 'js/emoji-reactions.js', ['jquery'], INSTANT_EMOJI_REACTIONS_VERSION, true);

    // Localize the script with the guest ID if the user is logged out
    wp_localize_script('emoji-reactions-js', 'emojiReactions', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('instant_emoji_reaction_nonce'),
        'guest_id' => instant_emoji_reactions_generate_guest_id()  // Pass the guest ID to the JS script
    ]);

    wp_enqueue_style('emoji-reactions-css', plugin_dir_url(__FILE__) . 'css/emoji-reactions.css', [], INSTANT_EMOJI_REACTIONS_VERSION);
}

// Shortcode to display emoji reactions
function instant_emoji_reactions_shortcode($atts) {
    $post_id = get_the_ID();  // Get the current post ID
    $user_id = is_user_logged_in() ? get_current_user_id() : (isset($_COOKIE['guest_id']) ? sanitize_text_field(wp_unslash($_COOKIE['guest_id'])) : instant_emoji_reactions_generate_guest_id());

    $reactions = get_option('instant_emoji_reactions', ['😀', '😍', '😢', '😡', '👍', '👎']);  // Get the emoji options

    // Get all reactions for this post
    $reaction_meta = get_post_meta($post_id, '_emoji_reactions', true);
    $reaction_counts = [];

    // Initialize reaction counts
    foreach ($reactions as $index => $emoji) {
        $reaction_counts[$index + 1] = 0;
    }

    // Count reactions
    if (is_array($reaction_meta)) {
        foreach ($reaction_meta as $user => $reaction_id) {
            if (isset($reaction_counts[$reaction_id])) {
                $reaction_counts[$reaction_id]++;
            }
        }
    }

    // Get the current user's reaction
    $user_reaction = isset($reaction_meta[$user_id]) ? $reaction_meta[$user_id] : null;

    ob_start();
    echo '<div class="emoji-reactions-container">';
    foreach ($reactions as $index => $emoji) {
        $reaction_id = $index + 1;
        $class = 'emoji-reaction' . ($user_reaction == $reaction_id ? ' active' : ' inactive');
        echo '<span class="' . esc_attr($class) . '" data-post-id="' . esc_attr($post_id) . '" data-reaction-id="' . esc_attr($reaction_id) . '">';
        echo '<span class="emoji">' . esc_html($emoji) . '</span>';
        echo '<div class="reaction-count">' . esc_html($reaction_counts[$reaction_id] ?? 0) . '</div>';
        echo '</span>';
    }
    echo '</div>';
    return ob_get_clean();
}
add_shortcode('instant_emoji_reactions', 'instant_emoji_reactions_shortcode');

// AJAX handler to store emoji reaction
add_action('wp_ajax_store_instant_emoji_reaction', 'instant_emoji_reactions_store_reaction');
add_action('wp_ajax_nopriv_store_instant_emoji_reaction', 'instant_emoji_reactions_store_reaction');

function instant_emoji_reactions_store_reaction() {
    // Verify the nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'instant_emoji_reaction_nonce')) {
        wp_send_json_error('Invalid nonce.');
        return;
    }

    $post_id = isset($_POST['post_id']) ? intval(wp_unslash($_POST['post_id'])) : 0;
    $reaction_id = isset($_POST['reaction_id']) ? sanitize_text_field(wp_unslash($_POST['reaction_id'])) : '';
    $user_id = is_user_logged_in() 
        ? get_current_user_id() 
        : (isset($_COOKIE['guest_id']) ? sanitize_text_field(wp_unslash($_COOKIE['guest_id'])) : instant_emoji_reactions_generate_guest_id());

    if (!$post_id || !$reaction_id) {
        wp_send_json_error('Invalid post or reaction ID.');
        return;
    }

    // Get existing reactions
    $reaction_meta = get_post_meta($post_id, '_emoji_reactions', true);
    if (!is_array($reaction_meta)) {
        $reaction_meta = [];
    }

    // Update or add the user's reaction
    $reaction_meta[$user_id] = $reaction_id;
    update_post_meta($post_id, '_emoji_reactions', $reaction_meta);

    // Calculate reaction counts
    $reactions = get_option('instant_emoji_reactions', ['😀', '😍', '😢', '😡', '👍', '👎']);
    $reaction_counts = [];

    foreach ($reactions as $index => $emoji) {
        $reaction_counts[$index + 1] = 0;
    }

    foreach ($reaction_meta as $user => $reaction) {
        if (isset($reaction_counts[$reaction])) {
            $reaction_counts[$reaction]++;
        }
    }

    wp_send_json_success([
        'message' => 'Reaction saved.',
        'reaction_counts' => $reaction_counts
    ]);
}

// Add settings menu for Instant Emoji Reactions in the WordPress dashboard
add_action('admin_menu', 'instant_emoji_reactions_menu');
function instant_emoji_reactions_menu() {
    add_menu_page(
        'Instant Emoji Reactions Settings',
        'Instant Emoji Reactions',
        'manage_options',
        'instant-emoji-reaction-settings',
        'instant_emoji_reactions_settings_page',
        'dashicons-smiley',
        20
    );
}

// Add settings link to the plugin action links
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'instant_emoji_reactions_add_settings_link');
function instant_emoji_reactions_add_settings_link($links) {
    $settings_link = '<a href="admin.php?page=instant-emoji-reaction-settings">Settings</a>';
    array_unshift($links, $settings_link);
    return $links;
}

// Settings page callback with emoji dropdown
function instant_emoji_reactions_settings_page() {
    if (isset($_POST['instant_emoji_reactions'])) {
        $nonce = isset($_POST['instant_emoji_reactions_nonce']) ? sanitize_text_field(wp_unslash($_POST['instant_emoji_reactions_nonce'])) : '';
        if (empty($nonce) || !wp_verify_nonce($nonce, 'instant_emoji_reactions_nonce_action')) {
            die('Nonce verification failed');
        }

        $instant_emoji_reactions = isset($_POST['instant_emoji_reactions']) ? array_map('sanitize_text_field', wp_unslash($_POST['instant_emoji_reactions'])) : [];
        update_option('instant_emoji_reactions', $instant_emoji_reactions);

        echo '<div class="updated"><p>Emojis updated successfully!</p></div>';
    }

    $reaction_options = ['😀', '😍', '😢', '😡', '👍', '👎', '😂', '👏', '🎉', '🙏', '❤️', '🎈'];
    $reactions = get_option('instant_emoji_reactions', ['😀', '😍', '😢', '😡', '👍', '👎']);

    ?>
    <div class="wrap">
        <h1>Emoji Reactions Settings</h1>
        <form method="post" action="">
            <?php wp_nonce_field('instant_emoji_reactions_nonce_action', 'instant_emoji_reactions_nonce'); ?>
            <table class="form-table">
                <?php foreach ($reactions as $index => $emoji) : ?>
                    <tr>
                        <th scope="row">Emoji <?php echo esc_html($index + 1); ?></th>
                        <td>
                            <select name="instant_emoji_reactions[]">
                                <?php foreach ($reaction_options as $option) : ?>
                                    <option value="<?php echo esc_attr($option); ?>" <?php selected($emoji, $option); ?>>
                                        <?php echo esc_html($option); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </table>
            <?php submit_button('Save Emojis'); ?>
        </form>

        <!-- Instructions for using the shortcode -->
        <div class="emoji-reactions-instructions">
            <h2>How to Use Emoji Reactions on Your Website</h2>
            <p>To display emoji reactions on any post or custom post type, simply add the following shortcode to the content of your post, page, or widget:</p>
            <pre>[instant_emoji_reactions]</pre>
            <p>This shortcode will display the emoji reactions below the content of the post, allowing both logged-in users and guests to react.</p>
        </div>

        <!-- Video Tutorial Section -->
        <div class="emoji-reactions-video-tutorial">
            <h2>Video Tutorial</h2>
            <p>If you're unsure about how to use emoji reactions on your site, please watch the tutorial video below:</p>
            <video width="600" controls>
                <source src="<?php echo esc_url(plugin_dir_url(__FILE__)); ?>video/tutorial.mp4" type="video/mp4">
                Your browser does not support the video tag.
            </video>
        </div>
    </div>
    <?php
}

// Function to generate a random guest ID and store it in a cookie
function instant_emoji_reactions_generate_guest_id() {
    if (!is_user_logged_in()) {
        if (!isset($_COOKIE['guest_id'])) {
            $guest_id = 'guest' . wp_rand(1000000000000, 9999999999999);
            setcookie('guest_id', $guest_id, time() + (365 * DAY_IN_SECONDS), COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
            $_COOKIE['guest_id'] = $guest_id;
            return $guest_id;
        } else {
            return sanitize_text_field(wp_unslash($_COOKIE['guest_id']));
        }
    }
    return null;
}